4

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 modify the code above to get the json format of the elements as:

{key1:OSO;key2:AIKA} etc.

so that I can use it later in a 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);

    });

thanks!

1 Answer 1

2

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 the foreach):

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

But you will most likely need to loop trough them in jquery.
Your json output will be something like:

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

Loop trough them like:

//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
});
Sign up to request clarification or add additional context in comments.

4 Comments

hey thanks, could you give me some example of how to loop through them in jquery then? thanks!
Thanks, I did if($q3->rowCount()>0) { $check3 = $q3->fetchAll(PDO::FETCH_ASSOC); $arr = array(); foreach ($check3 as $row) { $arr[] = $row; } echo json_encode( 'result'=>$arr ); } but now I get the error Parse error: syntax error, unexpected T_DOUBLE_ARROW and I'm not sure what's the problem here :|
My bad. It's json_encode(array('result'=>$arr)); I'm on my phone
Hey @Alex, thanks for your dedication though! Your solution worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.