Update a MySQL record using PDO in PHP

July 21, 2013 | 911 views | Comments

Access MySQL database using PDO in PHP and update MySQL records with the 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.

For example.

Update a record using the named (:name) parameter where $value and $id are user-input values.

$value = $_GET['value'];
$id = $_GET['id'];
$sth = $dbh->prepare("UPDATE TABLE SET value = :value WHERE id = :id");
$sth->execute(array(":value"=>$value,":id"=>$id));

Update a record using the question mark (?) parameter $value and $id are user-input values.

$value = $_GET['value'];
$id = $_GET['id'];
$sth = $dbh->prepare("UPDATE TABLE SET value = ? WHERE id = ?");
$sth->execute(array($value,$id));

Make sure a PDO connection to a MySQL database has already been successfully made. The connection object was instantiated on $dbh on the examples given above.