Cooolranjan Cooolranjan - 6 months ago 10
Javascript Question

Not able to generate json data after fetching rows by alias in mysql

I am fetching rows from two tables through JOIN and by using alias.but it's not creating json data after assigning rows to json array.

Here is code;

$personal = $db->prepare('select pd.Id,pd.FirstName,pd.MiddleName,pd.LastName,pd.Gender,pd.Location,pd.Email,bd.BookTitle,bd.BookGenre,bd.BookWriter,bd.BookDescription from personaldetails pd,bookdetails bd where pd.Id = bd.UserId ORDER BY pd.Id DESC');

$personal->execute();
$json_data=array();
$id;


foreach($personal as $row)//foreach loop
{

$json_array['id']=$row['pd.Id'];
$json_array['FirstName']=$row['pd.FirstName'];
$json_array['MiddleName']=$row['pd.MiddleName'];
$json_array['LastName']=$row['pd.LastName'];
$json_array['Gender']=$row['pd.Gender'];
$json_array['Location']=$row['pd.Location'];
$json_array['Email']=$row['pd.Email'];
$json_array['Mobile']=$row['pd.Mobile'];
$json_array['BookTtile']=$row['bd.BookTitle'];
$json_array['BookGenre']=$row['bd.BookGenre'];
$json_array['BookWriter']=$row['bd.BookWriter'];
$json_array['BookDescription']=$row['bd.BookDescription'];

//here pushing the values in to an array
array_push($json_data,$json_array);
}

header('Content-type: application/json');
echo json_encode($json_data);


Thanks in advance!

Answer

Because you forget to fatch data form your query result.

Use fetch_assoc() to fetch data and

$personal->execute();
$json_data=array();
 while ($row = $personal->fetch_assoc()) {// fetch data from query
     $json_array['id']=$row['Id']; // don't use table name before ID
    $json_array['FirstName']=$row['FirstName'];// don't use table name FirstName
...................
}
Comments