Reputation: 2018
I need to run a database query multiple times depending in the User ID. Heres my query:
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234')";
I have an array of user ID's from a seperate query shown here:
while($rows=mysql_fetch_array($allresult)){
$birthdays_today[] = $rows['user_id'];
}
echo $birthdays_today[0];
I want the query to run, but there the "userid" = XXXXX in the query, I want that to be populated with a user ID from the array. This means the query must be ran multiple times and each time, the next ID is entered into the query..
Does this make sense?
Thanks :)
Upvotes: 0
Views: 1032
Reputation: 10648
MySQL has a bulk insert feature.
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234'), ('XXX2', '23234'), ('XXXX3', '3434545')"
<?php
$query = "INSERT INTO wp_scloyalty (userid, value) VALUES ";
$usersToInsert = array();
foreach($birthdays_today as $user_id){
$usersToInsert[] = "($user_id, '01234')";
}
$query .= implode(',', $usersToInsert);
?>
Upvotes: 2
Reputation: 80639
I will only display the script after your $birthdays_today[]
has been populated.
foreach( $birthdays_today as $thisID )
{
mysql_query( "INSERT INTO wp_scloyalty (userid, value) VALUES ('{$thisID}', '01234');" );
}
Upvotes: 0
Reputation: 7438
<?php
foreach($birthdays_today as $uid){
mysql_query(); // ...
}
?>
but
<?php
while($rows=mysql_fetch_array($allresult)){
mysql_query(); // use $rows['user_id'] here
}
?>
Upvotes: 0
Reputation: 3300
Use a for loop and change out the query with sprintf() and string formatting.
Upvotes: 1