Tomas Katz Tomas Katz - 6 months ago 35
PHP Question

MySQLi database tables to JSON - need template

I saw a lot of examples on the net to how to extract a DB query result into JSON, but none of them really worked.

I need a PHP template of a few lines that will retrieve a table and convert it to JSON, echoing back to the client a string of JSON that I can parse on the client side.

I need to use this template for a get request using JavaScript XHR.
Since I'm mostly programing client side, I'm running into some difficulties building this script.
I would appreciate your help and will learn greatly from it :)

Answer

You can use any Database connection you like. MySQLi, in this case, adapted from this example:

$mysqli->real_query("SELECT * FROM test ORDER BY id ASC");
$res = $mysqli->use_result();

$orders = array();

while ($row = $res->fetch_assoc()) {
    $orders[$row['id']] = $row;
}

And simply use json_encode to generate a JSON string:

$json_string = json_encode($orders);

Shouldn't be much more difficult than that.

Comments