Friday 13 July 2018

PHP MySQL: Delete Data

PHP MySQL: Delete Data?

Summary: in this tutorial, you will learn how to delete data from MySQL database table by using PHP PDO.
We will use the tasks table in the sample database for the demonstration. Before going forward with this tutorial, you should follow the PHP MySQL create table tutorial to create the tasks table and insert sample data for practicing.
See the following tasks table.

To delete data in a table, you use the following steps:
  • Connect to the MySQL database by creating a new instance of the PDO object.
  • Construct a DELETE statement to delete a row, multiple rows, or all rows in a table. If you want to delete all rows in a big table quickly and more efficiently, you use the TRUNCATE TABLE statement.
  • Execute the DELETE statement by calling the exec()  method of the PDO object or the execute() method of the PDOStatement object.

PHP MySQL Delete data examples

PHP MySQL: delete a single row example

To delete a single row in a table, you use the DELETE statement with a WHERE clause that specifies which row to delete.
The following script deletes a row with id 2 in the tasks table.
How it works.
In the __construct()  method of the DeleteDataDemo class, we connect to the MySQL database by initiating an instance of the PDO class, and in the __destruct()  method, we close the database connection.
The delete()  method accepts the id as the argument. First, we call the prepare()  method of the PDO object to prepare the DELETE statement for execution, and then we pass an array that contains values corresponding to the named placeholders in the DELETE statement to the execute() method of the PDOStatement object.
To delete the task with id 2, we create an instance of the DeleteDataDemo class and call the delete()method.

PHP MySQL: delete all rows in a table examples

There are two ways to delete all rows in a table:
  • Issue a DELETE statement without a WHERE clause.
  • Issue a TRUNCATE TABLE statement.
The following deleteAll() method deletes all rows in the tasks table using the DELETE statement:
The following truncateTable() method removes all rows in the tasks table as well as resets its autoincrement column’s value:
You can download the source code of this tutorial via the following link:
In this tutorial, we have shown you how to delete data from MySQL table using PHP PDO.

0 comments:

Post a Comment