This is a short tutorial on how to carry out a multi-insert with PHP’s PDO object. In this particular example, I will also be using prepared statements to guard against SQL injection.
Our example MySQL table looks like this:
As you can see, I’ve kept it extremely simple. Because id is an AUTO_INCREMENT column, the only columns that we need to worry about are name and dob.
For this example, I’ve created a custom function that you can reuse to your heart’s content:
This function takes in three parameters:
- The name of the table that we are inserting data into.
- The data that we are inserting (in this case, it is a multi-dimensional array, with each array representing a row that we want to insert).
- Our PDO object.
Step-by-step explanation of what this custom function is doing:
- We set up an array called $rowsSQL. This array will contain SQL snippets that we will “implode” / “glue” at a later stage.
- We set up an array called $toBind. This array will contain the parameters and values that we need to bind to our prepared statement before execution.
- We grab that column names from the first row. Remember, all rows must have the same number of columns!
- We loop through our $data array. Inside this loop, we construct our parameter names and we store the values that we need to bind. We also create the SQL snippets / strings that will be used in our multiple insert statement.
- We construct our SQL statement using the $tableName variable and the SQL snippets that we stored in our $rowsSQL array.
- We prepare our statement.
- We loop through our $toBind array, which contains the row data that we need to bind.
- We execute our prepared statement (this is where the multi-insert actually occurs).
Inserting multiple rows into MySQL with PDO.
OK, so our custom function is setup and it is ready for business. How do we use it?
As you can see, it’s actually pretty simple. We create a multidimensional array that contains multiple associative arrays that represent our rows! We supply that array to our custom function, which carries out the multi-insert.
0 comments:
Post a Comment