Row count with PDO

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

    fetchColumn()

    used if want to get count of record [effisien]

    $sql   = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
    $res   = $conn->query($sql);
    $count = $res->fetchColumn(); // ex = 2
    

    query()

    used if want to retrieve data and count of record [options]

    $sql = "SELECT * FROM fruit WHERE calories > 100";
    $res = $conn->query($sql);
    
    if ( $res->rowCount() > 0) {
    
        foreach ( $res as $row ) {
            print "Name: {$row['NAME']} 
    "; } } else { print "No rows matched the query."; }

    PDOStatement::rowCount

提交回复
热议问题