titlu titlu - 3 months ago 13
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 :

<?php
$dbhost = "localhost";
$username = "root";
$password = "";
mysql_connect($dbhost,$username,$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);
if($result==FALSE)
{
die(mysql_error());
}
while($row = mysql_fetch_array($result))
{
$all_result[] = $row;
}
header('Content-Type: application/json');
$jsondata = json_encode($all_result);echo $jsondata;
mysql_close();
?>


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

[{"0":"1","id":"1","1":"mon","Name":"mon","2":"26","Age":"26","3":"F","Gender":"F"}]


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 ?

Answer

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))

or

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

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

Comments