UPDATE query using PDO
First of all, make sure you've got a properly configured PDO connection variable that is needed in order to run SQL queries using PDO (and to inform you of the possible errors).
In order to run an UPDATE query with PDO just follow the steps below:
- create a correct SQL UPDATE statement
- replace all actual values with placeholders
- prepare the resulting query
- execute the statement, sending all the actual values to
execute()
in the form of array.
UPDATE query with positional placeholders
As usual, positional placeholders are more concise and easier to use
$sql = "UPDATE users SET name=?, surname=?, sex=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$name, $surname, $sex, $id]);
or you can chain execute() to prepare():
$sql = "UPDATE users SET name=?, surname=?, sex=? WHERE id=?";
$pdo->prepare($sql)->execute([$name, $surname, $sex, $id]);
UPDATE query with named placeholders
In case you have a predefined array with values, or prefer named placeholders in general, the code would be
$data = [
'name' => $name,
'surname' => $surname,
'sex' => $sex,
'id' => $id,
];
$sql = "UPDATE users SET name=:name, surname=:surname, sex=:sex WHERE id=:id";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
or you can chain execute() to prepare():
$sql = "UPDATE users SET name=:name, surname=:surname, sex=:sex WHERE id=:id";
$pdo->prepare($sql)->execute($data);
Remember that you should't wrap every query into a try..catch
statement. Instead, let a possible error to bubble up to either the built-in PHP's or your custom error handler.
Related articles:
- SELECT query with PDO
- INSERT query using PDO
- How to connect to MySQL using PDO
- PDO Examples
- Authenticating a user using PDO and password_verify()
- How to check if email exists in the database?
- Select the number of rows using PDO
- How to create a WHERE clause for PDO dynamically
- DELETE query using PDO
- How to create a prepared statement for UPDATE query
- Getting a nested array when multiple rows are linked to a single entry
- How to execute 1000s INSERT/UPDATE queries with PDO?
- Adding a field name in the ORDER BY clause based on the user's choice
- INSERT helper function for PDO Mysql
- PDO Examples
- PDO Examples
Add a comment
Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator's review.
Markdown is now supported:
>
before and an empty line after for a quote