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 . mem_id is the unique id of the record which is to be deleted.


$count=$dbo->prepare("DELETE FROM pdo_admin WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT);
$count->execute();
In the above code one record will be deleted from the table based on the id number stored in the variable $mem_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.
$count=$dbo->prepare("delete from pdo_admin where id > 10 ");
$count->execute();
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.
$count=$dbo->prepare("delete from pdo_admin where id > 10 ");
$count->execute();
$no=$count->rowCount();
echo " No of records deleted = ".$no;

DELETE with Error Message

To display the error message we will modifiy the above query like this.
$count=$dbo->prepare("delete from pdo_admin where id > 10 ");
if($count->execute()){ $msg = "No of records deleted =". $count->rowCount(); }else{ $str=''; $dbo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); $a=$count->errorInfo(); 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 .
$count=$dbo->prepare("TRUNCATE student_del ");
//$count=$dbo->prepare("delete from student_del");

$count->execute();
$no=$count->rowCount();
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.
$count=$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.

Visitors Rating
Your Rating





Post your comments , suggestion , error , requirements etc here .




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