I am making a simple web app. In one part of it, I want PHP to execute a SQL command and send the entire result to JavaScript via AJAX.
This is the code:
$meta_query = json_encode(mysql_fetch_row(mysql_query("SELECT * from meta")));
The problem here is that I am only getting the very first row as the result and not the other ones.
I tried:
$meta_query = json_encode(mysql_query("SELECT * from meta"));
But that's giving me null
.
What should I do to get the whole result and that too in json format?
You need to fetch all rows in a loop:
$rows = array();
$result = mysql_query("SELECT * from meta");
if($result){
while($row = mysql_fetch_row($result)){
$rows[] = $row;
}
}
echo json_encode($rows);
Side note: the MySQL library is deprecated, you should consider upgrading to a modern API such as MySQLi or PDO. PDO has a built in function to get all rows:
$result = $pdo->query('SELECT * FROM meta');
$rows = $reuslt->fetchAll(PDO::FETCH_NUM);
try this
$meta_query = json_encode(mysql_fetch_array(mysql_query("SELECT * from meta")));