Malathi N
Malathi N

Reputation: 13

How to fetch PHP database values in Json?

I have to create Matrix tree view in my project. So am plan to use json. My question is how to fetch PHP values in Json ?. I did static matrix tree but i want dynamic. Thank you for advance.

My code is following:

<?php
include('db.php');
$select = mysql_query("select * from table1");
while($row = mysql_fetch_array($select))
{
?>
{
 "name": "A", // Here database values come $row['name']; 
 "children": [



  {
   "name": "B",
   "children": [
    {"name": "B-1"}
   ]
  },
  {
   "name": "C",
   "children": [
    {"name": "C-1", "size": 1082},

    {"name": "C-2", "size": 1681}
   ]
  },



  {
   "name": "D",
   "children": [
    {
     "name": "D-1",
     "children": [
      {"name": "D-1 1", "size": 1302},


      {"name": "D-1 2", "size": 6703}
     ]
    },

   {"name": "D-2", "size": 16540}
   ]
  }
 ]
}
<?php
}
?>

Upvotes: 0

Views: 93

Answers (2)

DevDonkey
DevDonkey

Reputation: 4880

In this example Im using the mysqli driver. Do not use the mysql driver.

you just need to convert your output data into a json object.

Its possible to extract all the rows at once which is going to give you a marginally less overhead.

$data = mysqli_fetch_all($select); // returns everything in an associative array
$json_data = json_encode($data); // converts that array to json.

if you need specific keys, then manipulate your query to rename columns as necessary eg.

$query = "select name as firstname from ....";

Upvotes: 1

Glubus
Glubus

Reputation: 2855

You can just retrieve data from your database and store it in arrays like you normally would. Then call PHP's built in function json_encode() to transform your PHP array into json (assuming your PHP array is well formed (which should be the case if you get it out of a database)).

You could argue that this is slower because you're iterating over the data twice instead of once, but it shouldn't matter, the complexity remains the same.

Upvotes: 0

Related Questions