11

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

I know that I could SELECT COUNT(*) but then I need to sort through the array when I fetch results. Alternatively, it's been suggested to look in to getScalarResult(). But I can't seem to find any documentation about this, other than in DQL (which is a different project).

So what is the neatest way to do this? I guess it's because I'm used to the great MySQLI attribute num_rows!

1

4 Answers 4

21

Another way to do this with Doctrine DBAL is to get the count 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);
Sign up to request clarification or add additional context in comments.

Comments

20

Actually I thought I had looked really hard, but I just came across this Count Records Returned MySQL Doctrine

So the way to do it is via the rowCount() method.

Example:

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

2 Comments

That only makes sense if you anyway need to fetch the records. Otherwise fetching all records just to count them in PHP is a bad idea performance wise.
Be aware that rowCount is not 100% trustable for all databases, the behavior may change depending on the database that you are using it. This comment is copy pasted from the source code of the method. If the last SQL statement executed by the associated Statement object 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. link
5

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();

Comments

2

Here is an updated version of @DonkeyKong answer for Doctrine DBAL >= 2.13:

$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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.