How can I return json from my specific SQL query?

I have the following php code:

<?php
$servername = "host";
$username = "user";
$password = "passw";
$dbname = "dbname";

$conn3 = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

$conn3->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$q3 = $conn3->prepare("SELECT c.one, c.two FROM table c");
    $q3->execute();
if($q3->rowCount()>0)
{
    $check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
    $arr = array();
    foreach ($check3 as $row) {
    $arr[] = $row;
     //how can I return json format here?
    }   
}
$conn2 = null;
?>

and this query returns pairs of elements. But how can I change the code above to get the json format of the elements like:

{key1: OSO; key2: AIKA} etc.

so that I can use it later in the jquery file to print it with the following fuction:

$.getJSON('list.php', function(json) {
    //assuming list.php resides with list.html directory
    //console.log(json)
      console.log(json.result.key1);
       console.log(json.result.key2);

    });

thank!

+4
source share
1 answer

Change

SELECT c.one, c.two FROM table c

to

SELECT c.one as key1, c.two as key2 FROM table c

Then encapsulate the results in json (after foreach):

echo json_encode(array(
    'result'=>$arr
));

But you will most likely need a loop through them in jquery.
Your json output will look something like this:

result: [
    {'key1': 'asd', 'key2': 'qwe'},
    [...]
    {'key1': 'asd', 'key2': 'qwe'}
]

Scroll them like this:

//first, see how it looks:
console.log(json.result);
jQuery.each( json.result, function( i, subresult ) {
    console.log(subresult);
    // you should be able to use: subresult.key1
});
+2
source

All Articles