循环访问多个SQL查询?

问题描述:

我想通过我的数据库循环,只处理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 kaldoran

限制语法是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