Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all values of a mysql table in JSON from a php script?

This is php script that fetches a table values from mysql (one row). & echoes it as JSON

<?php  
      $username = "user";  
      $password = "********";  
      $hostname = "localhost";  
      $dbh = mysql_connect($hostname, $username, $password) or die("Unable to 
      connect to MySQL");  
      $selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");  
      $query = "SELECT * FROM user_spec";  
      $result=mysql_query($query);     
      $outArray = array(); 
      if ($result) { 
      while ($row = mysql_fetch_assoc($result)) $outArray[] = $row; 
       } 
      echo json_encode($outArray);  
?> 

this is HTML file to receive & print json data.
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> //$('document').ready(function() {

    function Preload() {
    $.getJSON("http://localhost/conn_mysql.php", function(jsonData){  
    $.each(jsonData, function(i,j)
    { alert(j.options);});
    });} 

// });
    </script></head>

    <body onLoad="Preload()">
    </body>

</html> >
like image 274
XCeptable Avatar asked Oct 19 '10 19:10

XCeptable


2 Answers

Your PHP needs to actually put all the rows together:

$query = "SELECT * FROM user_spec"; 
$result=mysql_query($query);    
$outArray = array();
if ($result) {
  while ($row = mysql_fetch_assoc($result)) $outArray[] = $row;
}
echo json_encode($outArray);

Your Javascript needs to look at each of the rows..

$.getJSON("/whatever.php", function(jsonData) { 
   for (var x = 0; x < jsonData.length; x++) {
      alert(jsonData[x].options);
   }
});
like image 57
Fosco Avatar answered Oct 12 '22 02:10

Fosco


mysql_fetch_assoc will only return a single row from the database. You will need a loop to retrieve all rows:

$data = array();
while ($row = mysql_fetch_assoc($result)) {
    // add some or all of $row to the $data array
}
echo json_encode($data);
like image 21
Richard Fearn Avatar answered Oct 12 '22 03:10

Richard Fearn