Im trying to read a large XML file and INSERT all the data in the database. I am trying out 3 different scenarios (and I need help with the third):
- After each XML element I do a single query:
$this->mysqli->query($sql);
- I add all the
INSERT
s to a$sql
variable and after the loop I use one multi query$this->mysqli->multi_query($sql);
to INSERT all at once.
I ran tests and both scenarios are not to my liking:
- Inserts all data in the db but runs for 113 seconds. It's not a big problem, but I want to do better!
- This is the option I use for my smaller XML files and it works wonders. For one of my functions it reduced execution time from 6.5s to 0.17s and just as accurate. The problem with this file is: this $sql packet is becoming too large and the script becomes unstable, the output is wrong.
So now I came up with a third, hybrid solution. But It's not working as expected. The idea behind it is to create a $this->mysqli->muli_query($sql);
call after each 200 elements, and then restart the process. I think I'm missing the right understanding of the mysqli->multi_query function, because to me the code below makes perfect sense. But maybe I need to free up / point / next() something?
Anyways: after running the script the database is not completely filled.
As stated, below my code :
if ($xmlObj) {
$sql = "";
$i = 1;
foreach ($xmlObj->Response->FeaturesList->Feature as $feature) {
$sid = $feature["ID"];
$sql .= "INSERT INTO ...;";
// Hybrid solution
if (($i % 200) == 0) {
$this->mysqli->multi_query($sql);
$sql = "";
}
$i++;
}
// Hybrid: Update the leftovers
$this->mysqli->multi_query($sql);
}
UPDATE
Option #4 as added by Mihai works fine. I created an INSERT..VALUES(a),(b),(c)
string and added that using mysqli->query()
Runs 10 second and adds all elements. Thanks
The question about the multi_query mystery remains though!