You already fetched the first row before the while loop $row = $stmt->fetch();
. If you remove this line, it will work as expected.
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.
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));
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 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 />";
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…