How to use the json_decode/json_encode in PHP?
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.
Here is my 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_enco开发者_如何转开发de($output));
Where is the problem?
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)
Another problem with your specific code is that you first output something else:
echo $username.$password;
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));
I would think there may be another level in the JSON-encoded data ($a
). Does your echo statement show the correct username and password? If not, place var_dump($b);
after your
$b = json_decode($a);
statement.
Replace the below two lines to the following.
Your original lines:
$username=$b->{'username'};
$password=$b->{'password'};
New lines:
$username=$b->username;
$password=$b->password;
After the replacement, check if it's working or not.
精彩评论