Wednesday, 8 August 2018

MySQL: Deleting Rows With The PDO Object.

This is a short tutorial on how to delete rows from a MySQL database using the PDO extension. In this example, I will connect to MySQL using the PDO object before deleting a specific row. For the sake of encouraging good practises, I will be using a prepared statement.
Let’s say that we have a table called cars and that we want to delete every car that is made by Honda. All rows have a column called “make”, which contains the name of the company that manufactured the car.
The code is pretty straightforward:
A step-by-step guide:
  1. We connected to MySQL and instantiated our PDO object.
  2. We constructed a DELETE SQL statement. Note how we also created a placeholder called :make.
  3. We prepared our DELETE statement.
  4. In this example, we are wanting to delete cars with the make “Honda”.
  5. We bind our $makeToDelete variable (Honda) to our :make placeholder.
  6. Finally, we executed the statement and deleted the database rows in question.

0 comments:

Post a Comment