Row count with PDO

前端 未结 23 3159
春和景丽
春和景丽 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:29

    when you make a COUNT(*) in your mysql statement like in

    $q = $db->query("SELECT COUNT(*) FROM ...");
    

    your mysql query is already counting the number of result why counting again in php? to get the result of your mysql

    $q = $db->query("SELECT COUNT(*) as counted FROM ...");
    $nb = $q->fetch(PDO::FETCH_OBJ);
    $nb = $nb->counted;
    

    and $nb will contain the integer you have counted with your mysql statement a bit long to write but fast to execute

    Edit: sorry for the wrong post but as some example show query with count in, I was suggesting using the mysql result, but if you don't use the count in sql fetchAll() is efficient, if you save the result in a variable you won't loose a line.

    $data = $dbh->query("SELECT * FROM ...");
    $table = $data->fetchAll(PDO::FETCH_OBJ);
    

    count($table) will return the number of row and you can still use the result after like $row = $table[0] or using a foreach

    foreach($table as $row){
      print $row->id;
    }
    

提交回复
热议问题