I am passing a DELETE query to mysql using PDO statements. I want to know, whether the query really deletes a row or not? I try to use return value of $stmt->execute()
function delete(){
$stmt = $this->db->prepare("DELETE FROM users WHERE id= :id");
$stmt->bindValue(':id',$_POST[id]);
var_dump($stmt->execute());
}
But This gives always true, even no row is deleted. This gives true even if I don't post any value Or even post same value again and again. May be because query is successful with 0 row deleted , so return value of $stmt->execute() does not help.
So Is There any other way in PDO to know whether any row is really deleted or not, more specifically I want to be sure that only one row was deleted.
So i want something like this
function delete(){
$stmt = $this->db->prepare("DELETE FROM users WHERE id= :id");
$stmt->bindValue(':id',$_POST[id]);
$stmt->execute();
if($rowdeleted == 1){ echo "success";}
else{echo "failure";}
}
Any ideas?
Explanation
In order to know how many rows have been affected for the last operation during the select and Delete you have to GET THE ROW COUNT after the execution of the code.
Conditions:
If the count is greater than 0 - It means the code has affected some operations.
If the count does no return greater than 0 - It means that there is no records to match in the WHERE Clause.
Examples
PDOStatement::rowCount - Returns the number of rows affected by the last SQL statement
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.
Sample Code:
<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();
/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>
Sample Output:
Return number of rows that were deleted:
Deleted 9 rows.
Happy Coding :)
If you are using PDO then you need the rowCount method.
In case of mysqli you need the affected rows
You could try somethign like this:
if($stmt[0]->rowCount() > 0)
{
echo "success";
}
else{
echo "failure";
}
A simple trick is to check the number of row affected
$count = $stmt->rowCount();
Count before update / insert.
so simplified thats what i want to do :
if (select >= 10) { pdo -> Update } else { pdo -> insert }
my idea was to use query :
$select_today_usage = $DBcon->prepare("SELECT kood FROM koodid k WHERE STR_TO_DATE(kpv,'%d.%m.%Y')=current_date");
and then check the row count :
if ($count = $update_kood->rowCount()>=10) {//PDO update } else { //PDO insert }
But i cant access that count anyhow..
I actually meant to use the mysql count() function not PHP's. With your current approach you will select every record in your DB (which can result in high memory costs) I'd do:
SELECT count(*) as the_count
FROM koodid k
WHERE STR_TO_DATE(kpv,'%d.%m.%Y')=current_date and kasutatud=1
then fetch that 1 row and access the the_count index.
$select_today_usage = $DBcon->prepare("SELECT kood FROM koodid k WHERE STR_TO_DATE(kpv,'%d.%m.%Y')=current_date");
$select_today_usage->execute();
$row = $select_today_usage->fetch(PDO::FETCH_ASSOC);
if($row['the_count'] >= 10 ) {
.....
For the longer answer, the PDO rowcount() doesn't work on select statements with mysql.
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.
-http://php.net/manual/en/pdostatement.rowcount.php
I am passing a DELETE query to mysql using PDO statements. I want to know, whether the query really deletes a row or not? I try to use return value of $stmt->execute()
function delete(){
$stmt = $this->db->prepare("DELETE FROM users WHERE id= :id");
$stmt->bindValue(':id',$_POST[id]);
var_dump($stmt->execute());
}
But This gives always true, even no row is deleted. This gives true even if I don't post any value Or even post same value again and again. May be because query is successful with 0 row deleted , so return value of $stmt->execute() does not help.
So Is There any other way in PDO to know whether any row is really deleted or not, more specifically I want to be sure that only one row was deleted.
So i want something like this
function delete(){
$stmt = $this->db->prepare("DELETE FROM users WHERE id= :id");
$stmt->bindValue(':id',$_POST[id]);
$stmt->execute();
if($rowdeleted == 1){ echo "success";}
else{echo "failure";}
}
Any ideas?
Explanation
In order to know how many rows have been affected for the last operation during the select and Delete you have to GET THE ROW COUNT after the execution of the code.
Conditions:
If the count is greater than 0 - It means the code has affected some operations.
If the count does no return greater than 0 - It means that there is no records to match in the WHERE Clause.
Examples
PDOStatement::rowCount - Returns the number of rows affected by the last SQL statement
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.
Sample Code:
<?php
/* Delete all rows from the FRUIT table */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();
/* Return number of rows that were deleted */
print("Return number of rows that were deleted:\n");
$count = $del->rowCount();
print("Deleted $count rows.\n");
?>
Sample Output:
Return number of rows that were deleted:
Deleted 9 rows.
Happy Coding :)
If you are using PDO then you need the rowCount method.
In case of mysqli you need the affected rows
You could try somethign like this:
if($stmt[0]->rowCount() > 0)
{
echo "success";
}
else{
echo "failure";
}
A simple trick is to check the number of row affected
$count = $stmt->rowCount();
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
How can I count the number of rows that a MySQL query returned?
Getting total rows in a query result...
You could just iterate the result and count them. You don't say what language or client library you are using, but the API does provide a mysql_num_rows function which can tell you the number of rows in a result.
This is exposed in PHP, for example, as the mysqli_num_rows function. As you've edited the question to mention you're using PHP, here's a simple example using mysqli functions:
$link = mysqli_connect("localhost", "user", "password", "database");
$result = mysqli_query($link, "SELECT * FROM table1");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
Getting a count of rows matching some criteria...
Just use COUNT(*) - see Counting Rows in the MySQL manual. For example:
SELECT COUNT(*) FROM foo WHERE bar= 'value';
Get total rows when LIMIT is used...
If you'd used a LIMIT clause but want to know how many rows you'd get without it, use SQL_CALC_FOUND_ROWS in your query, followed by SELECT FOUND_ROWS();
SELECT SQL_CALC_FOUND_ROWS * FROM foo
WHERE bar="value"
LIMIT 10;
SELECT FOUND_ROWS();
For very large tables, this isn't going to be particularly efficient, and you're better off running a simpler query to obtain a count and caching it before running your queries to get pages of data.
In the event you have to solve the problem with simple SQL you might use an inline view.
select count(*) from (select * from foo) as x;
If your SQL query has a LIMIT clause and you want to know how many results total are in that data set you can use SQL_CALC_FOUND_ROWS followed by SELECT FOUND_ROWS(); This returns the number of rows A LOT more efficiently than using COUNT(*)
Example (straight from MySQL docs):
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
Use 2 queries as below, One to fetch the data with limit and other to get the no of total matched rows.
Ex:
SELECT * FROM tbl_name WHERE id > 1000 LIMIT 10;
SELECT COUNT(*) FROM tbl_name WHERE id > 1000;
As described by Mysql guide , this is the most optimized way, and also SQL_CALC_FOUND_ROWS query modifier and FOUND_ROWS() function are deprecated as of MySQL 8.0.17
SELECT SQL_CALC_FOUND_ROWS *
FROM table1
WHERE ...;
SELECT FOUND_ROWS();
FOUND_ROWS() must be called immediately after the query.
If you want the result plus the number of rows returned do something like this. Using PHP.
$query = "SELECT * FROM Employee";
$result = mysql_query($query);
echo "There are ".mysql_num_rows($result)." Employee(s).";
Assuming you're using the mysql_ or mysqli_ functions, your question should already have been answered by others.
However if you're using PDO, there is no easy function to return the number of rows retrieved by a select statement, unfortunately. You have to use count() on the resultset (after assigning it to a local variable, usually).
Or if you're only interested in the number and not the data, PDOStatement::fetchColumn() on your SELECT COUNT(1)... result.
The basics
To get the number of matching rows in SQL you would usually use COUNT(*). For example:
SELECT COUNT(*) FROM some_table
To get that in value in PHP you need to fetch the value from the first column in the first row of the returned result. An example using PDO and mysqli is demonstrated below.
However, if you want to fetch the results and then still know how many records you fetched using PHP, you could use count() or avail of the pre-populated count in the result object if your DB API offers it e.g. mysqli's num_rows.
Using MySQLi
Using mysqli you can fetch the first row using fetch_row() and then access the 0 column, which should contain the value of COUNT(*).
// your connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'dbuser', 'yourdbpassword', 'db_name');
$mysqli->set_charset('utf8mb4');
// your SQL statement
$stmt = $mysqli->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();
// now fetch 1st column of the 1st row
$count = $result->fetch_row()[0];
echo $count;
If you want to fetch all the rows, but still know the number of rows then you can use num_rows or count().
// your SQL statement
$stmt = $mysqli->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
$stmt->bind_param('s', $someVariable);
$stmt->execute();
$result = $stmt->get_result();
// If you want to use the results, but still know how many records were fetched
$rows = $result->fetch_all(MYSQLI_ASSOC);
echo $result->num_rows;
// or
echo count($rows);
Using PDO
Using PDO is much simpler. You can directly call fetchColumn() on the statement to get a single column value.
// your connection code
$pdo = new \PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '', [
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
]);
// your SQL statement
$stmt = $pdo->prepare('SELECT COUNT(*) FROM some_table WHERE col1=?');
$stmt->execute([
$someVariable
]);
// Fetch the first column of the first row
$count = $stmt->fetchColumn();
echo $count;
Again, if you need to fetch all the rows anyway, then you can get it using count() function.
// your SQL statement
$stmt = $pdo->prepare('SELECT col1, col2 FROM some_table WHERE col1=?');
$stmt->execute([
$someVariable
]);
// If you want to use the results, but still know how many records were fetched
$rows = $stmt->fetchAll();
echo count($rows);
PDO's statement doesn't offer pre-computed property with the number of rows fetched, but it has a method called rowCount(). This method can tell you the number of rows returned in the result, but it cannot be relied upon and it is generally not recommended to use.
If you're fetching data using Wordpress, then you can access the number of rows returned using $wpdb->num_rows:
$wpdb->get_results( $wpdb->prepare('select * from mytable where foo = %s', $searchstring));
echo $wpdb->num_rows;
If you want a specific count based on a mysql count query then you do this:
$numrows = $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM mytable where foo = %s', $searchstring );
echo $numrows;
If you're running updates or deletes then the count of rows affected is returned directly from the function call:
$numrowsaffected = $wpdb->query($wpdb->prepare(
'update mytable set val=%s where myid = %d', $valuetoupdate, $myid));
This applies also to $wpdb->update and $wpdb->delete.
As it is 2015, and deprecation of mysql_* functionality, this is a PDO-only visualization.
<?php
// Begin Vault (this is in a vault, not actually hard-coded)
$host="hostname";
$username="GuySmiley";
$password="thePassword";
$dbname="dbname";
// End Vault
$b='</br>';
try {
$theCategory="fruit"; // value from user, hard-coded here to get one in
$dbh = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepared statement with named placeholders
$stmt = $dbh->prepare("select id,foodName from foods where category=:theCat and perishable=1");
$stmt->bindParam(':theCat', $theCategory, PDO::PARAM_STR,20);
$stmt->execute();
echo "rowCount() returns: ".$stmt->rowCount().$b; // See comments below from the Manual, varies from driver to driver
$stmt = $dbh->prepare("select count(*) as theCount from foods where category=:theCat and perishable=1");
$stmt->bindParam(':theCat', $theCategory, PDO::PARAM_STR,20);
$stmt->execute();
$row=$stmt->fetch(); // fetches just one row, which is all we expect
echo "count(*) returns: ".$row['theCount'].$b;
$stmt = null;
// PDO closes connection at end of script
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
?>
Schema for testing
create table foods
( id int auto_increment primary key,
foodName varchar(100) not null,
category varchar(20) not null,
perishable int not null
);
insert foods (foodName,category,perishable) values
('kiwi','fruit',1),('ground hamburger','meat',1),
('canned pears','fruit',0),('concord grapes','fruit',1);
For my implementation, I get the output of 2 for both echos above. The purpose of the above 2 strategies is to determine if your driver implementation emits the rowCount, and if not, to seek a fall-back strategy.
From the Manual on PDOStatement::rowCount:
PDOStatement::rowCount() returns the number of rows 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.
This is not a direct answer to the question, but in practice I often want to have an estimate of the number of rows that will be in the result set. For most type of queries, MySQL's "EXPLAIN" delivers that.
I for example use that to refuse to run a client query if the explain looks bad enough.
Then also daily run "ANALYZE LOCAL TABLE" (outside of replication, to prevent cluster locks) on your tables, on each involved MySQL server.
> SELECT COUNT(*) AS total FROM foo WHERE bar= 'value';