Alex Alex - 3 months ago 21
JSON Question

Echo json data in php for data table use

I have been try to echo json array data, but am getting error. i have not done it before i want to use it for datatable

here is what i tried do but is show error from but if i copy the return text and save it in php folder it will work fine pleas i need help to fix it

<?php
try{

$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$users_stmt = $db_conn->prepare("SELECT * FROM users");
$users_stmt->execute();
while ($row = $users_stmt->fetch(PDO::FETCH_ASSOC)){

//json_encode($users_stmt->fetch(PDO::FETCH_ASSOC));
$dataarray = '
[
"'.$row['username'].'",
"'.$row['fullname'].'",
"'.$row['email'].'",
"'.$row['siteright'].'",
"2011/04/25",
"$320,800"
],
';

}
}catch (PDOException $e){ echo 'Connection failed: ' . $e->getMessage();}

echo '{<br/>
"data": [<br/>'
.$dataarray.
'<br/>[
"Donna Snider",
"Customer Support",
"New York",
"4226",
"2011/01/25",
"$112,000"
]<br/>
]<br/>
}';
?>


I want it to look like this

{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Donna Snider",
"Customer Support",
"New York",
"4226",
"2011/01/25",
"$112,000"
]
]
}

Answer

I think you want to do in this way -

while ($row = $users_stmt->fetch(PDO::FETCH_ASSOC)){
  $dataarray['data'][] = array(
                           $row['username'], $row['fullname'], 
                           $row['email'], $row['siteright'], 
                           2011/04/25, $320,800
                         );
}
$jsonData = json_encode($dataarray);

print_r($jsonData); // your json output
Comments