Reputation: 880
I'm trying to query a database using PHP script and pass JSON string. I'm using this script from jQuery Ajax.
<?php
$con = mysqli_connect("localhost","root","password","test") or die("Some error occurred during connection " . mysqli_error($con));
$strSQL = "SELECT name,id from build";
$query = mysqli_query($con, $strSQL);
$builder_json=array();
$row_array=array();
while($result = mysqli_fetch_array($query))
{
// $builder_json[]=$result['name'].":".$result['id'];
$row_array['name'] = $result['name'];
$row_array['id'] = $result['id'];
array_push($builder_json[],$row_array);
}
echo json_encode($builder_json);
mysqli_close($con);
?>
Now if the data fetched is like :
Name - A,B
Id - 1,2
I want JSON string to be like - {"A":"1","B":"2"}; With the above code I get NULL . What is the mistake I have done
Upvotes: 0
Views: 35
Reputation: 5090
You don't need the [] after your variable in your array_push call
//array_push($builder_json[],$row_array);
array_push($builder_json,$row_array);
Otherwise it gives the following error :
Warning: array_push() expects parameter 1 to be array, null given on line
Upvotes: 1