I am wondering the best way to insert a multidimensional array of values into a database – particularly two tables? I created the following foreach loop which creates a query that will insert all the records into one table:
foreach($newPosts as $value) {
if(!isset($postQuery)) {
$postQuery = "INSERT INTO posts (primay_key, col1, col2, col3, col4) VALUES ('$value[0]', FROM_UNIXTIME($value[4]), '$value[2]', '$value[1]', '$value[3]')";
} else {
$postQuery .= "('$value[0]', FROM_UNIXTIME($value[4]), '$value[2]', '$value[1]', '$value[3]')";
}
}
I want to store one of the values in a separate table since the value is particularly large and the row is formatted as Longtext. This value is also rarely called upon when querying the database. I am assuming that moving it into a second table will increase the query speed of the first table? Is that correct?
If I move this value into a second table, I want to link the tables with the primary_key from the first table which is an auto-increment value. How do I loop through this multidimensional array and insert my data into both tables, while inserting the primary_key of the first table into the second? I know I can use LAST_INSERT_ID() if I am running each query one at a time. Some updates will insert hundreds of rows though, so I don’t want to do that.
Thanks in advance!
Not necessarily. It’s only going to affect performance
As you say, you lose the benefits of multi-inserts by splitting it into 2 tables. So your only options are, as you suggest, to insert one record at a time and read back the insert id or (with lots of code an complexity) use a sequence generator and preallocate multiple record ids.