PostgreSQL PHP: Updating Data In a Table
Summary: in this tutorial, you will learn to update data in a PostgreSQL database table using PHP PDO.
Steps for updating data in a database table from a PHP application
To update data in a table, you use these steps:
- Connect to the PostgreSQL database server by creating an instance of the PDO class.
- Call the
prepare()
method of the PDO object to prepare the UPDATE statement for execution. Theprepare()
method returns aPDOStatement
object. - Pass the values to the
UPDATE
statement by calling thebindValue()
method of thePDOStatement
object. - Execute the
UPDATE
statement by calling theexecute()
method of thePDOStatement
object. - Get the number of rows updated using the
rowCount()
method of thePDOStatement
object.
Updating data example
We will use the stocks
table that we created in the creating table tutorial for the demonstration.
The updateStock()
method of the PostgreSQLPHPUpdate
class updates the data in the stocks
table based on a specified id.
We use the PostgreSQLPHPUpdate
class in the index.php
file as follows:
In the index.php script, we connected to the PostgreSQL database and called the updateStock()
method of the PostgreSQLPHPUpdate
class to update the company name of the stock id 2 from Google Inc.
to Alphabet Inc.
Before running the script, we query data from the stocks table to see its current data.
Launch the index.php
file in a web browser; we get the following output.
Let’s recheck the stocks table.
The company name of stock with id 2 has been updated to the new one.
In this tutorial, you have learned how to update data in a PostgreSQL table using the prepared statement in PHP PDO.