在PHP中使用Highscore系统。要从MySQL数据库获取数据,我使用此代码。
<?php
$sql_query = "SELECT id,name, exp FROM user ORDER by exp DESC";
try {
$conn = new PDO('mysql:host=localhost;dbname=game', 'root', 'pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$rst = $conn->query($sql_query);
$users= $rst->fetchAll(PDO::FETCH_OBJ);
echo '' . json_encode($users) . '';
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
该代码的输出如下:
[{"id":"1","name":"Player","exp":"22060"}
我需要分别在标签中回显这些数据。例如。
<td><?php echo $users->name ?></td>
<td><?php echo $users->exp ?></td>
答案 0 :(得分:0)
这应该可以解决问题:
<?php
$sql_query = "SELECT id,name, exp FROM user ORDER by exp DESC";
try {
$conn = new PDO('mysql:host=localhost;dbname=game', 'root', 'pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$rst = $conn->query($sql_query);
$users= $rst->fetchAll(PDO::FETCH_OBJ);
foreach($users as $user) {
echo "<td>{$user->name}</td>";
echo "<td>{$user->exp}</td>";
}
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>