php - PDO Prepared Inserts multiple rows in single query -
I currently use this type of SQL on MySQL to insert multiple rows of values in a single query Enter: VALUES ('r1v1', 'r1v2'), ('r2v1', 'r2v2'), in the
`TBL` (` key1`, `key2`),. ..
Ready read statement on PDO, should give me better protection than static questions.
So I would like to know if it is possible that "insert several lines of values" using a query "using ready statements
If so, then I know that I How do I apply it?
Insert multiple values with PDO ready statement
According to this page, it is faster than regular inserts, because putting multiple values into an executed statement
$ 'Data field = array (' field ',' field b ', ...); $ data [] = array (' field '= & gt;' value ',' fieldb '= & gt;' Value '....); $ data [] = array (' field '= & gt;' value ',' fieldb '= & gt;' value '....);
More data values or you might have a loop that populates the data.
The fields you are about to enter with the included inclusion need to know, and make the fields ? Placeholder to compel your parameters? .
Insert in the table (field, field, ...) value (?,? ...), (?,? ...) ....
It is basically what kind of statement we want to show.
Now, code:
function placeholder ($ text, $ count = 0, $ separator = ",") {$ result = array (); If ($ count> 0) {for ($ x = 0; $ x & lt; $ count; $ x ++) {$ result [] = $ text; }} Return implode ($ separator, $ result); } $ Pdo- & gt; Starting restriction (); // also helps to speed up your inserts $ Insert_values = array (); Foreign currency ($ data $$) {$ question_marks [] = '('. Placeholder ('?', Size ($ d)). ')'; $ Insert_values = array_merge ($ insert_values, array_values ($ d)); } $ Sql = "Insert in the table (" Implode (",", $ datafields. ")" Value "Implode (',', $ question_marks); $ Stmt = $ pdo- & gt; Ready ($ Sql); {$ Stmt- & gt; Execute ($ insert_values);} Hold (PDOException $ e) {echo $ e-> getMessage ();} $ Pdo- & gt; committed ();
However in my testing, there was only a difference of 1 second when using regular inserts and regular insertions with single value.
Comments
Post a Comment