简体   繁体   中英

PHP while loop iterates only once

Quick Question;

$sql = mysql_query("SELECT * FROM cronjobs WHERE status = 0 ");

while($cronjob = mysql_fetch_array($sql)){
    if($cronjob['suid'] != $cronjob['cuid']){
        //echo 'not equal<br>';
        $set = 0;
        $sid = $cronjob['sid'];
        $suid = $cronjob['suid'];
        $cuid = $cronjob['cuid'];
        $set = notify($sid, $suid, $cuid);
        if($set==1){
            //echo 'notified<br>';
            $sql = "UPDATE cronjobs SET status = '1' WHERE id='".$cronjob['id']."'";
            if(mysql_query($sql)){
               echo '1<br>';
              $set = 0;
          }
        }
      }
   }
}

notify() will return 1 (numeric)

The problem is only one iteration of the while loop is executed even though there are more records. I don't know what's wrong here. Help me out pls.

Please change inner $sql variable name to something else..outer $sql and inner one are making conflict

$sql = mysql_query("SELECT * FROM cronjobs WHERE status = 0 ");

while($cronjob = mysql_fetch_array($sql)){
    if($cronjob['suid'] != $cronjob['cuid']){
        //echo 'not equal<br>';
        $set = 0;
        $sid = $cronjob['sid'];
        $suid = $cronjob['suid'];
        $cuid = $cronjob['cuid'];
        $set = notify($sid, $suid, $cuid);
        if($set==1){
            //echo 'notified<br>';
            $sql_2 = "UPDATE cronjobs SET status = '1' WHERE id='".$cronjob['id']."'";
            if(mysql_query($sql_2)){
               echo '1<br>';
              $set = 0;
          }
        }
      }
   }
}

Just an observation:

Because you have:

$sql = mysql_query("SELECT * FROM cronjobs WHERE status = 0 ");  
while($cronjob = mysql_fetch_array($sql)){ 

Its going to execute the Query EVERY SINGLE time it goes through the loop. If you have a 100 rows, its going to execute 100 times. If you do this instead, then it executes only once.

$sql = mysql_query("SELECT * FROM cronjobs WHERE status = 0 ");  
$res = mysql_fetch_array($sql);
while($cronjob = $res){ 

It wouldnt have conflicted either!

当您具有相同的查询变量($ query)和结果对象($ result)时,显然会发生此问题。请在WHILE循环内为mysql_query()尝试使用不同的名称。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM