简体   繁体   English

PHP - PDO获取循环

[英]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). 使用句柄DBH与MySQL数据库的数据库连接很好(未列出)。 The query works fine. 查询工作正常。 The echo of $row['text'] within the loop works fine multiple times. 循环中$row['text']的回显可以正常工作多次。 However, the echo of $help_text between -> and <- does nothing, resulting in -><- being displayed. 但是, -><-之间的$help_text的回$help_text什么都不做,导致显示-><- I would expect the echo to show the last instance of $row['text'] . 我希望echo能显示$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 "<-";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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