如果您查看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/