简体   繁体   中英

PHP - PDO fetch loop

I think I'm losing my mind here.

This is the code. (It's a simplified version of what I am actually trying to do in order to demonstrate the point.)

$STH = $DBH->query("SELECT * FROM help");
$STH->setFetchMode(PDO::FETCH_ASSOC);

while($row = $STH->fetch()) {
    echo $row['text'];
    $help_text = $row['text'];
}
echo "->";
echo $help_text;
echo "<-";

The db connection to the MySQL db using the handle DBH is fine (not listed). The query works fine. The echo of $row['text'] within the loop works fine multiple times. However, the echo of $help_text between -> and <- does nothing, resulting in -><- being displayed. I would expect the echo to show the last instance of $row['text'] .

Why is this not working, please?!

You need to declare it outside the loop

$help_text = "";
while($row = $STH->fetch()) {
    echo $row['text'];
    $help_text .= $row['text'];
}
echo "->";
echo $help_text;
echo "<-";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM