問題描述
我正在過渡到 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
語句回顯了正確的結(jié)果,但是 PDO::FETCH_ASSOC
查詢跳過了返回的第一個結(jié)果(因此它總是回顯小于它的一個結(jié)果應(yīng)該).
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 />";
}
推薦答案
您已經(jīng)在 while 循環(huán)之前獲取了第一行 $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 循環(huán)會在每次迭代時覆蓋 $row
,看起來您是從第二行開始的,但實際發(fā)生的是 $row
的值在首先覆蓋 while 循環(huán)迭代.
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.
要讓循環(huán)按照您編寫的方式工作,您需要使用 do-while 構(gòu)造:
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.
在這種特殊情況下,當沒有任何結(jié)果時,我不想回顯任何內(nèi)容
In this particular case I don't want to echo anything when there aren't any results
如果是這種情況,請先檢查您的查詢是否返回了任何結(jié)果.在這里,我在檢查中是明確的,因為如果您刪除外部 if
,您的 while
循環(huán)仍會遵循您的意圖 - 也就是說,它不會回顯任何內(nèi)容如果沒有任何結(jié)果.
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 />";
}
}
這篇關(guān)于此 PDO::FETCH_ASSOC` 查詢跳過返回的第一個結(jié)果的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!