How can I get all mysql table values ​​in JSON from a PHP script?

This is a php script that retrieves table values ​​from mysql (single row). and echoes it like 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 an HTML file for receiving and printing 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> >
+3
source share
3 answers

Your PHP should actually collect all the lines:

$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 should look at each of the lines.

$.getJSON("/whatever.php", function(jsonData) { 
   for (var x = 0; x < jsonData.length; x++) {
      alert(jsonData[x].options);
   }
});
+4
source

mysql_fetch_assoc . :

$data = array();
while ($row = mysql_fetch_assoc($result)) {
    // add some or all of $row to the $data array
}
echo json_encode($data);
0
<?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);

    $_ResultSet = array();

    while ($row = mysql_fetch_assoc($result)) {
       $_ResultSet[] = $row;
    }
       echo json_encode($_ResultSet); 
?>

and your jQuery will look like this:

$.getJSON("/yourscript.php", function(data) {
    $.each(data, function(i, j) {
        // use: j.columnName
    });
});

Good luck.

0
source

Source: https://habr.com/ru/post/1770386/


All Articles