如何使用json_de code / json_en $ C $在PHP C吗? [英] How to use the json_decode/json_encode in PHP?

查看:130
本文介绍了如何使用json_de code / json_en $ C $在PHP C吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到在PHP中的一个问题。我试图通过从Android的用户名/密码,并检查通过PHP MySQL中的价值。当使用 json_de code json_en code json_de $ C $ ç的作品,但 json_en code 不起作用。但是,当我删除 json_de code json_en code 的作品,但我想他们两个人在我的计划工作。

I am getting a problem in PHP. I am trying to pass the username/password from Android and checking the value in MySQL through PHP. While using json_decode and json_encode, json_decode works but json_encode does not work. But when I remove the json_decode, json_encode works, but I want both of them to work in my program.

下面是我的code:

$a = $_POST['userpwd_value']; //Accesing the value from Android.

$b = json_decode($a); //Decoding android value using JSON.

$username = $b->{'username'}; //Assigning username from android to a variable.
$password = $b->{'password'}; //Assigning password from android to a variable.

echo $username.$password;

$check = mysql_query("select username,password from user where id=1");
$row = mysql_fetch_assoc($check);

//if($row['username']==$username && $row['password']==$password)
    $output[]=$row;
//else
    //$output[]=array("value"=>"false");
print(json_encode($output));

问题出在哪里?

推荐答案

json_en $如果变量内容不正确的UTF-8序列C $ç 失败。如果数据库使用的字符集的另一个,变量包含特殊字符,那么你应该得到的错误。 (提高 的error_reporting 水平或检查的 json_last_error 找出)

json_encode fails if the variable content is not correctly UTF-8 sequenced. If your database uses another charset, the variables contain special characters, then you should get an error there. (raise the error_reporting level or check json_last_error to find out)

与您的特定code的另一个问题是,你第一个输出别的东西:

Another problem with your specific code is that you first output something else:

 echo $username.$password;

这将无效JSON输出作为一个整体。如果你已经领先的垃圾,你的浏览器不会去code正确返回的变量。也不要忘记使用标题(内容类型:应用程序/ JSON)与你的结果发送适当的头;

This will invalidate the JSON output as a whole. If you have leading garbage, your browser will not decode the returned variables correctly. Also don't forget to send the appropriate header with your result usingheader("Content-Type: application/json");

  $b=json_decode($_POST['userpwd_value']); 
  $username=$b->{'username'}; 
  $password=$b->{'password'};

  $check = mysql_query("select username,password from user where id=1");
  $row = mysql_fetch_assoc($check);
  $row = array_map("utf8_encode", $row);

  if ($row['username']==$username && $row['password']==$password) {
      $output[] = $row;
  } else {
      $output[] = array("value"=>"false");
  }
  header("Content-Type: application/json");
  print(json_encode($output));

这篇关于如何使用json_de code / json_en $ C $在PHP C吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆