while循环只显示一条记录,当我使用嵌套while循环从另一个表获取数据时

时间:2017-08-24 11:07:23

标签: php mysql

我有案例管理器表,我已插入法庭表id作为外键。我想从两个表中获取记录。当使用嵌套的while循环时,它只显示一个行数据。

$id = $_SESSION['id'];
$query1 = "SELECT * from `case_manager` where user_id = '$id' ";
$result1 = mysqli_query($conn, "$query1");
while($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
    $Status = $row['status'];
    $id = $row['id'];
    $case_type = $row['case_type'];
    $court_id = $row['court_id'];
    $query2 = "SELECT * from `case_type` where case_id = '$case_type'";
    if($result1 = mysqli_query($conn, "$query2")) {
        while($row2 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
            echo $row2['case_name'];
        }
    }
} 

3 个答案:

答案 0 :(得分:1)

因为您覆盖了$result1,所以将内部查询结果更改为$result2,然后尝试

$id = $_SESSION['id'];
$query1 ="SELECT * from `case_manager` where user_id = '$id' "; 
$result1 = mysqli_query($conn , "$query1");
while ($row = mysqli_fetch_array($result1 ,MYSQLI_ASSOC)) {
  $Status=$row['status'];
  $id = $row['id'];
  $case_type = $row['case_type'];
  $court_id = $row['court_id'];
  $query2 ="SELECT * from `case_type` where case_id = '$case_type'"; 
  if($result2 = mysqli_query($conn , "$query2")){;
    while ($row2 = mysqli_fetch_array($result2 ,MYSQLI_ASSOC)) {
      echo $row2['case_name'];
    } 
  }
} 

答案 1 :(得分:1)

1st:因为您在第二次查询执行中覆盖变量 $ result1

std::is_same

注意:并删除不必要的分号。

第二名:无需多个查询简单使用加入

if($result1 = mysqli_query($conn , "$query2")){;
   ^^^^^^^^                                   ^^

答案 2 :(得分:1)

您可以使用以下查询来获取记录:

$query = SELECT case_manager.* ,case_type.case_name FROM case_manager Left JOIN case_type ON case_manager.case_type=case_type.case_id where case_manger.user_id = $id;

While($row = mysql_fetch_array()){
  echo $row['case_name'];
}