循环结果PDO PHP [英] Loop results PDO PHP
问题描述
我正试图从我网站上的表中获取所有记录,我有以下内容
I'm trying to fetch all records from my table on my site, I have the following
$sth = $conn->prepare("SELECT * FROM directory WHERE user_active != ''");
$sth->execute();
/* Exercise PDOStatement::fetch styles */
$result = $sth->fetch(PDO::FETCH_ASSOC);
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $result) {
echo $result[First_Name];
}
只有它不返回所有记录,仅返回我的第一条记录,有人可以看到我要去哪里了吗?
Only its not returning all records, only my first, Can anybody see where I'm going wrong?
推荐答案
那么,您只需调用$sth->fetch
一次.您需要遍历结果.
Well, you only call $sth->fetch
once. You need to loop over the results.
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['First_Name'] . ' ' . $row['Surname'] . "\n";
}
也不要在没有大括号的情况下调用数组字符串索引.这样,PHP会检查键是否为常量,然后将其强制转换为字符串.这只是不好的做法,可能会导致意想不到的行为.
Also don't call array string indexes without braces. This way PHP checks if the key is a CONSTANT, then casts it to string. This is just bad practice and might lead to unexpected bahavior.
如果此方法仅返回一行,则数据库(或结果集)中可能只有一行.向我们显示更多代码!
If this returns only one row, you probably have only one row in the database (or the result set). Show us more code!
这篇关于循环结果PDO PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!