Using Doctrine DBAL to Count the Number of Rows from a SELECT Query

OK, so I'm looking for a neat and short way to count the number of rows from a SELECT query using Doctrine DBAL.

I know I can SELECT COUNT(*) , but then I need to sort the array when I get the results. As an alternative, it was suggested to take a look at getScalarResult() . But I can not find any documentation about this, except in DQL (this is a different project).

So what is the easiest way to do this? I guess, because I'm used to the excellent MySQLI attribute num_rows !

+8
php doctrine2
source share
2 answers

I actually thought it looked very hard, but I just came across this Count Records Returned Doctrine

So the way to do this is through the rowCount() method.

Example:

$num_rows = $conn->executeQuery("SELECT * FROM users")->rowCount();

+10
source share

Another way to do this with Doctrine DBAL is to get the counter as a field and return the column

  $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); 
+15
source share

All Articles