PDO: Updating MySQL using prepared statements.

This a small tutorial on how to update rows in a MySQL database using prepared statements. In this example, I will be using PHP’s PDO object.

For example, let us say that we have a table called cars and that we want to update the row with the ID “90” (it’s Primary Key). In this particular code example, we will be updating the “model” column to “Civic”.

A drill-down of the code above:

  1. We connect to MySQL using the PDO extension.
  2. We create an UPDATE SQL statement using placeholders. In this case, we used the placeholders :model and :id.
  3. We prepare our UPDATE statement.
  4. We set $id to 90 and $model to ‘Civic’.
  5. We bind our variables to the placeholders that we created in Step 2.
  6. We execute the prepared statement. It is at this stage that the row is updated.

Further recommended reading on PDO & MySQL:

Comments

comments