Reputation: 57
I pull results from my database, with a while I process each result. Now I would like to run all these results simultaneously. Is this possible with php?
Below I added a example code, I would like to have that for each result the query is executed simultaneously without waiting for the other results to be completed before going to next.
while ($accountdata = mysql_fetch_array($qaccountdata))
{
$un = $accountdata['email'];
mysql_query("INSERT INTO log (id, email, item,height, stamp) VALUES ('', '$un','something','', '" . strtotime('now') . "')");
}
What about something like this? script.php contains the process.
<?php
$q = 1;
$mh = curl_multi_init();
while ($accountdata = mysql_fetch_array($qaccountdata)) {
$a = $accountdata['email'];
$ch.$q = curl_init();
curl_setopt($ch.$q, CURLOPT_URL, 'script.php?id='.$a);
curl_setopt($ch.$q, CURLOPT_HEADER, 0);
curl_multi_add_handle($mh,$ch.$q);
$q++;
}
$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
curl_multi_remove_handle($mh, $ch.$q);
curl_multi_close($mh);
?>
Script.php
if (isset($_GET['type'])) {
$_GET['id'] = $un
//rest of code
}
Upvotes: 0
Views: 196
Reputation: 31839
Avoid doing SQL queries within a loop
A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once.
foreach ($userList as $user) {
$query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
mysql_query($query);
}
Produces:
INSERT INTO users (first_name,last_name) VALUES("John", "Doe")
Instead of using a loop, you can combine the data into a single database query.
$userData = array();
foreach ($userList as $user) {
$userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
}
$query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData);
mysql_query($query);
Produces:
INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")...
Make yourself and your server a favor, read the documentation here and some tips here.
Upvotes: 4