Skip to content
Advertisement

Displaying SQL result in JSON and parse data using Javascript. Seperate text from [{:,}]

<?php
$pdo = new PDO("mysql:dbname=sample;host=localhost", "admin", "passwd");        
$statement = $pdo->prepare("SELECT first_name, last_name FROM accounts WHERE account_id='1'");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo "$json";
?>

Result is

[{"first_name":"John","last_name":"Doe"}]

Expecting Result Using javascript:

John Doe

Advertisement

Answer

As the json code from your comment, you can do something like this:

var obj = JSON.parse('[{"first_name":"john","last_name":"doe"},{"first_name":"Jeen","last_name":"dra"},{"first_name":"Ad","last_name":"Does"},{"first_name":"Arin","last_name":"Gan"},{"first_name":"Jason","last_name":"Ford"},{"first_name":"Prince","last_name":"addar"},{"first_name":"Derek","last_name":"Frenzi"},{"first_name":"Jay","last_name":"dar"},{"first_name":"dam","last_name":"guly"},{"first_name":"nita","last_name":"Sa"}]');

for (i=0 ; i<obj.length ; i++){
   document.getElementById("demo").innerHTML += obj[i].first_name + " " + obj[i].last_name + "<br>" ;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement