简体   繁体   中英

Loop through a MySQL database until there is a result, then break

If you look at the else part, there is a code comment that contains a question. How to repeat it, maybe with a different kind of loop? Unfortunately, I do not know how.

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

I haven't been able to test it but it should work as far as I can tell. It increments count1 as long as the result is null (the loop hasn't started yet) or the number of rows that were fetched is zero and queries the database with the new incremented value of 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;
    }
}

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