循环遍历MySQL数据库,直到有结果,然后中断

时间:2016-07-21 17:17:46

标签: php mysql sql

如果查看else部分,则会有一个包含问题的代码注释。如何重复它,可能是一个不同类型的循环?不幸的是,我不知道如何。

for ($id = 0; $id <= 16; $id++) {
    $count1++;
    $count2++;
    $sql = "SELECT a FROM jedynki where id = $count1 && f = '0' ";  
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $a = $row['a'];
            $a=substr($a,0,55);
            // do something...
            break;
        }
    } else {
        /*  If no results:
              1. Go back to the top of sql query
              2. Increment $count1
              3. Try again
            Repeat these steps (very important), until there is a result.  */
    }
    $sql = " SELECT a FROM jedynki where id = $count2 && f = '1' ";                  
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
             $b = $row['a'];
             $b=substr($b,0,55);
    ?>
        // do something...
    <?php
        }
      }           
    }

1 个答案:

答案 0 :(得分:0)

我无法测试它,但它应该可以解决。只要结果为null(循环尚未启动)或者获取的行数为零,它就会增加count1,并使用新的递增值count1查询数据库。 / p>

for ($id = 0; $id <= 16; $id++) {
    $result = NULL;

    do {
        $count1++;
        $sql = "SELECT a FROM jedynki where id = $count1 && f = '0' ";  
        $result = $conn->query($sql);
    } while(($result == NULL) || ($result->num_rows == 0));

    while($row = $result->fetch_assoc()) {
        // do something...
        break;
    }
}