PDO: Insert example.

This is a beginners example on how to insert rows into a MySQL database using PHP’s PDO object. Note that I have also written a tutorial on how to do a multi-insert with PDO. For this tutorial, however, I will be sticking to the basics.

Example MySQL table:

For the purpose of this example, I have created a simple table called cars. Be sure to import the SQL above into your own database if you plan on playing around with the PDO extension.

PDO Insert.

Firstly, we need to connect to MySQL with the PDO object.

Once we have connected to MySQL and selected our database, we can execute a prepared insert statement:

The process of inserting a row into MySQL with the PDO object is actually pretty simple:

  1. We created our INSERT SQL statement. Note how we created “placeholders” such as :make and :model. Later on, these placeholders will allow us to “bind” our data to the statement. Remember that in a prepared statement, there are two rounds of communication with the MySQL server. First, we tell the MySQL about the structure of our statement by “preparing it”. Then, we send the data through by “binding” our data and executing the statement.
  2. We prepared our statement.
  3. We binded the data that we want to insert into our statement.
  4. We executed the statement (thereby executing the SQL query).
  5. Finally, we checked to see if the result of PDOStatement::execute was a boolean TRUE value.

Note that you can re-use the same statement to insert multiple rows:

Note how we executed the same statement twice, without having to prepare a new one for each insert.

Related reading for PDO beginners:

Facebook Comments