大家好,我想在 HTML 文件中显示 MySQL 表中的数据。我有一个有效的 PHP 文件:
<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>
当我运行 PHP 文件时,我得到了预期的回显:
{"results":[{"name":"Benane","device":"iPhone4,1","punkte":"5000"},{"name":"Tillazh","device... and so on.
现在我想在 HTML 表格中显示这些数据。为此,我必须将数据(JSON 变量)传递给 HTML 文件(可能使用 $_POST 函数?)。我怎样才能做到这一点?使用 XMLHttpRequest (XHR) 是否合适?
最佳答案
是的,除非你打算多次使用这种模式,即使那样,因为你已经从 PHP 导出数据库表并且没有使用多种目标格式,所以没有必要使用 JSON。
最简单的解决方案是这样的:
<table><?php
foreach ($json as $k=>$v){
echo'<tr><th>',$k,'</th><td>',$v,'</td></tr>';
}
?></table>
关于php - 在html中显示json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18283003/