PostgreSQL PHP: Delete Data From a Table
Summary: This tutorial shows you how to delete data from a PostgreSQL table using the PHP PDO.
Steps for deleting data in the PostgreSQL using PHP PDO
To delete data from a PostgreSQL table in PHP, you use the following steps:
- Connect to the PostgreSQL database server by creating an instance of the PDO class.
- Prepare the DELETE statement for execution by calling the
prepare()
method of the PDO object. Theprepare()
method returns aPDOStatement
object. - Bind values to the DELETE statement by calling the
bindValue()
method of thePDOStatement
object. - Execute the
DELETE
statement by calling theexecute()
method. - Get the number of rows deleted using the
rowCount()
method.
Deleting data examples
We will use the stocks
table for the demonstration. If you have not created the stocks
table yet, you can follow the creating table tutorial.
Let’s create a new class named StockDB that contains all the methods for deleting data in a table.
The following delete()
method deletes a row specified by id from the stocks
table
The following deleteAll()
method deletes all rows from the stocks
table.
Before running the methods, we query the data from the stocks
table.
Use the following code in the index.php file to delete the row with id 1.
The following is the output:
We query data from the stocks table again to verify.
The row with id 1 was deleted as expected.
In the index.php
file, modify the code to call the deleteAll()
method instead of the delete()
method and execute it. The following is the output of the script:
The following shows the output when we query data from the stocks
table.
All rows in the stocks table have been deleted as expected.
In this tutorial, we have shown you how to delete data from a PostgreSQL table in the PHP application using PDO API.