How to do a num_rows() on COUNT query in codeigniter? - php

This works:
$sql = "SELECT id
FROM `users`
WHERE `account_status` = '" . $i . "'";
$query = $this->db->query($sql);
var_dump($query->num_rows());
But this doesn't:
$sql = "SELECT COUNT(*)
FROM `users`
WHERE `account_status` = '" . $i . "'";
$query = $this->db->query($sql);
var_dump($query->num_rows());
How to do a num_rows on a COUNT(*) query? Also is doing it the 2nd way any better performance wise?

Doing a COUNT(*) will only give you a singular row containing the number of rows and not the results themselves.
To access COUNT(*) you would need to do
$result = $query->row_array();
$count = $result['COUNT(*)'];
The second option performs much better since it does not need to return a dataset to PHP but instead just a count and therefore is much more optimized.

In CI it's really simple actually, all you need is
$this->db->where('account_status', $i);
$num_rows = $this->db->count_all_results('users');
var_dump($num_rows); // prints the number of rows in table users with account status $i

$query->num_rows()
The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:
$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();

num_rows on your COUNT() query will literally ALWAYS be 1. It is an aggregate function without a GROUP BY clause, so all rows are grouped together into one. If you want the value of the count, you should give it an identifier SELECT COUNT(*) as myCount ..., then use your normal method of accessing a result (the first, only result) and get it's 'myCount' property.

As per CI Docs we can use the following,
$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();
If we want to get total rows in the table without any condition, simple use
echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table

it's my way of solving the above given question
model
$this->db->select('count(id) as ids');
$this->db->where('id', $id);
$this->db->from('your_table_name');
thanks

This will only return 1 row, because you're just selecting a COUNT(). you will use mysql_num_rows() on the $query in this case.
If you want to get a count of each of the ID's, add GROUP BY id to the end of the string.
Performance-wise, don't ever ever ever use * in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *. This is because * has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.

I'd suggest instead of doing another query with the same parameters just immediately running a SELECT FOUND_ROWS()

$list_data = $this->Estimate_items_model->get_details(array("estimate_id" => $id))->result();
$result = array();
$counter = 0;
$templateProcessor->cloneRow('Title', count($list_data));
foreach($list_data as $row) {
$counter++;
$templateProcessor->setValue('Title#'.$counter, $row->title);
$templateProcessor->setValue('Description#'.$counter, $row->description);
$type = $row->unit_type ? $row->unit_type : "";
$templateProcessor->setValue('Quantity#'.$counter, to_decimal_format($row->quantity) . " " . $type);
$templateProcessor->setValue('Rate#'.$counter, to_currency($row->rate, $row->currency_symbol));
$templateProcessor->setValue('Total#'.$counter, to_currency($row->total, $row->currency_symbol));
}

Related

Using Count giving wrong number of rows

Before I was using this code to count rows
echo $db_handle->numRows("SELECT * FROM orders WHERE DATE(reattemptdate) = CURDATE()");
than i found it effects on performance, than i tried to use below code, but it not giving correct number of rows, what wrong i done in below code ?
$sqldelivery = "SELECT COUNT(*) as count FROM orders WHERE DATE(reattemptdate) = CURDATE()";
$resultdeliverys = $db_handle->runSelectQuery($sqldelivery);
$numrowsresultdelivery =count($resultdeliverys);
echo $numrowsresultdelivery;
Database connection code :
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
In your second code, the query will always return 1 row - a row with the column count being the number of rows, so...
$numrowsresultdelivery =count($resultdeliverys);
Will probably always be 1, you need something like...
$numrowsresultdelivery =$resultdeliverys[0]['count'];
to extract the count field from the first row of the result.
(Note I don't know if this is the right notation, but it's the principle of needing a field from the result rather than the number of results.)
You must already have the count number via $resultdeliverys->count.
$sqldelivery = "SELECT COUNT(*) as count FROM orders WHERE DATE(reattemptdate) = CURDATE()";
$resultdeliverys = $db_handle->runSelectQuery($sqldelivery);
// Try this to know if it's returning array or object
var_dump($resultdeliverys);

count total rows in MySQL and number of rows based on a where statement [duplicate]

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.
fetchAll is something I won't want because I may sometimes be dealing with large datasets, so not good for my use.
Do you have any suggestions?
$sql = "SELECT count(*) FROM `table` WHERE foo = ?";
$result = $con->prepare($sql);
$result->execute([$bar]);
$number_of_rows = $result->fetchColumn();
Not the most elegant way to do it, plus it involves an extra query.
PDO has PDOStatement::rowCount(), which apparently does not work in MySql. What a pain.
From the PDO Doc:
For most databases,
PDOStatement::rowCount() does not
return the number of rows affected by
a SELECT statement. Instead, use
PDO::query() to issue a SELECT
COUNT(*) statement with the same
predicates as your intended SELECT
statement, then use
PDOStatement::fetchColumn() to
retrieve the number of rows that will
be returned. Your application can then
perform the correct action.
EDIT: The above code example uses a prepared statement, which is in many cases is probably unnecessary for the purpose of counting rows, so:
$nRows = $pdo->query('select count(*) from blah')->fetchColumn();
echo $nRows;
As I wrote previously in an answer to a similar question, the only reason mysql_num_rows() worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you.
So in PDO, your options are:
Use PDO's fetchAll() function to fetch all the rows into an array, then use count() on it.
Do an extra query to SELECT COUNT(*), as karim79 suggested.
Use MySQL's FOUND_ROWS() function UNLESS the query had SQL_CALC_FOUND_ROWS or a LIMIT clause (in which case the number of rows that were returned by the query and the number returned by FOUND_ROWS() may differ). However, this function is deprecated and will be removed in the future.
As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:
They need to know how many rows in the table
They need to know whether a query returned any rows
That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount() function has to be used.
Let's see why
Counting rows in the table
Before using PDO I just simply used mysql_num_rows().
Means you already did it wrong. Using mysql_num_rows() or rowCount() to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*) query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.
For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.
Counting the number rows returned.
The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!
Say, if you are selecting only one row. All right, you can use the fetched row as a flag:
$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
echo 'No data found';
}
In case you need to get many rows, then you can use fetchAll().
fetchAll() is something I won't want as I may sometimes be dealing with large datasets
Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount() nor fetchAll().
But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll(). Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT, WHERE or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll(). And again, just use this function's result in the condition:
$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
echo 'No data found';
}
And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.
Counting the number of rows in a large resultset
In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount() won't be available, thus there is no use for this function as well.
Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.
I ended up using this:
$result = $db->query($query)->fetchAll();
if (count($result) > 0) {
foreach ($result as $row) {
echo $row['blah'] . '<br />';
}
} else {
echo "<p>Nothing matched your query.</p>";
}
This post is old but Getting row count in php with PDO is simple
$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
This is super late, but I ran into the problem and I do this:
function countAll($table){
$dbh = dbConnect();
$sql = "select * from `$table`";
$stmt = $dbh->prepare($sql);
try { $stmt->execute();}
catch(PDOException $e){echo $e->getMessage();}
return $stmt->rowCount();
It's really simple, and easy. :)
This is an old post, but getting frustrated looking for alternatives. It is super unfortunate that PDO lacks this feature, especially as PHP and MySQL tend to go hand in hand.
There is an unfortunate flaw in using fetchColumn() as you can no longer use that result set (effectively) as the fetchColumn() moves the needle to the next row. So for example, if you have a result similar to
Fruit->Banana
Fruit->Apple
Fruit->Orange
If you use fetchColumn() you can find out that there are 3 fruits returned, but if you now loop through the result, you only have two columns, The price of fetchColumn() is the loss of the first column of results just to find out how many rows were returned. That leads to sloppy coding, and totally error ridden results if implemented.
So now, using fetchColumn() you have to implement and entirely new call and MySQL query just to get a fresh working result set. (which hopefully hasn't changed since your last query), I know, unlikely, but it can happen. Also, the overhead of dual queries on all row count validation. Which for this example is small, but parsing 2 million rows on a joined query, not a pleasant price to pay.
I love PHP and support everyone involved in its development as well as the community at large using PHP on a daily basis, but really hope this is addressed in future releases. This is 'really' my only complaint with PHP PDO, which otherwise is a great class.
Answering this because I trapped myself with it by now knowing this and maybe it will be useful.
Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by count($array), and output results with foreach.
For example:
$query = "your_query_here";
$STH = $DBH->prepare($query);
$STH->execute();
$rows = $STH->fetchAll();
//all your results is in $rows array
$STH->setFetchMode(PDO::FETCH_ASSOC);
if (count($rows) > 0) {
foreach ($rows as $row) {
//output your rows
}
}
If you just want to get a count of rows (not the data) ie. using COUNT(*) in a prepared statement then all you need to do is retrieve the result and read the value:
$sql = "SELECT count(*) FROM `table` WHERE foo = bar";
$statement = $con->prepare($sql);
$statement->execute();
$count = $statement->fetch(PDO::FETCH_NUM); // Return array indexed by column number
return reset($count); // Resets array cursor and returns first value (the count)
Actually retrieving all the rows (data) to perform a simple count is a waste of resources. If the result set is large your server may choke on it.
Have a look at this link:
http://php.net/manual/en/pdostatement.rowcount.php
It is not recommended to use rowCount() in SELECT statements!
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
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
A quick one liner to get the first entry returned. This is nice for very basic queries.
<?php
$count = current($db->query("select count(*) from table")->fetch());
?>
Reference
I tried $count = $stmt->rowCount(); with Oracle 11.2 and it did not work.
I decided to used a for loop as show below.
$count = "";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "<table border='1'>\n";
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$count++;
echo "<tr>\n";
foreach ($row as $item) {
echo "<td class='td2'>".($item !== null ? htmlentities($item, ENT_QUOTES):" ")."</td>\n";
} //foreach ends
}// while ends
echo "</table>\n";
//echo " no of rows : ". oci_num_rows($stmt);
//equivalent in pdo::prepare statement
echo "no.of rows :".$count;
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;
}
The simplest way, it is only 2 lines,
$sql = $db->query("SELECT COUNT(*) FROM tablename WHERE statement='condition'");
echo $sql->fetchColumn();
So, the other answers have established that rowCount() shouldn't be used to count the rows of a SELECT statement. The documentation even says, that :
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
https://web.archive.org/web/20220409162106/https://www.php.net/manual/en/pdostatement.rowcount.php
So it's okay for other queries, but not great for SELECT. Most answers suggest that you should make two queries, one to count rows, and one to get the subset of records you need. However, you could query the row count and your subset of the data in one request. This is a bit of an exercise in code golf, but could actually prove more efficient than two requests if the request time is a bit costly and these requests are made frequently.
If you're in PostgreSQL you can provide clean JSON output, like so:
WITH mytable as (VALUES(1,2,3),(4,5,6),(7,8,9),(10,11,12))
SELECT
jsonb_build_object(
'rowcount', (SELECT count(1) FROM mytable)
,'data', (
SELECT jsonb_agg(data.*)
FROM (
SELECT *
FROM mytable
WHERE column1 > 1 -- pagination offset
ORDER BY column1
LIMIT 2 -- page size
) as data
)
) jsondata
Output:
{"data": [
{
"column1": 4,
"column2": 5,
"column3": 6
},
{
"column1": 7,
"column2": 8,
"column3": 9
}
],
"rowcount": 4
}
If you're not in postgres, those functions won't be available, but you could do this:
WITH mytable as (VALUES(1,2,3),(4,5,6),(7,8,9),(10,11,12))
SELECT
(SELECT count(1) FROM mytable) as rowcount
,data.*
FROM (
SELECT *
FROM mytable as mytable(column1, column2, column3)
WHERE column1 > 1 -- pagination offset
ORDER BY column1
LIMIT 2 -- page size
) as data
but it will return the rowcount on every row, which might be a bit wasteful:
rowcount
column1
column2
column3
4
4
5
6
4
7
8
9
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;
}
Here's a custom-made extension of the PDO class, with a helper function to retrieve the number of rows included by the last query's "WHERE" criteria.
You may need to add more 'handlers', though, depending on what commands you use. Right now it only works for queries that use "FROM " or "UPDATE ".
class PDO_V extends PDO
{
private $lastQuery = null;
public function query($query)
{
$this->lastQuery = $query;
return parent::query($query);
}
public function getLastQueryRowCount()
{
$lastQuery = $this->lastQuery;
$commandBeforeTableName = null;
if (strpos($lastQuery, 'FROM') !== false)
$commandBeforeTableName = 'FROM';
if (strpos($lastQuery, 'UPDATE') !== false)
$commandBeforeTableName = 'UPDATE';
$after = substr($lastQuery, strpos($lastQuery, $commandBeforeTableName) + (strlen($commandBeforeTableName) + 1));
$table = substr($after, 0, strpos($after, ' '));
$wherePart = substr($lastQuery, strpos($lastQuery, 'WHERE'));
$result = parent::query("SELECT COUNT(*) FROM $table " . $wherePart);
if ($result == null)
return 0;
return $result->fetchColumn();
}
}
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);
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();
}
Now, if you want to know how many rows are existing in your table and you have for example column 'id' as the primary key, the query to DB will be:
$query = $handler->query("SELECT id FROM your_table_name");
And finally, to get the amount of the rows matching your query, write like this:
$amountOfRows = $query->rowCount();
Or you can write:
$query = $handler ->query("SELECT COUNT(id) FROM your_table_name");
$amountOfRows = $query->rowCount();
Or, if you want to know how many products there are in the table 'products' have the price between 10 and 20, write this query:
$query = $handler ->query("SELECT id FROM products WHERE price BETWEEN 10 AND
20");
$amountOfRows = $query->rowCount();

Select from two tables with if condition and delete [duplicate]

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.
fetchAll is something I won't want because I may sometimes be dealing with large datasets, so not good for my use.
Do you have any suggestions?
$sql = "SELECT count(*) FROM `table` WHERE foo = ?";
$result = $con->prepare($sql);
$result->execute([$bar]);
$number_of_rows = $result->fetchColumn();
Not the most elegant way to do it, plus it involves an extra query.
PDO has PDOStatement::rowCount(), which apparently does not work in MySql. What a pain.
From the PDO Doc:
For most databases,
PDOStatement::rowCount() does not
return the number of rows affected by
a SELECT statement. Instead, use
PDO::query() to issue a SELECT
COUNT(*) statement with the same
predicates as your intended SELECT
statement, then use
PDOStatement::fetchColumn() to
retrieve the number of rows that will
be returned. Your application can then
perform the correct action.
EDIT: The above code example uses a prepared statement, which is in many cases is probably unnecessary for the purpose of counting rows, so:
$nRows = $pdo->query('select count(*) from blah')->fetchColumn();
echo $nRows;
As I wrote previously in an answer to a similar question, the only reason mysql_num_rows() worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you.
So in PDO, your options are:
Use PDO's fetchAll() function to fetch all the rows into an array, then use count() on it.
Do an extra query to SELECT COUNT(*), as karim79 suggested.
Use MySQL's FOUND_ROWS() function UNLESS the query had SQL_CALC_FOUND_ROWS or a LIMIT clause (in which case the number of rows that were returned by the query and the number returned by FOUND_ROWS() may differ). However, this function is deprecated and will be removed in the future.
As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:
They need to know how many rows in the table
They need to know whether a query returned any rows
That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount() function has to be used.
Let's see why
Counting rows in the table
Before using PDO I just simply used mysql_num_rows().
Means you already did it wrong. Using mysql_num_rows() or rowCount() to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*) query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.
For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.
Counting the number rows returned.
The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!
Say, if you are selecting only one row. All right, you can use the fetched row as a flag:
$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
echo 'No data found';
}
In case you need to get many rows, then you can use fetchAll().
fetchAll() is something I won't want as I may sometimes be dealing with large datasets
Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount() nor fetchAll().
But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll(). Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT, WHERE or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll(). And again, just use this function's result in the condition:
$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
echo 'No data found';
}
And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.
Counting the number of rows in a large resultset
In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount() won't be available, thus there is no use for this function as well.
Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.
I ended up using this:
$result = $db->query($query)->fetchAll();
if (count($result) > 0) {
foreach ($result as $row) {
echo $row['blah'] . '<br />';
}
} else {
echo "<p>Nothing matched your query.</p>";
}
This post is old but Getting row count in php with PDO is simple
$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
This is super late, but I ran into the problem and I do this:
function countAll($table){
$dbh = dbConnect();
$sql = "select * from `$table`";
$stmt = $dbh->prepare($sql);
try { $stmt->execute();}
catch(PDOException $e){echo $e->getMessage();}
return $stmt->rowCount();
It's really simple, and easy. :)
This is an old post, but getting frustrated looking for alternatives. It is super unfortunate that PDO lacks this feature, especially as PHP and MySQL tend to go hand in hand.
There is an unfortunate flaw in using fetchColumn() as you can no longer use that result set (effectively) as the fetchColumn() moves the needle to the next row. So for example, if you have a result similar to
Fruit->Banana
Fruit->Apple
Fruit->Orange
If you use fetchColumn() you can find out that there are 3 fruits returned, but if you now loop through the result, you only have two columns, The price of fetchColumn() is the loss of the first column of results just to find out how many rows were returned. That leads to sloppy coding, and totally error ridden results if implemented.
So now, using fetchColumn() you have to implement and entirely new call and MySQL query just to get a fresh working result set. (which hopefully hasn't changed since your last query), I know, unlikely, but it can happen. Also, the overhead of dual queries on all row count validation. Which for this example is small, but parsing 2 million rows on a joined query, not a pleasant price to pay.
I love PHP and support everyone involved in its development as well as the community at large using PHP on a daily basis, but really hope this is addressed in future releases. This is 'really' my only complaint with PHP PDO, which otherwise is a great class.
Answering this because I trapped myself with it by now knowing this and maybe it will be useful.
Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by count($array), and output results with foreach.
For example:
$query = "your_query_here";
$STH = $DBH->prepare($query);
$STH->execute();
$rows = $STH->fetchAll();
//all your results is in $rows array
$STH->setFetchMode(PDO::FETCH_ASSOC);
if (count($rows) > 0) {
foreach ($rows as $row) {
//output your rows
}
}
If you just want to get a count of rows (not the data) ie. using COUNT(*) in a prepared statement then all you need to do is retrieve the result and read the value:
$sql = "SELECT count(*) FROM `table` WHERE foo = bar";
$statement = $con->prepare($sql);
$statement->execute();
$count = $statement->fetch(PDO::FETCH_NUM); // Return array indexed by column number
return reset($count); // Resets array cursor and returns first value (the count)
Actually retrieving all the rows (data) to perform a simple count is a waste of resources. If the result set is large your server may choke on it.
Have a look at this link:
http://php.net/manual/en/pdostatement.rowcount.php
It is not recommended to use rowCount() in SELECT statements!
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
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
A quick one liner to get the first entry returned. This is nice for very basic queries.
<?php
$count = current($db->query("select count(*) from table")->fetch());
?>
Reference
I tried $count = $stmt->rowCount(); with Oracle 11.2 and it did not work.
I decided to used a for loop as show below.
$count = "";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "<table border='1'>\n";
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$count++;
echo "<tr>\n";
foreach ($row as $item) {
echo "<td class='td2'>".($item !== null ? htmlentities($item, ENT_QUOTES):" ")."</td>\n";
} //foreach ends
}// while ends
echo "</table>\n";
//echo " no of rows : ". oci_num_rows($stmt);
//equivalent in pdo::prepare statement
echo "no.of rows :".$count;
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;
}
The simplest way, it is only 2 lines,
$sql = $db->query("SELECT COUNT(*) FROM tablename WHERE statement='condition'");
echo $sql->fetchColumn();
So, the other answers have established that rowCount() shouldn't be used to count the rows of a SELECT statement. The documentation even says, that :
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
https://web.archive.org/web/20220409162106/https://www.php.net/manual/en/pdostatement.rowcount.php
So it's okay for other queries, but not great for SELECT. Most answers suggest that you should make two queries, one to count rows, and one to get the subset of records you need. However, you could query the row count and your subset of the data in one request. This is a bit of an exercise in code golf, but could actually prove more efficient than two requests if the request time is a bit costly and these requests are made frequently.
If you're in PostgreSQL you can provide clean JSON output, like so:
WITH mytable as (VALUES(1,2,3),(4,5,6),(7,8,9),(10,11,12))
SELECT
jsonb_build_object(
'rowcount', (SELECT count(1) FROM mytable)
,'data', (
SELECT jsonb_agg(data.*)
FROM (
SELECT *
FROM mytable
WHERE column1 > 1 -- pagination offset
ORDER BY column1
LIMIT 2 -- page size
) as data
)
) jsondata
Output:
{"data": [
{
"column1": 4,
"column2": 5,
"column3": 6
},
{
"column1": 7,
"column2": 8,
"column3": 9
}
],
"rowcount": 4
}
If you're not in postgres, those functions won't be available, but you could do this:
WITH mytable as (VALUES(1,2,3),(4,5,6),(7,8,9),(10,11,12))
SELECT
(SELECT count(1) FROM mytable) as rowcount
,data.*
FROM (
SELECT *
FROM mytable as mytable(column1, column2, column3)
WHERE column1 > 1 -- pagination offset
ORDER BY column1
LIMIT 2 -- page size
) as data
but it will return the rowcount on every row, which might be a bit wasteful:
rowcount
column1
column2
column3
4
4
5
6
4
7
8
9
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;
}
Here's a custom-made extension of the PDO class, with a helper function to retrieve the number of rows included by the last query's "WHERE" criteria.
You may need to add more 'handlers', though, depending on what commands you use. Right now it only works for queries that use "FROM " or "UPDATE ".
class PDO_V extends PDO
{
private $lastQuery = null;
public function query($query)
{
$this->lastQuery = $query;
return parent::query($query);
}
public function getLastQueryRowCount()
{
$lastQuery = $this->lastQuery;
$commandBeforeTableName = null;
if (strpos($lastQuery, 'FROM') !== false)
$commandBeforeTableName = 'FROM';
if (strpos($lastQuery, 'UPDATE') !== false)
$commandBeforeTableName = 'UPDATE';
$after = substr($lastQuery, strpos($lastQuery, $commandBeforeTableName) + (strlen($commandBeforeTableName) + 1));
$table = substr($after, 0, strpos($after, ' '));
$wherePart = substr($lastQuery, strpos($lastQuery, 'WHERE'));
$result = parent::query("SELECT COUNT(*) FROM $table " . $wherePart);
if ($result == null)
return 0;
return $result->fetchColumn();
}
}
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);
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();
}
Now, if you want to know how many rows are existing in your table and you have for example column 'id' as the primary key, the query to DB will be:
$query = $handler->query("SELECT id FROM your_table_name");
And finally, to get the amount of the rows matching your query, write like this:
$amountOfRows = $query->rowCount();
Or you can write:
$query = $handler ->query("SELECT COUNT(id) FROM your_table_name");
$amountOfRows = $query->rowCount();
Or, if you want to know how many products there are in the table 'products' have the price between 10 and 20, write this query:
$query = $handler ->query("SELECT id FROM products WHERE price BETWEEN 10 AND
20");
$amountOfRows = $query->rowCount();

Get the count of the mysql query results in php

I would like to get the count of the mysql query results in php.
The query usually returns up to 10 rows.
Which one in the below is better to use:
1.
$query = "SELECT * FROM test_table WHERE test_no=12345";
$queryResult = $db->query($query);
$count = $queryResult->size();
if($count < 5){}
2.
$query = "SELECT COUNT(test) AS count FROM test_table WHERE test_no=12345";
$queryResult = $db->query($query);
$result = $queryResult->fetch();
if($result['count'] < 5){}
Also, please let me know if there is another better way to use it
$query = 'SELECT COUNT(1) FROM test_table WHERE test_no=12345';
$queryResult = $db->query($query);
$count = $queryResult->fetchColumn();
This is the best way, assuming you are using PDO. Do not specify a column name in COUNT(), use * or 1. Then use fetchColumn() to get the first column's data.
It's probably better to let MySQL handle row counting. This is more important when large amounts of data are in play. If PHP were in charge of counting the rows, all of that data would need to be sent from MySQL to PHP, only for PHP to then count & discard it. It's better to skip the middle man. So the SELECT COUNT(test) query is the preferable one, of the two choices you provided.
If you're using PDO, the best way is to use PDO's rowCount() method. This methods returns the number of rows returned by the query.
Here's an example.
try
{
$s = $conn->execute("YOUR QUERY HERE");
$count = $s->rowCount();
}
catch(PDOException $e)
{
echo $e->getMessage();
}

Row count with PDO

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.
fetchAll is something I won't want because I may sometimes be dealing with large datasets, so not good for my use.
Do you have any suggestions?
$sql = "SELECT count(*) FROM `table` WHERE foo = ?";
$result = $con->prepare($sql);
$result->execute([$bar]);
$number_of_rows = $result->fetchColumn();
Not the most elegant way to do it, plus it involves an extra query.
PDO has PDOStatement::rowCount(), which apparently does not work in MySql. What a pain.
From the PDO Doc:
For most databases,
PDOStatement::rowCount() does not
return the number of rows affected by
a SELECT statement. Instead, use
PDO::query() to issue a SELECT
COUNT(*) statement with the same
predicates as your intended SELECT
statement, then use
PDOStatement::fetchColumn() to
retrieve the number of rows that will
be returned. Your application can then
perform the correct action.
EDIT: The above code example uses a prepared statement, which is in many cases is probably unnecessary for the purpose of counting rows, so:
$nRows = $pdo->query('select count(*) from blah')->fetchColumn();
echo $nRows;
As I wrote previously in an answer to a similar question, the only reason mysql_num_rows() worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you.
So in PDO, your options are:
Use PDO's fetchAll() function to fetch all the rows into an array, then use count() on it.
Do an extra query to SELECT COUNT(*), as karim79 suggested.
Use MySQL's FOUND_ROWS() function UNLESS the query had SQL_CALC_FOUND_ROWS or a LIMIT clause (in which case the number of rows that were returned by the query and the number returned by FOUND_ROWS() may differ). However, this function is deprecated and will be removed in the future.
As it often happens, this question is confusing as hell. People are coming here having two different tasks in mind:
They need to know how many rows in the table
They need to know whether a query returned any rows
That's two absolutely different tasks that have nothing in common and cannot be solved by the same function. Ironically, for neither of them the actual PDOStatement::rowCount() function has to be used.
Let's see why
Counting rows in the table
Before using PDO I just simply used mysql_num_rows().
Means you already did it wrong. Using mysql_num_rows() or rowCount() to count the number of rows in the table is a real disaster in terms of consuming the server resources. A database has to read all the rows from the disk, consume the memory on the database server, then send all this heap of data to PHP, consuming PHP process' memory as well, burdening your server with absolute no reason.
Besides, selecting rows only to count them simply makes no sense. A count(*) query has to be run instead. The database will count the records out of the index, without reading the actual rows and then only one row returned.
For this purpose the code suggested in the accepted answer is fair, save for the fact it won't be an "extra" query but the only query to run.
Counting the number rows returned.
The second use case is not as disastrous as rather pointless: in case you need to know whether your query returned any data, you always have the data itself!
Say, if you are selecting only one row. All right, you can use the fetched row as a flag:
$stmt->execute();
$row = $stmt->fetch();
if (!$row) { // here! as simple as that
echo 'No data found';
}
In case you need to get many rows, then you can use fetchAll().
fetchAll() is something I won't want as I may sometimes be dealing with large datasets
Yes of course, for the first use case it would be twice as bad. But as we learned already, just don't select the rows only to count them, neither with rowCount() nor fetchAll().
But in case you are going to actually use the rows selected, there is nothing wrong in using fetchAll(). Remember that in a web application you should never select a huge amount of rows. Only rows that will be actually used on a web page should be selected, hence you've got to use LIMIT, WHERE or a similar clause in your SQL. And for such a moderate amount of data it's all right to use fetchAll(). And again, just use this function's result in the condition:
$stmt->execute();
$data = $stmt->fetchAll();
if (!$data) { // again, no rowCount() is needed!
echo 'No data found';
}
And of course it will be absolute madness to run an extra query only to tell whether your other query returned any rows, as it suggested in the two top answers.
Counting the number of rows in a large resultset
In such a rare case when you need to select a real huge amount of rows (in a console application for example), you have to use an unbuffered query, in order to reduce the amount of memory used. But this is the actual case when rowCount() won't be available, thus there is no use for this function as well.
Hence, that's the only use case when you may possibly need to run an extra query, in case you'd need to know a close estimate for the number of rows selected.
I ended up using this:
$result = $db->query($query)->fetchAll();
if (count($result) > 0) {
foreach ($result as $row) {
echo $row['blah'] . '<br />';
}
} else {
echo "<p>Nothing matched your query.</p>";
}
This post is old but Getting row count in php with PDO is simple
$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
This is super late, but I ran into the problem and I do this:
function countAll($table){
$dbh = dbConnect();
$sql = "select * from `$table`";
$stmt = $dbh->prepare($sql);
try { $stmt->execute();}
catch(PDOException $e){echo $e->getMessage();}
return $stmt->rowCount();
It's really simple, and easy. :)
This is an old post, but getting frustrated looking for alternatives. It is super unfortunate that PDO lacks this feature, especially as PHP and MySQL tend to go hand in hand.
There is an unfortunate flaw in using fetchColumn() as you can no longer use that result set (effectively) as the fetchColumn() moves the needle to the next row. So for example, if you have a result similar to
Fruit->Banana
Fruit->Apple
Fruit->Orange
If you use fetchColumn() you can find out that there are 3 fruits returned, but if you now loop through the result, you only have two columns, The price of fetchColumn() is the loss of the first column of results just to find out how many rows were returned. That leads to sloppy coding, and totally error ridden results if implemented.
So now, using fetchColumn() you have to implement and entirely new call and MySQL query just to get a fresh working result set. (which hopefully hasn't changed since your last query), I know, unlikely, but it can happen. Also, the overhead of dual queries on all row count validation. Which for this example is small, but parsing 2 million rows on a joined query, not a pleasant price to pay.
I love PHP and support everyone involved in its development as well as the community at large using PHP on a daily basis, but really hope this is addressed in future releases. This is 'really' my only complaint with PHP PDO, which otherwise is a great class.
Answering this because I trapped myself with it by now knowing this and maybe it will be useful.
Keep in mind that you cant fetch results twice. You have to save fetch result into array, get row count by count($array), and output results with foreach.
For example:
$query = "your_query_here";
$STH = $DBH->prepare($query);
$STH->execute();
$rows = $STH->fetchAll();
//all your results is in $rows array
$STH->setFetchMode(PDO::FETCH_ASSOC);
if (count($rows) > 0) {
foreach ($rows as $row) {
//output your rows
}
}
If you just want to get a count of rows (not the data) ie. using COUNT(*) in a prepared statement then all you need to do is retrieve the result and read the value:
$sql = "SELECT count(*) FROM `table` WHERE foo = bar";
$statement = $con->prepare($sql);
$statement->execute();
$count = $statement->fetch(PDO::FETCH_NUM); // Return array indexed by column number
return reset($count); // Resets array cursor and returns first value (the count)
Actually retrieving all the rows (data) to perform a simple count is a waste of resources. If the result set is large your server may choke on it.
Have a look at this link:
http://php.net/manual/en/pdostatement.rowcount.php
It is not recommended to use rowCount() in SELECT statements!
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
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
A quick one liner to get the first entry returned. This is nice for very basic queries.
<?php
$count = current($db->query("select count(*) from table")->fetch());
?>
Reference
I tried $count = $stmt->rowCount(); with Oracle 11.2 and it did not work.
I decided to used a for loop as show below.
$count = "";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "<table border='1'>\n";
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$count++;
echo "<tr>\n";
foreach ($row as $item) {
echo "<td class='td2'>".($item !== null ? htmlentities($item, ENT_QUOTES):" ")."</td>\n";
} //foreach ends
}// while ends
echo "</table>\n";
//echo " no of rows : ". oci_num_rows($stmt);
//equivalent in pdo::prepare statement
echo "no.of rows :".$count;
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;
}
The simplest way, it is only 2 lines,
$sql = $db->query("SELECT COUNT(*) FROM tablename WHERE statement='condition'");
echo $sql->fetchColumn();
So, the other answers have established that rowCount() shouldn't be used to count the rows of a SELECT statement. The documentation even says, that :
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
https://web.archive.org/web/20220409162106/https://www.php.net/manual/en/pdostatement.rowcount.php
So it's okay for other queries, but not great for SELECT. Most answers suggest that you should make two queries, one to count rows, and one to get the subset of records you need. However, you could query the row count and your subset of the data in one request. This is a bit of an exercise in code golf, but could actually prove more efficient than two requests if the request time is a bit costly and these requests are made frequently.
If you're in PostgreSQL you can provide clean JSON output, like so:
WITH mytable as (VALUES(1,2,3),(4,5,6),(7,8,9),(10,11,12))
SELECT
jsonb_build_object(
'rowcount', (SELECT count(1) FROM mytable)
,'data', (
SELECT jsonb_agg(data.*)
FROM (
SELECT *
FROM mytable
WHERE column1 > 1 -- pagination offset
ORDER BY column1
LIMIT 2 -- page size
) as data
)
) jsondata
Output:
{"data": [
{
"column1": 4,
"column2": 5,
"column3": 6
},
{
"column1": 7,
"column2": 8,
"column3": 9
}
],
"rowcount": 4
}
If you're not in postgres, those functions won't be available, but you could do this:
WITH mytable as (VALUES(1,2,3),(4,5,6),(7,8,9),(10,11,12))
SELECT
(SELECT count(1) FROM mytable) as rowcount
,data.*
FROM (
SELECT *
FROM mytable as mytable(column1, column2, column3)
WHERE column1 > 1 -- pagination offset
ORDER BY column1
LIMIT 2 -- page size
) as data
but it will return the rowcount on every row, which might be a bit wasteful:
rowcount
column1
column2
column3
4
4
5
6
4
7
8
9
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;
}
Here's a custom-made extension of the PDO class, with a helper function to retrieve the number of rows included by the last query's "WHERE" criteria.
You may need to add more 'handlers', though, depending on what commands you use. Right now it only works for queries that use "FROM " or "UPDATE ".
class PDO_V extends PDO
{
private $lastQuery = null;
public function query($query)
{
$this->lastQuery = $query;
return parent::query($query);
}
public function getLastQueryRowCount()
{
$lastQuery = $this->lastQuery;
$commandBeforeTableName = null;
if (strpos($lastQuery, 'FROM') !== false)
$commandBeforeTableName = 'FROM';
if (strpos($lastQuery, 'UPDATE') !== false)
$commandBeforeTableName = 'UPDATE';
$after = substr($lastQuery, strpos($lastQuery, $commandBeforeTableName) + (strlen($commandBeforeTableName) + 1));
$table = substr($after, 0, strpos($after, ' '));
$wherePart = substr($lastQuery, strpos($lastQuery, 'WHERE'));
$result = parent::query("SELECT COUNT(*) FROM $table " . $wherePart);
if ($result == null)
return 0;
return $result->fetchColumn();
}
}
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);
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();
}
Now, if you want to know how many rows are existing in your table and you have for example column 'id' as the primary key, the query to DB will be:
$query = $handler->query("SELECT id FROM your_table_name");
And finally, to get the amount of the rows matching your query, write like this:
$amountOfRows = $query->rowCount();
Or you can write:
$query = $handler ->query("SELECT COUNT(id) FROM your_table_name");
$amountOfRows = $query->rowCount();
Or, if you want to know how many products there are in the table 'products' have the price between 10 and 20, write this query:
$query = $handler ->query("SELECT id FROM products WHERE price BETWEEN 10 AND
20");
$amountOfRows = $query->rowCount();

Categories