I was wondering, what is the best way to count the rows of a table with PHP using PDO?
Here is what I have, but not getting anything for $count.
$count = $con -> query("SELECT COUNT(*) FROM item_descr")->fetch(PDO::FETCH_NUM);
echo $count[0];
if (count($count)>0)
{
$subStatus = "The email introduced is already in our database.";
}
There's no reason to use the PHP count() function on the array returned by fetch(). The count has already been calculated in SQL, so you want the value stored in the result, not the count of results.
Here's how I would write it:
$countStmt = $con->query("SELECT COUNT(*) FROM item_descr");
if ($countStmt === false) {
// do something to report the error
}
$count = 0;
while ($row = $countStmt->fetch(PDO::FETCH_NUM)) {
$count = $row[0];
}
if ($count > 0)
{
$subStatus = "The email introduced is already in our database.";
}
Always check that the return value from query() is a valid PDOStatement. Any error causes it to return false, and the scalar value false is not an object with a fetch() method.
In other words, you can't make the call in a fluent interface manner ($con->query()->fetch()), because query() is not guaranteed to return an object.
$count = $con->query("SELECT COUNT(*) as `num` FROM `item_descr`")
->fetch(PDO::FETCH_ASSOC);
echo $count['num'];
if ( $count['num'] > 0 )
{
$subStatus = "The email introduced is already in our database.";
}
would work.
If you do a COUNT in your query, you will ALWAYS have just ONE result, namely the number of rows. So count( $result) will always give you 1. In my example I use the COUNT from the query.
Related
I'm selecting something in mySQL via PHP and that command returns some array (which is right), but when I put that returning SELECT inside if condition and ask if it is returning null than PHP says it is returning null (which is not right, because it is returning array)
include '../db.php'; // my config
function select($command) {
global $db;
$sql = "".$command."";
$sqlDone = $db -> prepare($sql);
$sqlDone -> execute();
$data = $sqlDone -> fetchAll();
return $data;
}
$select = "SELECT likes.ID, likes.ID_user, likes.ID_post FROM likes WHERE likes.ID_user = '53' AND likes.ID_post = '2'"
if (select($select) == null) { // goes throw this
print_r(select($select)); // returns array
} else {
echo 'not null';
}
I tried to use !is_null and it doesn't work anyway.
I tried to put that select command with same values directly inside phpmyadmin and it returns array, so I'm confused. Can you help me out?
PDO's fetchAll() returns an array, if there are no results, it returns an empty array (not NULL).
Just use empty()
$return = select($select); //put this into a variable, because if you don't, you'll query the database twice and may get different results.
if (empty($return)) { // goes throw this
print_r($return); // returns array
} else {
echo 'not null';
}
Side note, your function doesn't really do anything special. You could achieve the same thing with this:
$return = $db->prepare($select)->execute()->fetchAll();
If you used a PDO wrapper, it could be even shorter. For example, using my own wrapper GrumpyPDO, you would use
$return = $db->all($select);
then if you had variables to pass to the query, you would do
$select = "SELECT likes.ID, likes.ID_user, likes.ID_post FROM likes WHERE likes.ID_user = ? AND likes.ID_post = ?"
$return = $db->all($select, [$userid, $postid]);
I've been running the query oh phpMyAdmin and it shows all the rows, but my query in php only returns the first row.
$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'");
print(count($result)); //always returns 1
for ($x = 0; $x < count($result); $x++) {
$row = mysqli_fetch_row($result);
}
For reference, here's why count() is returning 1. From the manual:
If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable [the parameter] is NULL, 0 will be returned.
Since $result is a resource (object) that is returned from your query, not an array which you would get within your loop getting the actual data out of the resource, count($resource) will return 1.
Your solution is of course to use mysqli_num_rows(). To retrieve data from this resource, you need to loop over it as you are doing, but either use mysqli_num_rows() in place of count(), or other (more common) ways of looping through a result set, like so:
while($row = mysqli_fetch_row($result)) {
// do stuff
}
You have to use mysqli_num_rows($result) function to count rows which are returned by MySQLi query.
Try this
echo mysqli_num_rows($result);
while($row = mysqli_fetch_row($result)) {
// write your code...
}
Use this instead of the for loop
the first thing that the query method returns to you is a resource/object. This query method always return a mysqli_result object for successful queries using SELECT, SHOW, DESCRIBE or EXPLAIN queries . For other successful queries mysqli_query() will return TRUE. For that reason it always count it as "1", what you should try is:
$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'");
$numRows = $result->num_rows;
print(count($numRows)); //it should show you the total amount of rows
//verify the amount of rows before of tryng to loop over it
if ($numRows) {
while($object = mysqli_fetch_object($result)){
//for each loop you will have an object with the attributes of the row
echo $object->song_name;
}
}
This should work,
Regards.
This is not dieing as I expected it to, if $key is not a value in the key_code column of the database. Instead it just continues. I'm probably missing something really simple.
$key = $_GET['k'];
$keycheck = mysql_query("SELECT * FROM ib_dist WHERE key_code = '$key'");
if (!$keycheck) {
die("A database error has occured.");
} else {
mysql_query returns a resource or false based on whether the query executed successfully. It does not in any way denote how many rows were returned or whether the query did anything, only whether it executed successfully.
Check how many results where returned or evaluate the returned result separately.
try checking the amount of rows found.
$key = $_GET['k'];
$result = mysql_query("SELECT * FROM ib_dist WHERE key_code = '$key'");
if (!$result) {
die("A database error has occured.");
} else if (0 == mysql_num_rows($result)) {
// unknown key action
} else {
// known key action
}
I have this PHP function that gets the data of the currently logged in user, or returns false if the visitor either isn't logged in, or has invalid user_id and password_hash cookies. For some reason, $q->fetch() always returns FALSE.
if( $_COOKIE['cuid']!='' && $_COOKIE['cuph']!='' )
{
try
{
$q = $db->prepare( 'SELECT * FROM users WHERE user_id = ? AND password = ?' );
$data = array( $_COOKIE['cuid'], $_COOKIE['cuph'] ); // id and password hash
$q->execute($data);
$num = count( $q->fetchAll() ); // in my case, $num is set to 1
if( $num == 1 )
{
$q->setFetchMode(PDO::FETCH_CLASS, 'User');
$user = $q->fetch(); // $user is set to FALSE for some reason
return $user;
} else {
return FALSE;
}
}
catch( Exception $e )
{
$db->rollBack();
echo 'Error: ' . $e->getMessage();
}
} else {
return FALSE;
}
Running that with exact data instead of placeholders in the query doesn't change anything, and running that query directly in my database returns 1 row, like it should. I checked, $num does indeed equal 1. I don't know why $q->fetch() returns FALSE, so any pointers would be very much appreciated.
You're already fetching all results using fetchAll(). The result set is thereby exhausted, you cannot fetch any more results from it. You simply want $q->rowCount() to count the rows or save the array returned by fetchAll() somewhere and use it later.
As said, you cannot use fetchAll then fetch after one query; but rowCount cannot be used for select. A solution can be:
You get results in an array with fetchAll:
$results=$q->fetchAll()
Then you can get and use or check the number, for example:
echo count( $results);
And get and work with results, for example:
foreach ($results as $result)
{
var_dump($result);
}
I've used PDO in my PHP application. But I have problem with fetch() function. Whenever I count the result of fetch(), it tells me there is something in resultset. But when I want to show them, it has nothing to show.
try
{
$sql = "SELECT id,salt FROM tbl_admin WHERE username = ? AND password = ? LIMIT 1";
$q = $db->prepare($sql);
$q->execute(array($username,$password));
$rows = $q->columnCount();
if ($rows > 0)
{
$r = $q->fetch(PDO::FETCH_BOTH);
echo(count($r).'<br />'); // Prints 1
print_r($r); // Nothing to print ...
die();
}
else
{
die('error');
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
May you help me please?
You're counting the number of columns, not the number of rows.
$rows = $q->columnCount();
This should be
$rows = $q->rowCount();
That said, rowCount is for UPDATE, INSERT, or DELETE queries. So that isn't the problem here.
Firstly should also be checking if $q->execute returns true or false.
Secondly you should be checking if $q->fetch returns true or false.
Given your code
$r = $q->fetch(PDO::FETCH_BOTH);
echo(count($r).'<br />'); // Prints 1
Try the following.
echo(count(false));
You'll notice that this also outputs 1.
So the solution is, that you need to check the return value of $q->fetch before assuming it returned a valid row.