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”.
<?php //Our MySQL connection details. $host = 'localhost'; $user = 'root'; $pass = ''; $database = 'test'; //PDO options. These are optional. $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false ); //Connect to MySQL and create our PDO object. $pdo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options); //Our UPDATE SQL statement. $sql = "UPDATE `cars` SET `model` = :model WHERE id = :id"; //Prepare our UPDATE SQL statement. $statement = $pdo->prepare($sql); //The Primary Key of the row that we want to update. $id = 90; //The new model value. $model = 'Civic'; //Bind our value to the parameter :id. $statement->bindValue(':id', $id); //Bind our :model parameter. $statement->bindValue(':model', $model); //Execute our UPDATE statement. $update = $statement->execute();
A drill-down of the code above:
- We connect to MySQL using the PDO extension.
- We create an UPDATE SQL statement using placeholders. In this case, we used the placeholders :model and :id.
- We prepare our UPDATE statement.
- We set $id to 90 and $model to ‘Civic’.
- We bind our variables to the placeholders that we created in Step 2.
- We execute the prepared statement. It is at this stage that the row is updated.
Further recommended reading on PDO & MySQL:
- Connecting to MySQL.
- Inserting rows with the PDO object.
- Inserting multiple rows with the PDO object.
- Selecting data from MySQL with the PDO object.
- Delete rows from a MySQL table with the PDO object.
- Transactions with the PDO object.