php while循环只显示跨多个表的mysql查询的一个结果

时间:2012-10-02 21:47:18

标签: php mysql

我遇到一个只返回一个结果的while语句的问题。这是我第一次尝试从几个表中显示产品信息而我不知道我做错了什么。这是代码:

<?php
    require('./includes/config.inc.php');
    require(MYSQL);

    $sql = sprintf("SELECT * FROM tea");

    $res = mysqli_query($dbc, $sql);

    if(!$res){
    die('Could not complete query: '.mysqli_error($dbc));
    } else {

    echo 'Success!<br />';

    while($row = mysqli_fetch_array($res)){
        $table = $row['category'];
        $inum = $row['item_number'];

        echo $table.' '.$inum.'<br />';

        $fetch = sprintf("SELECT sub_category, item_name, description FROM $table WHERE item_number ='$inum'");
        $fetchRes = mysqli_query($dbc, $fetch);

        if(!$fetchRes){
            die('Could not fetch: '.mysqli_error($dbc));
        } else {
            while($fetchRow = mysqli_fetch_array($fetchRes)){
                $subCat = $fetchRes['sub_category'];
                $iNumber = $inum;
                $iname = $fetchRes['item_name'];
                $desc = $fetchRes['description'];

                echo $id.' '.$subCat.' '.$iNumber.' '.$iname.' '.$desc.'<br />';
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

在while循环中,您应该使用$fetchRow变量作为从中获取列的数组,例如'sub_category'。

答案 1 :(得分:0)

IS

  $subCat = $fetchRes['sub_category'];
  $iNumber = $inum;
  $iname = $fetchRes['item_name'];
  $desc = $fetchRes['description'];

需要:Res to Row

 $subCat = $fetchRow['sub_category'];
 $iNumber = $inum;
 $iname = $fetchRow['item_name'];
 $desc = $fetchRow['description'];