Home » Update MySQL DB Data With PHP PDO

Update MySQL records with the PDO prepare() function, it already has an auto-escaping feature for any given parameter values. Bind the user-input value to the query using one of the following, the named (:name) or the question mark (?) parameter marker.

Requirements:

  • PHP
  • PHP Data Objects
  • PDO Drivers
  • MySQL Functions (PDO_MYSQL)
  • MySQL UPDATE Statement

How to update MySQL database records using PDO in PHP.

The connection to MySQL Database should have successfully already been made. And that the connection object was assigned to $dbh.

Consider below as the employees TABLE inside a MySQL DATABASE.

The objective is to update the first_name using the named (:name) parameter where $id is equal to 2.

$id = 2;
$updated_first_name = 'Peter Richard';
$sth = $dbh->prepare("UPDATE employees SET first_name = :first_name WHERE id = :id");
$sth->execute(array(":fist_name"=>$updated_first_name,":id"=>$id));

Result.

Before.

After.

Next goal is to update the last_name using the question mark (?) parameter where $id is equal to 3.

$id = 3;
$updated_last_name= 'Thompson';
$sth = $dbh->prepare("UPDATE employees SET last_name = ? WHERE id = ?");
$sth->execute(array($updated_last_name, $id));

Result.

Before.

After.

Notes:

  • Always sanitize user inputs.

References:


Posted

in

by

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *