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
Comments:
As described in one of your other excellent :-) phpdelusions pages, fetch() can do a (say) "SELECT *" and put the result in an object. (PDO::FETCH_OBJ).
Is there an equivalent for "UPDATE"? I.e. I'd like to write an object back into the DB, the exact inverse of fetching it.
I can imagine writing something to do that, via reflection, that would build the UPDATE statement piece by piece... but, oy vey!
(Quote: "Object-relational mapping is the Vietnam of computer science.")
Reply:
Hello Charles!
I am very amused by your reference, it's my favorite article too!
Well, PDO doesn't have anything out of the box, so it's entirely on you. Reflection is not a requirement if your object can surrender its data, through array access for example. But the code has to be written, yeah. Or you can take one of many ORMs out there. Aura.ORM for example. Eloquent models are quite handy too, and Doctrine and Cycle are very customizable.
Hey YourCommonSense, im in a problem with the UPDATE, three months trying to solve it, and I don't know. In your code using named placeholders are those coming from a form? And something that I can't find the answer, Where :id that's not coming from a form, that's coming from the session, how you write that piece of code. Like that? $uid=$_SESSION['Id']; and after in the form like this, <input type='hidden' name='id' value="<?=$uid ?>" >. Just need some help, thank you.
Just want you to know that your work has helped me understand and implement PDO based queries and data handling from these tutorials and scripts provided here. Its just to say a "BIG THANK YOU".
How to use PDO to INSERT & UPDATE values If i have to identify the value in a column, [ If it is NULL have to : INSERT a value and [If there is a number and have to: UPDATE]
Reply:
Hello Jyoti!
You can simply create a condition in PHP, like
Top Tutorial, Thanks!
Hi, I would ask you if this is the same for pictures or images, can you help me doing the same, but for pictures. Thank you.
I used your PDO UPDATE article as a template which worked well EXCEPT: the form does not retain the updated field values after
confirmation eg form values driven by output of a select while update values are taken from POST. Is another select the only way?
Reply:
Hello Howard!
Yes, that's by design.
PHP execution is atomic. Every time you reload the page, a brand new PHP instance is created that knows nothing of the precious state.
So yes - you have to select the values again but don't worry - it is normal and every PHP app in the world works this way.
Note that if you want to retain the selected value, you have to do it manually, comparing the selected value with every element in the output loop, and adding a "selected" attribute if they match.
I don't know if this is to prevent copy and paste, but I notice your prepare method calls dpo rather than pdo. If it's to prevent random copy/pasting, kudos. If not, I just thought I'd point it out!
Excellent site, I've just discovered it, will be here regularly!
$stmt= $dpo->prepare($sql);
Reply:
Hello Dave!
That was actually a silly typo which I fixed right now. Thank you for letting me know!
how to run update query by using for change boolean value in database column?
Reply:
Hello!
A boolean values is the same as any other. Just pass it to a prepared statement in the execute - that's all!
In the first (unchained) positional parameters example, $id seems to be missing from the array passed to execute.
Reply:
Thank you very much! Fixed!
Placeholders not placeholdreds occurs in more than one place!
Yes I do like the rest.
Placeholders not placeholdreds
Reply:
Hello Andrew!
Thank you very much, fixed!
Hope you liked the rest :)
How does the
SET name=:nameknow to pull the name from the $data array as opposed to some other associative array in the script?Reply:
Hello GrNadpa!
Oh, it was a typo which is fixed now. You are actually sending $data into execute() and this is how it works.
Thank you for pointing out!
I'm trying to code a game demo for my web dev portfolio. I'm pretty new to PHP and I've only learned vanilla JS so far. Here's a problem I've run into: I have an interactive map where a newly registered player must choose a "region" for their character's starting point. These regions include things like "Arctic", "Forest", etc, with 6 options in total. Each region is represented on a map by a clickable icon, each with an ID attribute. Clicking each icon triggers a modal popup with a "Choose Region" button or a "Go Back" button. Here's what my problem is: I'm having trouble storing the user's chosen region in the members table in my SQL database. The table contains a "usrregion" field specifically to store this info, which will be necessary later in the demo. For instance, let's say Player3 wants to choose "Forest". Clicking the "Choose" button in the Forest modal popup should update Player3's row in the members table and store "Forest" in the "usrregion" cell. I've tried writing an update statement but it doesn't have any result. I've been googling this for days now with no luck. Most examples on update statements are for HTML forms with text inputs (such as updating a user's email address), which doesn't apply in my case. Any suggestions would be appreciated.
Reply:
Hello!
I am not sure I understands what your problem is, but I suppose it should be a communication between a browser and PHP. Upon clicking "Choose Region" your HTML page should launch an AJAX request to PHP.
Before doing that, however, you should create a regular HTML form that sends a regular POST request to your PHP. Make sure it works and updates the table. Only after that (knowing that PHP part works all right) you can start with AJAX. There are a lot of examples around.
Feel free to ask if you will have any particular problem to deal with
Hello Still cannot get past the prepare statement. I am using the named placeholders script after trying the other options in the update section. The error message is focused on the prepare statement. Please can you offer me any further guidance. Regards David E.