本文介绍了PDO在SELECT语句后返回错误的rowCount()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在执行与此类似的代码:
Im executing code similar to this:
// first select
$query = $link->prepare("
SELECT id FROM table
WHERE name = ?;");
$param = 'foo';
$query->bindParam(1, $param); // should return 1 row
$query->execute();
echo $query->rowCount(); // displays 0 (??????)
其他示例:
// second select
$query = $link->prepare("
SELECT id FROM table
WHERE name = ?;"); // should return 0 rows
$param = 'bar';
$query->bindParam(1, $param);
$query->execute();
echo $query->rowCount(); // displays 1 (?????)
我的桌子:
id | name
---------
1 | foo
我不明白.
推荐答案
某些数据库可能返回SELECT语句返回的行数.但是,并非所有数据库都可以保证有此行为,因此不应该依赖此行为. 手册 可以在以下查询中使用COUNT(*)
和fetchColumn()
来模拟rowCount()
.
Some databases may return the number of rows returned by a SELECT statement. However, this behaviour is not guaranteed for all databases and should not be relied on .Manual You can use COUNT(*)
and fetchColumn()
as in following query to emulate rowCount()
.
$query = $link->prepare("SELECT COUNT(*) FROM table WHERE name = ?");
$param = 'bar';
$query->bindParam(1,$param);
$query->execute();
// Check the number of rows that match the SELECT statement
if($query->fetchColumn() == 0) {
echo "No records found";
}else{
$query = $link->prepare("SELECT id FROM table WHERE name = ?")
//Etc
}
这篇关于PDO在SELECT语句后返回错误的rowCount()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!