Gandalf Gandalf - 1 month ago 6
MySQL Question

Get all mysql selected rows into an array

I am wondering if there a function in php that can allow me put all my selected data in an array .Currently i am using mysql_fetch_array and as i have read in the manual,that function won't fetch every record in the table.

$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_array($result);

echo json_encode($array);

Answer

I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:

while($row = mysql_fetch_assoc($result)){
     $json[] = $row;
}

echo json_encode($json);

If you switched to MySQLi you could do:

$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );