Home » Delete MySQL DB Data With PHP PDO

It’s easy to delete a MySQL record using PDO in PHP, just make sure a PDO connection to the MySQL database has been successfully established, and more importantly, use the PDO prepare() function to auto escape any parameter values. Select from the named (:name) or the question mark (?) parameter marker to bind any given or user-input value to the query.

Requirements:

  • PHP
  • PHP Data Objects
  • PDO Drivers
  • MySQL Functions (PDO_MYSQL)
  • MySQL DELETE Statement

How to delete MySQL database records using PDO in PHP.

This assumes that a successful connection to MySQL Database has already been made. And that the connection object was assigned to $dbh.

Consider below as the employees TABLE inside a MySQL DATABASE.

The objective is to delete the record with the id equal to 2 using the named (:name) parameter.

$id = 2;
$sth = $dbh->prepare("DELETE FROM employees WHERE id = :id");
$sth->execute(array(":id"=>$id));

Result.

Try to delete a record using the question mark (?) parameter where the id is equal to 3 as the next goal.

$id = 3;
$sth = $dbh->prepare("DELETE FROM employees WHERE id = ?");
$sth->execute(array($id));

Result.

Notes:

  • Always sanitize user inputs.

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *