问题描述
我正在过渡到 PDO 准备好的语句,但我在使用 WHILE
语句的基本 SELECT
查询的语法方面遇到了问题.
I'm transitioning over to PDO prepared statements, and I'm having trouble with the syntax for a basic SELECT
query with a WHILE
statement.
下面的 foreach
语句回显了正确的结果,但是 PDO::FETCH_ASSOC
查询跳过了返回的第一个结果(因此它总是回显小于它的一个结果应该).
The foreach
statement below echos the correct results, but the PDO::FETCH_ASSOC
query is skipping the 1rst result that's returned (so it always echo's one result less than it should).
PDO::FETCH_ASSOC
$stmt = $conn->prepare("SELECT * FROM products");
$stmt->execute();
$row = $stmt->fetch();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['product_name'].' '.$row['price'].' '.$row['color'], "<br />";
}
foreach
foreach($conn->query('SELECT * FROM products') as $row) {
echo $row['product_name'].' '.$row['price'].' '.$row['color'], "<br />";
}
推荐答案
您已经在 while 循环之前获取了第一行 $row = $stmt->fetch();
.如果您删除此行,它将按预期工作.
You already fetched the first row before the while loop $row = $stmt->fetch();
. If you remove this line, it will work as expected.
由于 while 循环会在每次迭代时覆盖 $row
,看起来您是从第二行开始的,但实际发生的是 $row
的值在首先覆盖 while 循环迭代.
Since the while loop will overwrite $row
on each iteration, it looks like you start with the second row, but what happens is the value of $row
at the first while loop iteration is overwritten.
要让循环按照您编写的方式工作,您需要使用 do-while 构造:
To have the loop work the way you have written, you would need to use a do-while construct:
$row = $stmt->fetch();
do {
echo $row['product_name'].' '.$row['price'].' '.$row['color'], "<br />";
} while($row = $stmt->fetch(PDO::FETCH_ASSOC));
这里首先打印$row
的值,然后被while
条件覆盖.
Here the value of $row
will be printed first, before it is overwritten by the while
condition.
在这种特殊情况下,当没有任何结果时,我不想回显任何内容
In this particular case I don't want to echo anything when there aren't any results
如果是这种情况,请先检查您的查询是否返回了任何结果.在这里,我在检查中是明确的,因为如果您删除外部 if
,您的 while
循环仍会遵循您的意图 - 也就是说,它不会回显任何内容如果没有任何结果.
If that's the case, then check to see if your query returned any results first. Here I'm being explicit in the check, because if you removed the outer if
, your while
loop would still follow your intentions - that is, it won't echo anything if there aren't any results.
但是,在您的代码中有明确的意图总是好的:
However, it is always good to have clear intent in your code:
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['product_name'].' '.$row['price'].' '.$row['color'], "<br />";
}
}
这篇关于此 PDO::FETCH_ASSOC` 查询跳过返回的第一个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!