INSERT query using PDO
- INSERT query with positional placeholders
- INSERT query with named placeholders
- INSERTing multiple rows
- Comments (31)
First of all make sure you've got a properly configured PDO connection variable that needs in order to run SQL queries with PDO and to inform you of the possible errors.
In order to run an INSERT query with PDO just follow the steps below:
- create a correct SQL INSERT statement
- replace all actual values with placeholders
- prepare the resulting query
- execute the statement, sending all the actual values in the form of array.
INSERT query with positional placeholders
As usual, positional placeholders are more concise and easier to use
$sql = "INSERT INTO users (name, surname, sex) VALUES (?,?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$name, $surname, $sex]);
or you can chain execute() to prepare():
$sql = "INSERT INTO users (name, surname, sex) VALUES (?,?,?)";
$pdo->prepare($sql)->execute([$name, $surname, $sex]);
Important! You don't have to check the result of
execute()(as it is often shown in low-quality tutorials). Such a condition will make no sense, as in case of error, a PDOException will be thrown and the script execution will be terminated, which means such a condition will never reach theelsepart.
Neither atry ... catchoperator should be used, unless you have a specific scenario to handle the error, such as a transaction rollback shown below. Please see the article about error reporting for the details.
INSERT 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,
];
$sql = "INSERT INTO users (name, surname, sex) VALUES (:name, :surname, :sex)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
or you can chain execute() to prepare():
$sql = "INSERT INTO users (name, surname, sex) VALUES (:name, :surname, :sex)";
$pdo->prepare($sql)->execute($data);
Important! The only characters allowed in the placeholder names are Latin letters, numbers and underscores. No umlauts or dashes ar any other characters are allowed. It's also a good idea to keep all the letters lowercase.
INSERTing multiple rows
As it's explained in the main article, a once prepared statement could be executed multiple times, slightly reducing the overhead on the query parsing. So it makes sense to use this feature when we need to insert multiple rows into the same table. Just a couple notes before we begin:
- make sure that the emulation mode is turned off, as there will be no speed benefit otherwise, however small it is.
- it's a good idea to wrap our queries in a transaction. In some circumstances it will greatly speed up the inserts, and it makes sense overall, to make sure that either all data has been added or none.
So in the end our code would be like
$data = [
['John','Doe', 22],
['Jane','Roe', 19],
];
$stmt = $pdo->prepare("INSERT INTO users (name, surname, age) VALUES (?,?,?)");
try {
$pdo->beginTransaction();
foreach ($data as $row)
{
$stmt->execute($row);
}
$pdo->commit();
}catch (Exception $e){
$pdo->rollback();
throw $e;
}Related articles:
- SELECT query with PDO
- UPDATE 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:
Excellent, very well explained and didactic Thank you
I read your bit on not needing to check the status of execution. I'm curious, if I needed to know whether the execute was successful or not so that a microcontroller knows whether it needs to send the request again or not, would I get a different HTTP code if the execute failed? ie: HTTP code 200 for success and anything else for failure?
Reply:
Hello Michael!
It's explained in another article and rather irrelevant to PDO: https://phpdelusions.net/articles/error_reporting
Basically you need to configure PHP so that it returns a 500 HTTP status in case of a fatal error. And a failed insert query is such an error. Just make sure that ERRMODE_EXCEPTION is used for PDO.
While 200 status is returned by default. Which means that as a rule, you don't need any special code to handle failures! It makes your code much shorter and cleaner.
Only in case you need to send some custom HTTP status, like 599 (or any other special treatment) for some selected query, then you can enclose it inside a try-catch where you can do some custom handling.
Brilliant, thank you for that. My problem is twofold, in that I am coming to PDO afresh and (primarily) my predecessor who wrote the website's code used a construct that I can find nowhere in any other specialist site (like yours). Strangely, she included the config.php file in every page (although the variable produced is not used elsewhere on the site) and then included db.php (with a correctly-formatted $pdo) prior to every QUERY, INSERT, etc.
I now know where to go and what to do to regularise the situation thanks to your advice. Thank you so much.
Thank you for the (very swift) response. However, if the config.php (which I now have coded to copy your example) is required on every page, is it still necessary to include the db.php file for every query? In fact, if db.php simply includes the try{} element of the config.php file, is it necessary to include it at all?
I'm not sure what 'rolled back' means; I'll go looking for it on your pages, but ....
Reply:
Look.
config.php is just integral part of db.php. It is made into a separate file so it will be the only file one has to edit moving the code to another server. But logically it's the same file. And should be used the way was explained above: db.php should be included strictly ONCE on every page. While config.php just gets included in db.php and none of our concern.
Either way, the point is, the connection should be made only once. Whatever file the connection code in. BY NO MEANS db.php should be included for the every query.
Now to your problem. It's hard to tell actually.
By the look of it, it seems that somewhere in your code a transaction is started but never commited. A transaction is not a synonym for executing an SQL query as you seemingly think. It has a very special meaning. It is not explained on this site because it's a database stuff while the site is PHP related. But you can google it up.
In case transactions are used, including db.php for the every query will actually roll back the previously executed query. So it possible could be the reason why insert queries don't work.
A friend owns a bed&breakfast website that uses PDO to insert and administer bookings, along with limited maintenance of the text/narrative and photos associated with each page. I inherited the maintenance of the site when it needed a new home, but a recent upgrade of MariaDB to 10.10.3 seems to prevent INSERT operations (although I can see them in the general log that I've activated. I wonder if there is anything in the MariaDB upgrade that might have affected things? The site uses a config.php file with code unlike your example and a db.php file that is accessed on EVERY transaction. Should I think about rewriting the PDO code?
Reply:
Hello Janette!
there was nothing in to 10.10.3 to affect such a fundamental query as INSERT.
given you can see these queries in the general Log, I suppose it has something to do with transactions. Make sure they aren't rolled back.
Speaking of creating the new PDO connection every time the query gets executed, it should be definitely rewritten. The connection should be made strictly once per script execution.
Is it OK to use the ON DUPLICATE KEY UPDATE feature of mysql when using PDO ?
If so, how is this best achieved using named placeholders?
If not, what is the best approach when I want to insert a record if it doesn't exist, but update if it does? Is it best to check if the record key exists with SELECT and then deciding? Does this need to be done in a transaction?
Thanks for your help David
Reply:
Hello David!
Yes, any SQL functionality is OK to use with PDO by default.
Given no data input should be involved in the ON DUPLICATE part, you just use a regular INSERT query with named placeholders as usual.
While in ON DUPLICATE part you just reference the entered value with VALUES() function like
and it will use the :baz_param value with update.
Though this VALUES() function is deprecated now but you can find the new syntax on mysql man page or stack overflow.
i am trying for three months to learn php. I hope my question will not make you waste your time. How can i insert multiple fields of the html form into a database using oop php? Thank you!
Reply:
Ahaha, thank you man! It was a funny one. Damned autocorrect :)
this is my code: <?php require_once('models/Garrard.php'); $dbh = Db::connect();
I tried your code but still returning nothing
Thank you so much for your time and help!!
Hello, thank you so much for this website. I am struggling with a function to update a record, and i kindly ask for your help on using placeholders to secure the prepared statement of said function.
The data i use to update the record is in the following format:
And the function to update the record is the following:
Currently the function "works", but malicious data can still be injected since is is not using placeholders. However im stuck at where and how exactly i should put those placeholders. I'd be grateful if you point me in the right direction. Cheers
Reply:
Hello Giorgio
You almost did it, just add placeholders instead of values, that's it
I am using positional placeholders as for the dynamically created query it doesn't matter but using positional can save you a headache or two.
Notice the silly protection part. This is very important, as keys are going into the query as is. And it would be much better to filter the keys using the white list approach but I do understand that for such a function it would be hard to implement it.
Besides, your questions let me make my articles even better, so you are more than welcome to ask any question you got.
should read "...any question you HAVE." Use of "got" is not idiomatic English in this context.
Reply:
Thank you very much, fixed on the spot!
In the below example, isn't $data supposed to be a nested array of values? Otherwise, wouldn't the foreach return each value separately for the execute() line instead of in groups of 3? e.g. John then Doe then 22 instead of [John, Doe, 22]
Thanks
Reply:
Hello!
Thank you so much! I can't believe i missed this part. You are absolutely correct, I missed the extra brackets. Fixed now, and thank you again!
Not a question, just thanks for making a great website. Being relatively new to PHP I use the site all the time.
INSERTing multiple rows
Pls I'm getting this error when I try to insert multple rows
this is my code
by the way thanks for the great tutorials
Reply:
Hello Lynn!
Unless I am overlooking something, this this code should work.
From the error it is evident that your array is not 2-dimansional as shown in your code but 1-dimensional. Check your input array.
Are you using any of text editor
If you fail to set the PDO::ERRMODE_EXCEPTION attribute the insert execute call can return a 0 (duplicate key error or whatever) and not throw an exception. You might want to reinforce that in your warning.
Sorry, but telling people not to check a return status if a call can potentially return one is bad form. Unless you work for Microsoft, and then silent bugs are expected. :-)
Reply:
Hello Andrew
I am afraid you are a bit wrong on this account. An uncaught exception is anything but a "silent bug".
And yes, you must not fail to set the PDO::ERRMODE_EXCEPTION. This is an obligatory prerequisite.
Chicken Noodle Soup
j
hi, are you sure that opening a transaction in the try section of a try/catch block will work? In my experience an 'no transaction started" is thrown. Keep up the good work.
Thanks so much for your advice! It was a spelling error indeed. I appreciate the help
Thanks for the incredibly fast response! I have the code set up as you advised, but I am getting an error on the second insert: Error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.
I checked all of my variables and they appear to be valid, but I am not sure about the lastInsertId(); I am using:
right after my $stmt->execute();
Should I be using a different connection string on the second PDO insert?
Reply:
The error message you get means that no parameter was defined in the query. Double-check the spelling.
The code for getting the id is OK.
I am trying to see if I can execute multiple PDO Insert statements in order to update two different tables from the same form information. To further complicate the question, I would like to take the resulting table ID from the first insert and use it in the second statement.
Reply:
Hello Ed!
Nothing could be simpler, just do what you said:
that's all.
if you want to make sure that both queries successfully executed, wrap your inserts into a transaction
Can you help me with this INSERT from your example above?
I interpret the message to say $pdo is undefined. If so, what is $pdo?
Receive error: Notice: Undefined variable: pdo in E:\web\peoplespoll\htdocs\TestBed\insertuser2.php on line 37
Fatal error: Uncaught Error: Call to a member function prepare() on null in E:\web\peoplespoll\htdocs\TestBed\insertuser2.php:37 Stack trace: #0 {main} thrown in E:\web\peoplespoll\htdocs\TestBed\insertuser2.php on line 37
Connect string:
I'd be very grateful for your help.
Reply:
Hello Parker!
Sure I can. Your case is very simple actually. Look, in your connect string you are assigning a PDO instance to $dbconnect variable which is not used anywhere, but in your code you are using $pdo variable which is, naturally, nowhere defined.
For all database interactions you need a variable assigned in your connection string. You just should stick to a single variable name, I would suggest $pdo as it is shorter to type.
Besides, your connection string lacks a lot of essential options, consider using a canonical one instead: https://phpdelusions.net/pdo_examples/connect_to_mysql
Hi, Do you have some knowledge in REMEDY system?
Thanks for the great articles round PDO.
Can I prepare 2 statements and execute the one or the other in a loop?
I have to sync a table with a dataset Can I prepare an update and an insert statement and then check in a loop, if the row exists, update the data else insert a new row?
Or what is the best way to sync a table (with also extra (local) fields) and a dataset
Many thanks in advance,
Filip
Can you include in your example also an SELECT LAST_INSERT_ID() ?
Are you sure you really wanted
I mean, shouldn't this be "$pdo" (starting with a 'p') :)
I'm not sure because you have it in more than one place.
Reply:
Hello Konrad!
You are right it's a typo, just copy-pasted multiple times. Corrected now, thank you very much!
This is good stuff here. Thank you for the entire website and reference.
Lets say I have 500k line file and I break it into 10 chunks 50k records each chunk....
execute($data) not working of course.
Now, after reading your tutorial I have the following foreach loop:
Which works GREAT, but I wonder about performance...
Questions: A: Is there some equivalent that will allow multiple VALUES to be placed into 1 PDO execute statement?
B: Is foreach and PDO execute() really the way to go here? (speed, safety)
C: Is there some other method to examine?
Reply:
Hello Christian!
Thank you for the good questions.
Although you can create one big INSERT query with multiple values, like
it won't be cross-platform, as not all databases support such syntax.
So I would suggest to stick with single inserts, but with one difference: perpare() should be called only once, that's the very idea behind this statement. So your loop should be rewritten as
so it should gain you some 5% of the performance improvement.
I just updated the article showing the correct example.
Also, please note the you are adding identifiers to the query directly ($_table, $headers). It is always prone to errors and injections. Make sure you whitelist or at least format them properly.
Why is your grammar so bad?
Reply:
Hello Martin!
English is not my native language. But I am trying to improve.