I could swear that I had this working last week, but now I get errors.
In PHP I have a large CSV file that I run through a foreach loop and in this loop I have a created a variable that adds an UPDATE line to itself, like this:
foreach ($csv->data as $value){
$updater .= "UPDATE tblProduktData SET xtra = 2 WHERE id = '$value[1]';";
}
mysql_query("$updater") or die(mysql_error());
The CSV file contains over 3000 lines so having the mysql_query() inside the loop obviously makes the process slow and is not recommendable.
Can anyone tell me if I'm missing something or just doing it wrong?
We will temporarily ignore the fact that you are using a PHP extension mysql_ that has been deprecated ( Scheduled for removal from the language) for a number of years now.
For some reason you are adding to the sql query each time through the loop by using the .=
syntax. I assume you thought you could run more than one query at a time using the mysql_ extension, but you cannot.
So try this :-
foreach ($csv->data as $value){
$updater = "UPDATE tblProduktData SET xtra = 2 WHERE id = '$value[1]'";
mysql_query($updater) or die(mysql_error());
}
This is in fact a perfect candidate for using mysqli_ or PDO prepared statements.
Try this:
$id = "0"; // initialze the ids to update with a non-existing value
// fetch all the ids into a variable
foreach ($csv->data as $value){
$id .= "," . $value[1]
}
$updater .= "UPDATE tblProduktData SET xtra = 2 WHERE id in (".$id.") ;";
mysql_query("$updater") or die(mysql_error());