Parsing json in php I get a json string from a page, convert it to a json Array, and insert it into the database, but all the inserted values are null, i'm sure I can get the json string.
Include_once ('Inc/conn. php ');
$ Json_string = $ _ REQUEST ["visitor"];
$ AddressInfo = json_decode ($ json_string, TRUE );
$ Name = $ addressInfo ['name'];
$ Idcard = $ addressInfo ['idcrd'];
$ Visitedphone = $ addressInfo ['visitedphone'];
$ Address = $ addressInfo ['address'];
$ Visitedorganization = $ addressInfo ['visitedorganization'];
Echo "1 $ visitedphone ";
Echo "2 $ address ";
Echo "3 $ visitedorganization ";
$ SQL = "insert into adress_list (name, idcrad, tel, adress, visitorganization) values ('$ name',' $ idcard ',' $ visitedphone ',' $ address ', '$ visitedorganization ');";
$ Rest = 0;
$ Rest = mysql_query ($ SQL );
Echo mysql_error ();
If ($ rest ){
Echo "Congratulations, upload successful! ";
} Else {
Echo "Upload failed. please upload again! ";
}
// Close the database
Mysql_close ($ con );
?>
This is my code...
Reply to discussion (solution)
Print_r ($ addressInfo );
Take a look
Print_r ($ addressInfo); what is the result?
$ AddressInfo = json_decode ($ json_string, TRUE );
If it is null, it is estimated that the value of $ json_string is not in json format. check here.
It is probably because of quotation marks. Escape is required. Otherwise, the SQL statement is incorrectly saved.
$sql="insert into adress_list(name,idcrad,tel,adress,visitorganization)values('".mysql_real_escape_string($name)."','".mysql_real_escape_string($idcard)."','".mysql_real_escape_string($visitedphone)."','".mysql_real_escape_string($address)."','".mysql_real_escape_string($visitedorganization)."'); ";
$ AddressInfo; // check whether the value is null and execute the following logic.
$ AddressInfo; value during debugging
How can I get the value of name and idcard? I use $ name = $ addressInfo [0] ['name']. an error is returned.
$ Name = $ addressInfo ['Visitors '] [0] ['name.
The array is like this.
$ AddressInfo = array ('Visitors '=> array ('visitedphone'' => '20140901', 'organization' => 'Zhejiang Emy ', 'phone' => '123', 'address' => 'no. 38 Zhejiang University Road, Hangzhou', 'name' => 'Zhang San', 'visitedname' => 'Li Zong ', 'idcard' => '000000', 'visitedorganization' => 'Hangzhou Network Technology Co., Ltd '),));
The number is as follows: $ name = $ addressInfo ['name'];
Apparently not.
A little less foreach, you will see it.
It should be written like this
$ AddressInfo = json_decode ($ json_string, TRUE );
$ AddressInfo = ['Visitors '] [0];
Here is your original code.
Are you obtaining an object, not an array?
$ Name = $ addressInfo ['Visitors '] [0] ['name.
Thank you.