I am using MySQL to store a list of items on a database, and I am trying to retrieve all of the items from a single table. The connection part is working fine, and retrieving items seems to work well, but I cannot json_encode a list of items.
// Executes SQL query on the database specified by $con
$sql = "SELECT * FROM productlist";
$query = mysqli_query($con, $sql) or die(nl2br("\n Failed to execute query"));
// Retrieves all the rows returned by the SQL query
$rows = array();
while($r = mysqli_fetch_assoc($query)) {
$rows[] = $r;
}
echo json_encode($rows[0]); // test whether retrieval works
// Displays rows in content-type JSON and in PRETTY_PRINT
header('Content-Type: application/json');
echo json_encode($rows, JSON_PRETTY_PRINT);
Here is the code. The json_encode of rows[0] works well. However, when I comment it out and try to do the same with rows, it just returns nothing.
It's not even returning an error, it executes well, it's just that the json_encode function returns nothing at all when I try it with rows.
What am I doing wrong?