Delete Query using PDO

PHP PDO & MYsQL WE can delete a record using delete query through PDO connection We assumed that config.php file is already available and it is connected to database . id is the unique identity of the record which is to be deleted.
rowcount() to get number of records affected by Query involving any Delete , update & insert command

$step=$dbo->prepare("DELETE FROM pdo_admin WHERE id=:id");
In the above code one record will be deleted from the table based on the id number stored in the variable $id. We can also delete more records matching to a condition.
Let us try to delete all records having id number more than 10.
Here is the code.
$step=$dbo->prepare("DELETE FROM pdo_admin WHERE id > 10 ");
All records having id more than 10 will be deleted. We can also know how many records are deleted by using rowCount() command. This command will return a numeric value saying us number of records deleted by the query just given. Here is the sample code.
$step=$dbo->prepare("DELETE FROM pdo_admin WHERE id > 10 ");
echo " No of records deleted = ".$no;

DELETE with Error Message

To display the error message we will modify the above query like this.
$step=$dbo->prepare("delete from pdo_admin where id > 10 ");
$msg = "No of records deleted =". $step->rowCount();
while (list ($key, $val) = each ($a)  ) {
$str .= "<br>$key -> $val";
$msg .= " Not able to delete record  please contact Admin: Error Message :  $str";

Deleting all the records of a table

We can empty any table by using TRUNCATE command. But after deleting we will not get number of records deleted by using rowCount().
Read More on TRUNCATE command
Here is the code .
$step=$dbo->prepare("TRUNCATE student_del ");
//$step=$dbo->prepare("delete from student_del");

echo " No of records deleted = ".$no;
Above code will delete all records but we won't get any output saying number of records deleted.

By using delete command we can get the number of records deleted in the table.
$step=$dbo->prepare("DELETE FROM student_del");
Use this line ( by removing comment from this and adding comment to TRUNCATE query ) to get number of records deleted.
PDO References Delete Table

Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer