PHP MySQL: Insert Data Into a Table
Summary: in this tutorial, you will learn how to use PHP PDO to insert data into a MySQL table.
We will use the
tasks
table that we created in the PHP MySQL create table tutorial. If you have not yet created the tasks
table, please follow the tutorial and create it before going forward with this tutorial.
The following picture illustrates the
tasks
table:
To insert data into a table, you follow the steps below:
- Connect to the MySQL database by creating a new instance of the PDO object.
- Construct a MySQL INSERT statement.
- Call
exec()
method of the PDO object.
PHP MySQL Insert data examples
PHP MySQL: insert a new row into a table example
The following example illustrates how to insert a new row into the
tasks
table.
We defined the
InsertDataDemo
class with a constructor that establishes the database connection and a destructor that closes the database connection. Please refer to the PHP MySQL create table tutorial for the code these methods.
Inside the
InsertDataDemo
class, we define a the insert method that calls the exec()
method of the PDO object to execute the INSERT
statement.
The following statement creates an instance of the
InsertDataDemo
class and calls the insert()
method to insert a new row into the tasks table.
Let’s query the data in the
tasks
table:PHP MySQL: insert a single row using prepared statement example
To pass values from PHP to SQL statement dynamically and securely, you use the PDO prepared statement.
First, use MySQL statement with named placeholders as follows:
The :subject, :description, :startdate and :enddate are called named placeholders.
Second, call the
prepare()
method of the PDO object to prepare the SQL statement for the execution:
Third, call the
execute()
method and pass an array that contains the values which are corresponding to the named placeholders.
Putting it all together.
Now we can pass the task’s data to the
insertSingleRow()
method:
Le’ts check the
tasks
table:PHP MySQL Insert multiple rows into a table example
There are two ways to insert multiple rows into a table:
- Execute the
insertSingleRow()
method multiple times. - Construct a MySQL
INSERT
statement that inserts multiple rows and executes it.
Download
You can download the source code of this tutorial via the following link:
In this tutorial, you have learned how to insert data into a MySQL table using PHP PDO prepared statement.
0 comments:
Post a Comment