【发布时间】:2016-04-01 04:23:46
【问题描述】:
大约 3 周前开始学习 PHP,现在正在处理数据库连接和查询。我的问题涉及一章编程教学点。尽管我无法测试我的代码,但我在此站点上所做的研究使我使用 while 循环编写了以下一般查询。然而,这本书解释并教授了一些不同的东西。是一种方法比另一种更好还是两者都实现了相同的目标,即从数据库中提取数据并输出到 HTML 表?
另外,我相信我在这里学到的东西比任何书都多。意见和教导很有价值。
这就是我所拥有的:
<?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; ?>
【问题讨论】:
-
我不能 100% 确定您在问什么,但
while ($row = $qry->fetchALL();不是一个好主意。fetchAll()实际上是获取所有信息。所以这个循环只会执行一次,$row实际上会有很多行。 -
我在这里找到的许多示例和问题都使用了我原始问题中的第一种方法。我只是想知道首选的逻辑方法。
-
你确定吗?我敢肯定他们中的许多人确实使用
while ($row = $qry->fetch())...,但我真的不认为你会找到很多使用while ($row = $qry->fetchAll())...。