0

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 :)

1

4 Answers 4

2

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);
?>
Sign up to request clarification or add additional context in comments.

4 Comments

Could even get rid of the loop all together with implode :)
Oh wait, how would that work since we need a value for loyalty too?
Well, it depends if the OP wants 01234 to change or not. If he doesn't you could just set the separater as ', '01234'),('
Ah yeah, I see now. Pretty clever.
1

Use a for loop and change out the query with sprintf() and string formatting.

Comments

0
<?php
foreach($birthdays_today as $uid){
    mysql_query(); // ...
}
?>

but

<?php
while($rows=mysql_fetch_array($allresult)){  
    mysql_query(); // use $rows['user_id'] here
}
?>

Comments

0

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');" );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.