Oj Obasi
Oj Obasi

I am also and will continue to be a student of web design and development. My tutorials may not be for you. If you feel that way, then search online for better tutorials.

PHP PDO Update Data in MySQL

In this tutorial, we will be using php prepared statement to update information in our 'products' table.

We will be updating table row with id = 1(WHERE id=1).

We would change the 'product_name' from let say 'Blue Shirt' to 'Yellow Shirt'. Remember , you can only use the sql UPDATE statement to update existing data.

<?php
require 'database.php';
try{
$sql = "UPDATE products SET product_name='Yellow Shirt' WHERE id=1";

// Prepare statement
$stmt = $db->prepare($sql);

// execute the query
$stmt->execute();

// echo a message to say the UPDATE succeeded
echo "UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>

If you forget to use the WHERE id=1, all records in your database will be updated.