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

标签 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
        }
      }           
    }

最佳答案

我还没能测试它,但据我所知它应该可以工作。它递增count1只要结果为空(循环尚未开始)或获取的行数为零,并使用新的增量值 count1 查询数据库。 .

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;
    }
}

关于php - 循环遍历MySQL数据库直到有结果,然后中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510519/

相关文章:

php - 在 PHP 中从迭代器中删除元素

php - 在 MySQL 中获取表列名?

iOS Swift 和外部 SQL 数据库

sql - 在 Derby WHERE 子句中使用 timestampdiff

php - 如何查看 ID 是否已预订特定日期?

php - 等待 PROOPH 中投影创建的读取模型中的新记录

php - 是否可以通过 [Web] Guard 使用 Laravel 资源?

php - "group"mysql结果以获得更好的php性能

mysql - JOINing 后旋转表不正确?

MySQL在删除时设置默认字段值