aryaxt
aryaxt

Reputation: 77636

PHP, JSON, and MySQL

What is the easiest way to retrieve data from the database, and convert the data to a JSON String?

Is there any kind of helper class? or am I supposed to loop through the columns in my dataset to create the JSON string?

Upvotes: 2

Views: 1669

Answers (5)

BillRobertson42
BillRobertson42

Reputation: 12883

If you use the json_encode function then you're depending on somebody else's interpretation of the right way to format the json. Which means that you might come out with weird json, or have to contort your classes in evil ways to make the json come out right.

Just something to think about.

Upvotes: 0

RolandasR
RolandasR

Reputation: 3046

Make an array from mySQL, and json_encode() it

Upvotes: 4

Alexander Sagen
Alexander Sagen

Reputation: 4038

Have you seen the json_encode() function? It takes an array as input and outputs JSON. So the most basic would be a two-dimensional array representing your table as input to json_encode

Upvotes: 0

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181450

Yes, use PHP's functions to handle JSON encoding.

Here's an example I got from this SO question:

$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163308

You can use the json_encode function to convert a native PHP array or stdClass object to it's corresponding JSON representation:

$result = $db->query('SOME QUERY');
$set = array();
if($result->num_rows) {
   while($row = $result->fetch_array()) {
      $set[] = $row;
   }
}
echo json_encode($set);

Upvotes: 5

Related Questions