我一直在努力让以下代码运行,它不会返回任何内容:
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();
}
任何帮助将不胜感激。 Rgds,Stew
答案 0 :(得分:2)
fetchAll
会返回所有行,如果您想迭代结果,可以使用fetch
:
while($row = $STH->fetch())
或者如果你想坚持使用fetchAll()
:
$rows = $STH->fetchAll();
foreach($row in $rows){
...
}
正如bitWorking指出的那样,你也错过了对execute
的调用:
$STH = $DBH->prepare('SELECT * FROM `component`');
$STH->execute();
# setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
答案 1 :(得分:1)
您错过了execute方法。 使用fetchAll也是错误的。
请参阅Example #1 Fetch all remaining rows in a result set
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";
}