2013-11-26 48 views
0

我從我的數據庫中取得結果,並且一段時間處理每個結果。現在我想同時運行所有這些結果。這可能與PHP?同時運行foreach結果php

下面我添加了一個示例代碼,我希望對每個結果都可以同時執行查詢,而無需等待其他結果在下一步之前完成。

while ($accountdata = mysql_fetch_array($qaccountdata)) 
{ 
    $un = $accountdata['email']; 
    mysql_query("INSERT INTO log (id, email, item,height, stamp) VALUES ('', '$un','something','', '" . strtotime('now') . "')");    
} 

這樣的事情呢? script.php包含進程。

<?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 
    } 
+0

請參閱http://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-applications – MeNa

+0

它可以做到嗎? '$計數=結果 爲量($ I = 0; $ I <$計數; $ I + = 1) { 而($ accountdata = mysql_fetch_array($ qaccountdata)) { } }' – user3009108

+0

NO。 'mysql_fetch_array($ qaccountdata)'會阻止你的程序,直到他結束。 – MeNa

回答

4

避免做一個循環

一個常見的錯誤是把一個SQL查詢一個循環內內SQL查詢。這導致數據庫的多次往返,以及腳本的速度明顯較慢。在下面的示例中,您可以更改循環以構建單個SQL查詢並一次插入所有用戶。

foreach ($userList as $user) { 
    $query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")'; 
    mysql_query($query); 
    } 

產地:

INSERT INTO users (first_name,last_name) VALUES("John", "Doe") 

而不是使用一個循環,你可以將數據合併到一個單一的數據庫查詢。

$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); 

產地:

INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")... 

讓自己和你的服務器的忙,閱讀文檔here和一些技巧here