we have a table usersandgroups and it has four rows.I am trying to fetch the row count as per group id but it is returning 1 for every group id but it has many rows......one more point when i remove where clause condition even then it is returning 1...that means it is always returning 1.
<?php
require_once("db_connect.php");
$gp_id = $_POST["GP_ID"];
$query = "SELECT COUNT(*) FROM USER_ANDGROUPS WHERE GP_ID = '$gp_id';";
$res = mysqli_query($con,$query);
if(mysqli_num_rows($res)>0)
{
$row_cnt = $res->num_rows;
echo $row_cnt ;
}
else
{
echo "false";
}
?>
I am trying to fetch the row count as per group id but it is returning 1 for every group id but it has many rows......one more point when i remove where clause condition even then it is returning 1...that means it is always returning 1.
SELECT COUNT(*) FROM will always return a single row which has the complete record number in itself
Change SELECT COUNT(*) FROM to SELECT * FROM and you are good to go
Note: Your code is wide open for SQL INJECTION. so use prepared statements to prevent from that.
mysqli::prepare
Related
So I have this query like this
$sql2 = "SELECT count(*) FROM comments WHERE YourUsername = '$MyUsername' AND PostId = '$PostId'";
if ($result2=mysqli_query($conn,$sql2))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result2);
echo $rowcount;
}
and I have 2 rows in my database which meet the clause requirements but for some reason it keeps outputting 1 as the result. How do I make it display the actual count and not just 1 when in reality the count is 2 and so on for future rows.
You're SELECTing the count of the rows in your first line, so when the query is run, it's returning the row count into $result2. You don't need to use mysqli_num_rows.
Foul
With mysqli I can get the number of rows from a select query by using mysqli_num_rows. I can't find a way to do that with PDO without having to do a separate query like SELECT COUNT(*)? I don't see the point in doing a separate query when I already have a recordset.
You could use SQL_CALC_FOUND_ROWS as documented here. For example:
$result = $db->prepare("SELECT SQL_CALC_FOUND_ROWS id, name FROM fruit WHERE calories > 100");
$result->execute();
$result = $db->prepare("SELECT FOUND_ROWS()");
$result->execute();
$row_count =$result->fetchColumn();
echo $row_count;
This option is normally used to get full match counts when you have a LIMIT clause, however, it works just fine without one, and it's much more efficient than issuing the same query again with a COUNT(*) since it just retrieves the count value stored by the first query value and does not have to run another full query.
In Pdo you use rowCount. Example: $string-> rowCount ();
RTM: http://php.net/manual/en/pdostatement.rowcount.php
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.
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* .... */
I don't want to copy the whole PHP.net page, please just read it.
Why does PDO not have num_rows ?
You may think it's slower to have 2 queries but it isn't. PDO is a general client library for several database systems, not only MySQL. For performance reasons, not everys database system has internal, technical ability to calculate the total rows in select uppon the query. Knowing the total number of rows requires to examine all rows before serving them.
try this:
$sql = "SELECT count(id) FROM `table` WHERE condition";
$result = $db->prepare($sql);
$result->execute();
$row_count =$result->fetchColumn();
echo $row_count;
I have the following code:
$queryMobileNumber = $dbh->prepare("SELECT mobile_number FROM $tableBusinessOwner WHERE business_owner_id = $businessOwnerIDTable");
$queryMobileNumber->bindValue( 1, $mobileNumberNew);
$queryMobileNumber->execute();
echo $businessOwnerIDTable;
echo '-';
echo $queryMobileNumber->rowCount();
I connect to my database using PDO.
The above checks whether a mobile number inserted by the user already exists in the table or not. Regardless if the number exists or not when I echo $queryMobileNumber->rowCount(); the value is always 1.
I am not sure what I'm missing. I am not getting any error in my error_log.
As explained by the PHP documentation
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
Since you're doing a select, rowCount() is not the function you're looking for.
What can you do instead?
<?php
$queryMobileNumber = $dbh->prepare("SELECT mobile_number FROM $tableBusinessOwner WHERE business_owner_id = $businessOwnerIDTable");
$queryMobileNumber->execute();
$res = $queryMobileNumber->fetch(PDO::FETCH_ASSOC);
echo $businessOwnerIDTable;
echo '-';
if(!empty($res['mobile_number')){
echo $res['mobile_number'); //or whatever else
} else {
echo 'N/A';
}
As indicated in this example: http://php.net/manual/en/pdostatement.rowcount.php#example-1009
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.
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
...
If you just want to check if a number exists, the procedure count is less demanding for mysql
You have always to fetch any query you execute in order to get the query's data.. Try this
$queryMobileNumber->execute();
$result = $queryMobileNumber->fetchAll();
echo $result->rowCount();
see documentation
The rowCount of the query you execute (select, insert, delete) will return how many times your query was executed
if($sql = $db->query("Count (*) FROM post_items")){
echo mysqli_num_rows($sql);
}
what's wrong with my code? is this the correct way to echo the total of row in a table?
Your query should be
select count(*) FROM post_items
but echoing
mysqli_num_rows($sql);
will always give 1 as the ans, because count function returns only one row.
Rather fetch the details and show the count
$row = $sql->fetch_row();
echo $row[0];
No it is not; you will always get a return value of 1.
Why? Because you are in essence double-counting. The query executes a COUNT aggregate on the table returning a single row with the counted number. mysqli_num_rows is then counting the number of rows in this result set - the single row - and returns 1.
Try, the following line instead, which should fetch the first (only) column returned of the first (only) row in the result set.
echo $sql->fetch_row()[0]
Note you're also missing a SELECT keyword in your SQL statement.
It should be
if($sql = $db->query("select count(*) FROM post_items")){
echo mysqli_num_rows($sql);
}
I am trying to get a count of items with PDO (on a MySql table). I read somewhere that the rowCount does not work on MySql. Is this correct?
So far I definitely can't get it to work as I keep getting count=0.
Could anyone give me an idea so I can avoid going back to the db every time? I have multiple queries that look similar to this one:
$items = $con -> prepare("SELECT * FROM item_descr ORDER BY $sortBy DESC");
$count = $items -> rowCount();
$items -> execute();
while($info = $items->fetch(PDO::FETCH_ASSOC)) { ... }
I want to try to avoid an extra query with SELECT COUNT (*)
Thanks!
You need to first execute the query. Only then will the database do its work and only then can you get a count of the found results.
As, #deceze indicated,
$items = $con -> prepare("SELECT * FROM item_descr ORDER BY $sortBy DESC");
$items -> execute();
$count = $items -> rowCount();
while($info = $items->fetch(PDO::FETCH_ASSOC)) { ... }
rowCount only works after execute. I have never had a problem with rowCount in MySQL.
Using rowCount is nice, but you could also use your own counter variable if you're going to iterate over the results anyway.
Just to add this is all, please refer to the PHP documentation:
http://www.php.net/manual/en/pdostatement.rowcount.php
Particularly:
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.
And an example from said page:
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
You can simplify your code so much if you are using PDO, such as:
$items = $conn->query("SELECT * FROM item_descr ORDER BY $sortBy DESC")->fetchAll(PDO::FETCH_ASSOC);
if(count($items))
{
// You can count the array to see how many records you got and you can iterate trough it using foreach / for loops
}
else
{
// 0 records returned
}
There is no need for prepared statements in this particular case or checking whether you got any rows back using rowCount. It is true that rowCount CAN fail even with MySQL, it all depends whether you are using unbuffered queries or not.
This works for me:
$my_query = $db->query('SELECT COUNT(*) AS Count FROM the_table');
$c = $my_query->fetch(PDO::FETCH_OBJ);
return $c->Count;
PDOStatement::rowCount() returns the number of rows only affected by a DELETE, INSERT, or UPDATE statement.
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.