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
.
function count_x($connect) {
$query = " SELECT * FROM tbl WHERE id = '0' ";
$statement = $connect->prepare($query); $statement->execute();
$total_rows = $statement->rowCount();
return $total_rows;
}
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
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);
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;
}
Have a look at this link: http://php.net/manual/en/pdostatement.rowcount.php It is not recommended to use rowCount() in SELECT statements!
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