How to return data from MySQL to php file as JSON?

I need to return data from MySQL table to php file as JSON. Here is my code for connecting to mysql and getting data from it. How now I can return it as JSON.

<?php
    $username = "user";
    $password = "********";
    $hostname = "localhost";    
    $dbh = mysql_connect($hostname, $username, $password) 
        or die("Unable to connect to MySQL");
    print "Connected to MySQL<br>";
    $selected = mysql_select_db("spec",$dbh) 
        or die("Could not select first_test");
    //$rows = array();  

    $query = "SELECT * FROM user_spec"; 
    $result=mysql_query($query);

    //mysql_close($dbh);
    ?>

Under is the complete stack that I have to implement. For step 3, I dynamically process the list using user inputs, although it does not use any engine, it uses input values ​​directly, so I have to see how to do this when I receive JSON data. I lay the stack so that you people can kindly see this, which I should do when I can possibly help me.

  • user loads an HTML page
  • the page makes an ajax call and receives the parameters as JSON (either it already exists in the database, or a new set of parameters is generated)
  • json JS- (PURE )
  • -
  • JSON POST
  • JSON ( ). 4, .
+2
3

, user_spec, json_encode:

<?php
$username = "user";
$password = "********";
$hostname = "localhost";    
$dbh = mysql_connect($hostname, $username, $password) 
    or die("Unable to connect to MySQL");

//print "Connected to MySQL<br>";

$selected = mysql_select_db("spec",$dbh) 
    or die("Could not select first_test");

$query = "SELECT * FROM user_spec"; 
$result=mysql_query($query);

echo json_encode(mysql_fetch_assoc($result));

?>

.

PHP, json_encode PHP Manual .

+3
+2

If you are not like me, using the tiredness of the old version of Symfony (for your sake, hopefully not!) Your answer json_encode Zend and CodeIgniter have similar other simple methods.

If you are not lucky enough to access this, you can create it manually through the foreach loop.

You can check your JSON strings using JSONlint

+1
source

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


All Articles