嵌套While While with mysql_fetch_array给出空白结果

时间:2013-09-12 07:18:14

标签: php mysql sql while-loop nested-loops

我使用了以下代码,如果存在,请解决任何错误

我正在尝试使用子类别表中的parentID

从类别表中捕获类别名称

这是代码

$query_select = "SELECT * FROM subcategory where parentID<>0 and isDisabled=0 and isDeleted=0";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
  $rows[] = $row;

foreach($rows as $row){ 
  $id = $row['subcatID'];
  $subname = $row['subcatName'];
  $parentID= $row['parentID'];
  $status = $row['isDisabled'];
  $catname="";
  echo "<tr><td style='display:none;'>$id</td>";
  echo "<td><center>$subname</center></td>";
  $resultnew=mysql_query("select catName from category where catID=$parentID");

  while(mysql_fetch_row($resultnew)){
    $catname = $resultnew[0];
    echo "<script>alert($catname);</script>";
    echo "<td class='center'><center>$catname</center></td>";
  }
  if($status==0)
    {
      echo "<td class='center'><center><span class='label label-success'>Active</span></center></td>";
    }else{
    echo "<td class='center'><center><span class='label label-important'>Disabled</span></center></td>";
  }
  echo "<td class='center'><center>";
  echo "<a class='btn btn-success' href='#'><i class='icon-zoom-in icon-white'></i>View</a>";
  echo "<a class='btn btn-info' href='#'><i class='icon-edit icon-white'></i>Edit</a>";
  echo "<a class='btn btn-danger' href='#'><i class='icon-trash icon-white'></i>Delete</a>";
  echo "</center></td>";
  echo "</tr>";
}

1 个答案:

答案 0 :(得分:0)

变化:

  while(mysql_fetch_row($resultnew)){
    $catname = $resultnew[0];
    echo "<script>alert($catname);</script>";
    echo "<td class='center'><center>select catName from category where catID=$parentID $catname</center></td>";
  }

为:

  while($newrow = mysql_fetch_row($resultnew)){
    $catname = $newrow[0];
    echo "<script>alert($catname);</script>";
    echo "<td class='center'><center>select catName from category where catID=$parentID $catname</center></td>";
  }

但是,我认为catID是一个唯一的键,所以这个查询只能返回一行,所以根本不需要while循环。只需写下:

if ($newrow = mysql_fetch_row($resultnew)) {
    $catname = $newrow[0];
    echo "<script>alert($catname);</script>";
    echo "<td class='center'><center>select catName from category where catID=$parentID $catname</center></td>";
  }

但您也可以将其与主查询结合使用,因此您无需进行多次查询:

SELECT s.subcatID, s.subcatName, s.parentID, s.isDisabled, c.catName
FROM subcategory s
LEFT JOIN category c ON c.catID = s.parentID
WHERE s.parentID <> 0 and s.isDisabled = 0 and s.isDeleted = 0