从PDO手册:
PDOStatement::rowCount() returns the
number of rows affected by the last
DELETE, INSERT, or UPDATE statement
executed by the corresponding
PDOStatement object.
If the last SQL statement executed by
the associated PDOStatement was a
SELECT statement, some databases may
return the number of rows returned by
that statement. However, this
behaviour is not guaranteed for all
databases and should not be relied on
for portable applications.
我最近才发现这一点.我刚刚改变了我的数据库抽象层,不再使用SELECT COUNT(1)……因为只需查询实际行然后计算结果就会更有效率.现在PDO不支持!?
我没有将PDO用于MySQL和PgSQL,但我是为SQLite做的.有没有办法(没有完全改变dbal背部)在PDO中计算这样的行?在MySQL中,这将是这样的:
$q = $db->query('SELECT a, b, c FROM tbl WHERE oele = 2 GROUP BY boele');
$rows = $q->num_rows;
// and now use $q to get actual data
使用MySQLi和PgSQL驱动程序,这是可能的.所有的PDO都不是!?
PS.我最初的解决方案是扩展SQLResult-> count方法(我自己的)以通过SELECT COUNT(1)FROM替换SELECT … FROM并返回该数字(非常低效,但仅适用于SQLite PDO).但这还不够好,因为在上面的示例查询中是GROUP BY,它会改变COUNT(1)的含义/功能.
解决方法:
这是您的解决方案
$sql="SELECT count(*) FROM [tablename] WHERE key == ? ";
$sth = $this->db->prepare($sql);
$sth->execute(array($key));
$rows = $sth->fetch(PDO::FETCH_NUM);
echo $rows[0];
标签:php,sqlite,database,pdo
来源: https://codeday.me/bug/20190916/1808564.html