LucN LucN - 7 months ago 29
PHP Question

Display json in html

Hi guys, I would like to display data from a MySQL table in a HTML file. I have a working PHP file:

<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost","user","pass","db");
if (mysqli_connect_errno()) {
printf("Can't connect to SQL Server. Error Code %s\n", mysqli_connect_error($mysqli));
exit;
}
$name = $_POST['name'];
// Set the default namespace to utf8
$mysqli->query("SET NAMES 'utf8'");
$json = array();
if($result = $mysqli->query("SELECT name, device, punkte FROM freefallhighscores ORDER BY punkte DESC LIMIT 0, 50")) {
while ($row=$result->fetch_assoc()) {
$json[]=array(
'name'=>$row['name'],
'device'=>$row['device'],
'punkte'=>$row['punkte']
);
}
}
$result->close();

header("Content-Type: text/json");
echo json_encode(array( 'results' => $json ));
$mysqli->close();
?>

</body>
</html>


When I run the PHP file, I get the expected echo:

{"results":[{"name":"Benane","device":"iPhone4,1","punkte":"5000"},{"name":"Tillazh","device... and so on.


Now I want to display this data in an HTML table. To do so, I have to pass the data (JSON variable) to an HTML file (maybe using the $_POST function?). How can I do this? Would it be appropriate to use an XMLHttpRequest (XHR)?

Answer

Yes, unless you are going to use this pattern a lot of times, and even then, since you're already exporting the database table from PHP and are not using multiple target formats, there is no need to use JSON.

The simplest solution would be something like:

<table><?php
foreach ($json as $k=>$v){
  echo'<tr><th>',$k,'</th><td>',$v,'</td></tr>';
}
?></table>
Comments