循环php mysql查询直到找不到结果

时间:2013-12-20 20:54:21

标签: php mysql sql

我有这个mysql查询,我想循环,直到在表中找不到更多结果,

$sql_query="select id from rev_r_clients WHERE parent_client_id='$id'";
 $res = mysql_query($sql_query);
 $ids=array();
 while($row = mysql_fetch_object($res)){
 $ids[]=$row->id;
}
 $ids=array_filter($ids);
 foreach($ids as $id){
 echo $id;

}

和我想要的是一遍又一遍地循环同一个查询:

$sql_query="select id from rev_r_clients WHERE parent_client_id='$id'";
 $res = mysql_query($sql_query);
 $ids=array();
 while($row = mysql_fetch_object($res)){
 $ids[]=$row->id;
}
 $ids=array_filter($ids);
 foreach($ids as $id){
 echo $id;

$sql_query="select id from rev_r_clients WHERE parent_client_id='$id'";
 $res = mysql_query($sql_query);
 $ids=array();
 while($row = mysql_fetch_object($res)){
 $ids[]=$row->id;
}
 $ids=array_filter($ids);
 foreach($ids as $id){
 echo $id;

}
}

这最后一个代码将循环查询两次,但我遇到的问题是我想循环它直到找不到更多的结果

$sql_query="select id from rev_r_clients WHERE parent_client_id='$id'";
 $res = mysql_query($sql_query);
 $ids=array();
 while($row = mysql_fetch_object($res)){
 $ids[]=$row->id;
}
 $ids=array_filter($ids);
 foreach($ids as $id){
 echo $id;

<! - 在这里重复相同的代码并再次重复 - >     }

循环3次:

$sql_query="select id from rev_r_clients WHERE parent_client_id='$id'";
 $res = mysql_query($sql_query);
 $ids=array();
 while($row = mysql_fetch_object($res)){
 $ids[]=$row->id;
}
 $ids=array_filter($ids);
 foreach($ids as $id){
 echo $id;

$sql_query="select id from rev_r_clients WHERE parent_client_id='$id'";
 $res = mysql_query($sql_query);
 $ids=array();
 while($row = mysql_fetch_object($res)){
 $ids[]=$row->id;
}
 $ids=array_filter($ids);
 foreach($ids as $id){
 echo $id;

$sql_query="select id from rev_r_clients WHERE parent_client_id='$id'";
 $res = mysql_query($sql_query);
 $ids=array();
 while($row = mysql_fetch_object($res)){
 $ids[]=$row->id;
}
 $ids=array_filter($ids);
 foreach($ids as $id){
 echo $id;

}
}
}

那么如何重复代码无限次,直到数据库中没有结果

1 个答案:

答案 0 :(得分:0)

使用递归的快速解决方案:

function getChildIds($id, &$count) { // Note that $count is passed in as a reference (the & before the $count)
    ++$count;
    echo $id;
    $sql_query="select id from rev_r_clients WHERE parent_client_id='$id'";
    $res = mysql_query($sql_query);
    $ids = Array();
    while($row = mysql_fetch_object($res)){
        if ($row->id) { // Checking for false-like values here to remove the need for array_filter
            $ids[] = $row->id;
        }
    }

    foreach ($ids as $next) { // using foreach instead of array_walk as we cannot pass a reference into array_walk without raising a warning (or fatal error, depending on PHP version)
        getChildIds($next, $count);
    }
}

$count = 0;
getChildIds($firstId, $count);
// $count now has the number of times the function was called
echo $count;

但请注意mysql_* functions are deprecated而应使用mysqliPDO