PHP MySQL: Update Data?
Summary: in this tutorial, you will learn how to update data in a MySQL table using PHP PDO prepared statement.
We are going to use the
tasks
table in the sample database for practicing. If you have not yet created the tasks
table, please follow the PHP MySQL create table tutorial to complete it first.
The following picture illustrates the structure of the
tasks
table.
To update data in a table, you use the following steps:
- First, connect to the MySQL database by creating a new PDO object.
- Second, construct an UPDATE statement to update data. If you want to pass values to the
UPDATE
statement, you use the named placeholders such as:name
. - Third, call the
execute()
method of thePDOStatement
object with an array that contains the corresponding input values of the named placeholders specified in theUPDATE
statement.
PHP MySQL: update data example
PHP MySQL – update a single row
Let’s take a look at the following
UpdateDataDemo
class.
How the script works.
- First, connect to the database by creating a new
PDO
instance in the constructor of theUpdateDataDemo
class. - Second, in the
update()
method, construct theUPDATE
statement with named placeholders. - Third, use a prepared statement to prepare the
UPDATE
statement for the execution and execute it with an array argument.
you can update a row with id 2 using the following script:
You can query data from the
tasks
table to verify the update:
You can download the code via the following link:
PHP MySQL – update rows in related tables
There are three ways to update rows in related tables:
- Use the MySQL UPDATE JOIN statement.
- Use multiple
UPDATE
statements inside a transaction.
We will examine the second way in the PHP MySQL transaction tutorial.
In this tutorial, you have learned how to update data in the MySQL table using the PHP PDO prepared statement.
0 comments:
Post a Comment