PHP PDO SQL only returning one row of data instead of all rows(PHP PDO SQL 只返回一行数据而不是所有行)
问题描述
我正在使用 PHP PDO 扩展来创建数据库类别表中所有项目的列表.预期结果不正确,只返回一行数据而不是全部预期的行.通过在 phpMyAdmin 控制台中运行相同的 SQL 语句,我得到了预期的结果所有数据行的结果.我需要知道我在使用 pdo 时忽略了什么.
I am using PHP PDO extension to create a list of all items from a DB category table. The expected results are not correct, only one row of data returned instead of all rows which is expected. By running the same SQL statement within the phpMyAdmin console I get the expected results for all rows of data. I need to know what I am overlooking with pdo.
当前代码:
$catId = 0;
$sql = "SELECT *
FROM category
WHERE cat_parent_id = :catId
ORDER BY cat_name";
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->bindParam(":catId", $catId, PDO::PARAM_INT);
$_stmt->execute();
$rows = $_stmt->fetch(PDO::FETCH_ASSOC);
// display PDO result - only getting one row instead of all rows.
print_r($rows);
Array ( [cat_id] => 3
[cat_parent_id] => 0
[cat_name] => Shop
[cat_description] => Seminars
[cat_image] => c72e.gif
)
// NOTE: By running the same SQL within the phpMyAdmin
// console I get the expected results with all rows.
Array ( [cat_id] => 3
[cat_parent_id] => 0
[cat_name] => Shop
[cat_description] => Seminars
[cat_image] => c72e.gif
),
( [cat_id] => 1
[cat_parent_id] => 0
[cat_name] => Site Map
[cat_description] => List content links
[cat_image] => c83b.gif
)
推荐答案
PDOStatement::fetch()
一次只返回 1 行.
PDOStatement::fetch()
will only return 1 row at a time.
您可以使用 PDOStatement::fetchAll()
:
You could use PDOStatement::fetchAll()
:
$rows = $_stmt->fetchAll(PDO::FETCH_ASSOC);
或创建一个循环,在该循环中不断调用 PDOStatement::fetch()
直到它返回 false
:
or create a loop where you keep calling PDOStatement::fetch()
until it returns false
:
$rows = array();
while( $row = $_stmt->fetch(PDO::FETCH_ASSOC) ) {
$rows[] = $row;
}
但后一个示例有点多余,如果您无论如何都想一次获取所有行,除非您想解决一些内存问题.
But the latter example is a bit redundant, if you want to get all rows at once anyway, unless there are some memory concerns you want to address.
这篇关于PHP PDO SQL 只返回一行数据而不是所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP PDO SQL 只返回一行数据而不是所有行
基础教程推荐
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01