[英]Using Doctrine DBAL to count number of rows from SELECT query
OK so I am looking for a neat and short way to count the number of rows from a SELECT query using Doctrine DBAL.好的,所以我正在寻找一种简洁的方法来计算使用 Doctrine DBAL 的 SELECT 查询的行数。
I know that I could SELECT COUNT(*)
but then I need to sort through the array when I fetch results.我知道我可以SELECT COUNT(*)
但是当我获取结果时我需要对数组进行排序。 Alternatively, it's been suggested to look in to getScalarResult()
.或者,建议查看getScalarResult()
。 But I can't seem to find any documentation about this, other than in DQL (which is a different project).但除了 DQL(这是一个不同的项目)之外,我似乎找不到任何关于此的文档。
So what is the neatest way to do this?那么最简洁的方法是什么? I guess it's because I'm used to the great MySQLI attribute num_rows
!我想这是因为我习惯了很棒的 MySQLI 属性num_rows
!
Another way to do this with Doctrine DBAL is to get the count as a field and return the column使用 Doctrine DBAL 执行此操作的另一种方法是将计数作为字段并返回列
$sql = "SELECT count(*) AS Total FROM myTable WHERE myId = :myId";
$stmt = $conn->prepare($sql);
$stmt->bindValue('myId', $myId, PDO::PARAM_INT);
$stmt->execute();
$count = $stmt->fetchColumn(0);
Actually I thought I had looked really hard, but I just came across this Count Records Returned MySQL Doctrine其实我以为我看起来真的很努力,但我刚刚遇到了这个计数记录返回的 MySQL Doctrine
So the way to do it is via the rowCount()
method.所以这样做的方法是通过rowCount()
方法。
Example:例子:
$num_rows = $conn->executeQuery("SELECT * FROM users")->rowCount();
I enjoy to use the query builder.我喜欢使用查询构建器。 An example:一个例子:
$queryBuilder = $connection->createQueryBuilder();
$queryBuilder->select('COUNT(*)');
$queryBuilder->from("the_table");
$queryBuilder->where('some_column = :theValue');
$queryBuilder->setParameter('theValue', $someValue);
return (int) $queryBuilder->execute()->fetchColumn();
Here is an updated version of @DonkeyKong answer for Doctrine DBAL >= 2.13 :这是 Doctrine DBAL >= 2.13的@DonkeyKong 答案的更新版本:
$sql = "SELECT count(*) AS Total FROM myTable WHERE myId = :myId";
$stmt = $conn->prepare($sql);
$stmt->bindValue('myId', $myId, PDO::PARAM_INT);
$result = $stmt->executeQuery();
$count = $result->fetchOne();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.