[英]PDO - Display Rows from Select statement
I have been struggling for a while to get the following code to run, it isnt returning anything: 我一直在努力运行以下代码,但并没有返回任何内容:
try {
$DBH = new PDO("mysql:host=$dbHost;dbname=$dbDatabase", $dbUser, $dbPass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->prepare('SELECT * FROM `component`');
# setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
while($row = $STH->fetchAll()) {
echo $row['cid'] . "\n";
echo $row['cdesc'] . "\n";
echo $row['cinfo'] . "\n";
}
}
catch(PDOException $e) {
echo "I'm sorry. I'm afraid I can't do that.";
echo $e->getMessage();
}
Any assistance would be appreciated. 任何援助将不胜感激。 Rgds, Stew
炖菜
fetchAll
returns all the rows, if you want to iterate over the results you can use fetch
: fetchAll
返回所有行,如果要遍历结果,可以使用fetch
:
while($row = $STH->fetch())
Or if you want to stick with fetchAll()
: 或者,如果您想坚持使用
fetchAll()
:
$rows = $STH->fetchAll();
foreach($row in $rows){
...
}
As bitWorking pointed out you are also missing the call to execute
: 正如bitWorking指出的那样,您还缺少
execute
的调用:
$STH = $DBH->prepare('SELECT * FROM `component`');
$STH->execute();
# setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
You missed the execute method. 您错过了execute方法。 Also wrong usage of fetchAll.
也错误地使用了fetchAll。
See Example #1 Fetch all remaining rows in a result set 请参阅示例#1提取结果集中的所有剩余行
Another example with fetchMode: 另一个使用fetchMode的示例:
$STH = $DBH->prepare('SELECT * FROM `component`');
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
// since PDOStatement implements Traversable you can directly iterate
foreach ($STH as $row) {
echo $row['cid'] . "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.