大约 3 周前开始学习 PHP,现在正在研究数据库连接和查询。我的问题涉及到一章编程教学点。尽管我无法测试我的代码,但我在此站点上所做的研究使我使用 while 循环编写了以下常规查询的代码。然而,这本书所解释和教导的东西是不同的。一种方法比另一种更好,还是两者都实现相同的目标,即从数据库中提取数据并输出到 HTML 表?
而且,我相信我在这里学到的东西比任何书上都多。意见和教导很有值(value)。
这就是我所拥有的:
<?php
/set connection parameter variables
$hostname = 'localhost';
$username = 'richardweb';
$password = 'richardchocolate';
$dbname = 'richard_ricardo_assignment_db';
$conn = new PDO("mysql:dbname=$dbname;host=$hostname", $username, $password);
//set mysql query
$sql = 'SELECT studentID, name, email
FROM student
ORDER BY studentID';
$qry = $conn->query($sql);
$qry->setFetchMode(PDO::FETCH_ASSOC);
try {
$conn = new PDO("mysql:dbname=$dbname;host=$hostname"; $username, $password);
$sql = 'SELECT studentID, name, email
FROM student
ORDER BY studentID';
$qry = $conn->query($sql);
$qry->setFetchMode(PDO::FETCH_ASSOC);
}
catch (PDOException $e) {
echo "Error connecting to the database" . $e->getMessage();
}
?>
<!doctype html>
<html>
<head>
<title>Whatever</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class="main">
<h1>Students</h1>
<table class="table1">
<thead>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php while ($row = $qry->fetchALL(); ?>
<tr>
<td><?php echo htmlspecialchars($r['studentID'])?></td>
<td><?php echo htmlspecialchars($r['name'])?></td>
<td><?php echo htmlspecialchars($r['email'])?></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</body>
</html>
This is what my book covers for displaying results in HTML Table. Only showing the tabular data output. I'm only giving the example from the book and have not converted my code.
<?php foreach ($products as $product) : ?>
<tr>
<td><?php echo $product['productCode']; ?></td>
<td><?php echo $product['productName']; ?></td>
<td><?php echo $product['listPrice']; ?></td>
</tr>
<?php endforeach; ?>
最佳答案
如果您成功执行了 PDO 语句,有两种主要方法可以获取结果。
一次一个 - 这通常在 while 循环中完成,使用
PDOStatement
的方法之一从结果集中的一行中获取数据,例如fetch()
、fetchColumn()
或fetchObject()
,如下所示:while ($row = $stmt->fetch()) { // do something with data from each row }
一次性完成。为此,您将使用
fetchAll()
,然后通常使用foreach
循环来迭代行数组。$rows = $stmt->fetchAll(); foreach ($rows as $row) { // do something with data from each row }
两者本质上并不比另一个更好。您应该选择哪一种取决于您需要对数据执行什么操作。对于简单创建 HTML 表来显示结果之类的情况,使用“一次一个”方法就足够了。
fetchAll()
的一个合理用途是,如果您需要在程序中的不同点对结果执行多个不同的操作。如果您使用“一次一个”方法,则需要重复执行查询,这通常效率较低。
但是在使用 fetchAll 时,请务必注意此警告(来自 PHP 文档):
Using this method to fetch large result sets will result in a heavy demand on system and possibly network resources. Rather than retrieving all of the data and manipulating it in PHP, consider using the database server to manipulate the result sets. For example, use the WHERE and ORDER BY clauses in SQL to restrict results before retrieving and processing them with PHP.
关于php - 将 mysql(PDO) 结果输出到 HTML 表的更好方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36342293/