Row count with PDO

前端 未结 23 3205
春和景丽
春和景丽 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:18
    function count_x($connect) {  
     $query = "  SELECT * FROM tbl WHERE id = '0' ";  
     $statement = $connect->prepare($query);  $statement->execute();  
     $total_rows = $statement->rowCount();  
     return $total_rows; 
    }
    
    0 讨论(0)
  • 2020-11-21 23:19

    When it is matter of mysql how to count or get how many rows in a table with PHP PDO I use this

    // count total number of rows
    $query = "SELECT COUNT(*) as total_rows FROM sometable";
    $stmt = $con->prepare($query);
    
    // execute query
    $stmt->execute();
    
    // get total rows
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $total_rows = $row['total_rows'];
    

    credits goes to Mike @ codeofaninja.com

    0 讨论(0)
  • 2020-11-21 23:20

    You can combine the best method into one line or function, and have the new query auto-generated for you:

    function getRowCount($q){ 
        global $db;
        return $db->query(preg_replace('/SELECT [A-Za-z,]+ FROM /i','SELECT count(*) FROM ',$q))->fetchColumn();
    }
    
    $numRows = getRowCount($query);
    
    0 讨论(0)
  • 2020-11-21 23:21

    For straight queries where I want a specific row, and want to know if it was found, I use something like:

    function fetchSpecificRow(&$myRecord) {
        $myRecord = array();
        $myQuery = "some sql...";
        $stmt = $this->prepare($myQuery);
        $stmt->execute(array($parm1, $parm2, ...));
        if ($myRecord = $stmt->fetch(PDO::FETCH_ASSOC)) return 0;
        return $myErrNum;
    }
    
    0 讨论(0)
  • 2020-11-21 23:22

    Have a look at this link: http://php.net/manual/en/pdostatement.rowcount.php It is not recommended to use rowCount() in SELECT statements!

    0 讨论(0)
  • 2020-11-21 23:23

    To use variables within a query you have to use bindValue() or bindParam(). And do not concatenate the variables with " . $variable . "

    $statement = "SELECT count(account_id) FROM account
                      WHERE email = ? AND is_email_confirmed;";
    $preparedStatement = $this->postgreSqlHandler->prepare($statement);
    $preparedStatement->bindValue(1, $account->getEmail());
    $preparedStatement->execute();
    $numberRows= $preparedStatement->fetchColumn();
    

    GL

    0 讨论(0)
提交回复
热议问题