Row count with PDO

前端 未结 23 3202
春和景丽
春和景丽 2020-11-21 22:57

There are many conflicting statements around. What is the best way to get the row count using PDO in PHP? Before using PDO, I just simply used mysql_num_rows.

23条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 23:35

    There is a simple solution. If you use PDO connect to your DB like this:

    try {
        $handler = new PDO('mysql:host=localhost;dbname=name_of_your_db', 'your_login', 'your_password'); 
        $handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } 
        catch (PDOException $e) {   
        echo $e->getMessage();
    }
    

    Then, the query to DB will be:

    $query = $handler->query("SELECT id FROM your_table WHERE ...");
    

    And finally, to count the rows matching your query write like this

    $amountOfRows = $query->rowcount();
    

提交回复
热议问题