Share this question

Welcome to Teachnovice Q&A, where you can ask questions and receive answers from other members of the community.

This is a collaboratively edited question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

PHP - PDO fetch loop

0 like 0 dislike
126 views

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?!

asked Jan 5, 2012 by anonymous  
edited Jul 4, 2012 by sarwana

1 Answer

0 like 0 dislike

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 "<-";
answered Jul 2, 2012 by anonymous  
edited Jul 4, 2012 by sarwana
...