titlu titlu - 5 months ago 16
Ajax Question

Why my json_encode is not giving proper value in PHP

I am trying to receive data from database based on the name entered by user, everything works fine I do see the value on screen and no error Here is the php code :

$dbhost = "localhost";
$username = "root";
$password = "";
@mysql_select_db("trynew") or die(mysql_error());
$user ="mon";
$query = "SELECT * FROM trynewtable where name = '$user' ";
$all_result = array();
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
$all_result[] = $row;
header('Content-Type: application/json');
$jsondata = json_encode($all_result);echo $jsondata;

but the output that I see on the html div is :


Actual data stored in the database is :
The actual data in the database

enter image description here

Kindly let me know what am I doing wrong ?


You are using mysql_fetch_array() which will return both the numerically keyed and associative array of data in your database. Either use mysql_fetch_assoc() or mysql_fetch_array() with MYSQL_ASSOC as the second parameter to get only the associative array.

while($row = mysql_fetch_assoc($result))


while($row = mysql_fetch_array($result, MYSQL_ASSOC))

FYI, the mysql_ API is deprecated and was removed in PHP 7.