2017-03-09 78 views
1

我想通過我的數據庫循環,只處理100行,準時,否則我的內存將耗盡。循環訪問多個SQL查詢?

但我的問題是,我不知道,爲什麼我的腳本沒有增加開始和結束的限制。所以我只得到一個回報,並且不會通過將開始和結束限制增加+100來循環訪問我的數據庫。

有沒有人看到我的失敗?

$count_values = mysqli_num_rows($values_gk); 
$count_values = intval($count_values); 
$myfile = fopen("httpdocs/wp_all_import.txt", "a"); 

if($values_gk === FALSE){ 
    fwrite($myfile, "SQL Error\n"); 
} 

$start = -100; 
$end = 0; 

do{ 
$start = $start + 100; 
$end = $end + 100; 

if($end > $count_values){ 
    $end = $count_values; 
} 

$values_gkw = $database_gk->query("SELECT `ID` FROM `fWR6qIN_posts` where post_type = 'product' AND post_status = 'publish' limit $start, $end"); 

fwrite($myfile, "Entered 1. While Loop\n"); 

while($row = $values_gkw->fetch_assoc()){ 

    if($row["ID"] != null){ 
     //do something with the values 
     //code removed to reduce the text here 
    } 
} 

fwrite($myfile, "\n+++ Start: " .$start. " Limit: " .$end. " +++\n\n"); 

} while ($end <= $count_values); 

計數值:(檢查無極限讓所有行的量)

$values_gk = $database_gk->query("SELECT `ID` FROM `fWR6qIN_posts` where post_type = 'product' AND post_status = 'publish'"); 
$count_values = mysqli_num_rows($values_gk); 
$count_values = intval($count_values); 

問候和感謝!

+2

「只能處理100行,準時,否則我的RAM將耗盡」。 。 。告訴更多。這不是1980年。 –

+0

這段代碼看起來不錯。什麼值存儲'$ count_values'? –

+0

如果'$ end> $ count_value',你將會遇到問題。然後你設置'$ end'等於'$ count_value'。但是你的do-while循環,而'$ end <= $ count_values'。自從你設置它們相等,這是真的。 **你將得到一個infinit循環**! – kaldoran

回答

0

限制語法是LIMIT offset, count NOT LIMIT offset_start, offset_end。 它將在循環的第一次迭代中選擇100行,但會在循環的第二次迭代中選擇200行,因爲第二次迭代中的$end = 200和第三次迭代中的300行等等。

並按照kalrodan的規定,您的代碼會生成無限循環。

我在代碼中做了幾個更正。試試這個:

$start = -100; 
$limit = 100;//constant never changes 
$count = 0; 
do{ 
    $start = $start + 100; 
    $count = $count + 100;//see changes here 

    if($count > $count_values){//see changes here 
     $limit = $count_values - $start;//see changes here 
    } 

    $values_gkw = $database_gk->query("SELECT `ID` FROM `fWR6qIN_posts` where post_type = 'product' AND post_status = 'publish' limit $start, $limit");//$start, $limit here 

    fwrite($myfile, "Entered 1. While Loop\n"); 

    while($row = $values_gkw->fetch_assoc()){ 

     if($row["ID"] != null){ 
      //do something with the values 
      //code removed to reduce the text here 
     } 
    } 

    fwrite($myfile, "\n+++ Start: " .$start. " Limit: " .$end. " +++\n\n"); 

} while ($count < $count_values);//condition change here too 
+0

我仍然在一個無限循環中結束。他只是繼續,但當然,沒有什麼可以選擇的。但我沒有得到失敗? – ThisIsDon

+0

@ThisIsDon我在本地數據庫上測試了這個確切的代碼,它工作得很好。我得到的一點警告是'$ end'沒有在'fwrite'行定義,因爲我刪除了'$ end',但忘記從'fwrite'行中刪除它。並確保您使用完全相同的代碼,不要忘記更改'do-while'循環條件。我在很多地方做了更正,所以只需複製粘貼整個代碼並嘗試。 – Zeus