gpt4 book ai didi

php - 对大量数据使用 3 个变量

转载 作者:行者123 更新时间:2023-11-30 21:52:00 25 4
gpt4 key购买 nike

(标题有点奇怪,随便改,我不知道放什么)HTML 表将是 MySQL 表中最后 5 件事的历史记录,当加载第一行时,它存储在 HTML 表中第一行的变量中,然后加载/获取下一个 MYSQL 行,然后HTML 表中的第二行然后更改为 MYSQL 表的第二行。

例子:

for each row:
$username = row["username"]
$name = row["name"]

最终结果应该在 HTML 表格中:这些是使用上面的变量,我需要它们是根据 MySQL 表中最后 5 个表的所有不同数据

用户名一个名字 1(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'];
}

最佳答案

您可以使用 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>

关于php - 对大量数据使用 3 个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46817253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com