(标题有点奇怪,随意改变它,我不知道该放什么) HTML表将是MySQL表中最后5件事的历史记录,当第一行加载时,它存储在HTML表中第一行的变量中,然后加载/获取下一个MYSQL行,并且然后将HTML表中的第二行更改为MYSQL表的第二行。
示例:
for each row:
$username = row["username"]
$name = row["name"]
结果结果应该在HTML表格中: 这些是使用上面的变量,根据MySQL表中的最后5个表,我需要它们是所有不同的数据
用户名 一个Name1(MySQL第1行) 两个Name2(MySQL第2行) 三个Name3(MySQL第3行) 四个Name4(MySQL第4行)
到目前为止代码:
$stmt = $dbConnection->prepare("SELECT * FROM history ORDER BY id DESC LIMIT 5");
$stmt->execute();
foreach ($stmt as $row) {
$username = $row['username'];
$gamemode = $row['gamemode'];
$winnings = $row['won'];
}
答案 0 :(得分:0)
您可以使用PDOStatement::fetchAll方法执行此操作。我建议你避免从php构建HTML代码(如html表)。随意提问。
<?php
// Create a PDO instance as db connection to a MySQL db.
$dbConnection = new PDO(
'mysql:host=localhost;port=3306;dbname=demo;charset=utf8'
, 'user'
, 'pass'
, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_PERSISTENT => TRUE
)
);
$sql = 'SELECT * FROM history ORDER BY id DESC LIMIT 5';
$stmt = $dbConnection->prepare($sql);
$executed = $stmt->execute();
/*
* Fetch the result set in form of an array.
* It's used later to build the html table.
*
* Array
* (
* [0] => Array
* (
* [username] => one
* [name] => name1
* )
*
* [1] => Array
* (
* [username] => two
* [name] => name2
* )
*
* [2] => Array
* (
* [username] => three
* [name] => name3
* )
* ...
* [4] => Array
* (
* [username] => five
* [name] => name5
* )
* )
*/
$resultset = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Just for testing. Delete this in the end.
echo '<pre>' . print_r($resultset, TRUE) . '</pre>';
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<title>Demo</title>
</head>
<body>
<table>
<tr>
<td>Username</td>
<td>Name</td>
</tr>
<?php
// Loop through the resultset array and build each html row.
foreach ($resultset as $row) {
$username = $row['username'];
$name = $row['name'];
?>
<tr>
<td>
<?php echo $username; ?>
</td>
<td>
<?php echo $name; ?>
</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
答案 1 :(得分:0)
为了保持代码尽可能接近,您可以使用数组来存储数据,如下所示:
$stmt = $dbConnection->prepare("SELECT * FROM history ORDER BY id DESC LIMIT 5");
$stmt->execute();
$usernames = array();
$gamemodes = array();
$winnings = array();
foreach ($stmt as $row) {
$usernames[] = $row['username'];
$gamemodes[] = $row['gamemode'];
$winnings[] = $row['won'];
}
然后,您可以像这样访问它们:
echo $usernames[1]; // Second name