在php上循环循环不能正常工作

时间:2015-02-27 19:25:15

标签: php mysqli

我试图在MySQL上创建一个关于html的表。我试图在while循环下运行while循环。但遗憾的是我的剧本有一种奇怪的行为。它显示以下错误并且未正确显示输出。

Fatal error: Call to a member function fetch_array() on a non-object in /home/windsys/public_html/anamika/test2.php on line 27

这是我的代码。请告诉我我做错了什么。

<?php
require_once('configuration.php');
$con = new mysqli($hostname, $dbusername, $dbpass, $dbname);
if (mysqli_connect_errno($con)) {
    die('The connection to the database could not be established.');
}

$q2 = "SELECT DISTINCT type FROM product";
$result2 = $con->query($q2);
while ($row2 = $result2->fetch_array()) {
    $type = $row2['type'];
    echo "<tr>
              <td class=\"success\"><b>" . $type . "</b></td>
              <td class=\"success\"></td>
              <td class=\"success\"></td>
              <td class=\"success\"></td>
          </tr>";
    //echo $type."</br>";
    $q1 = "SELECT DISTINCT item_name FROM product WHERE type ='$type'";
    $result = $con->query($q1);
    while ($row = $result->fetch_array()) {
        $item_name = $row['item_name'];
        $item_name = strtolower($item_name);
        $task = "SELECT * FROM product WHERE item_name='$item_name' AND type='$type'";

        $restask = $con->query($task);
        while ($row3 = $restask->fetch_array()) {
            $item_count++;
            $item_cost += $row3['buying_price'];
            //echo $row['buying_price']."</br>";
        }
        echo "<tr><td></td><td>" . $item_name . "</td><td>" . $item_count
            . "</td><td class=\"text-right\">" . $item_cost . "</td></tr>";

        //echo $row['item_name'];
    }
}
?>

2 个答案:

答案 0 :(得分:1)

假设您在数据库中有数据,这可能不是您的特殊问题,但PHP会抛出&#34;调用非对象上的成员函数fetch_array()&#34;当你试图从0行的结果中获取一行时。

您可以通过将while循环包装在:

中来阻止这种情况
if($result->num_rows > 0){
  while($row = $result->fetch_assoc()){
    do stuff here...
  }
}

答案 1 :(得分:0)

代码:

$task = "SELECT * FROM product WHERE item_name='$item_name' AND type='$type'";

$restask = $con->query($task);
while ($row3 = $restask->fetch_array()) {
  ...

错误讯息:

  

致命错误:在非对象

上调用成员函数fetch_array()

mysqli::query()方法从成功的"SELECT"查询中返回mysqli_result个对象,或者在出错时返回FALSE。上面的错误消息表示您的查询失败。检查错误日志。

为避免出现此错误,您必须明确检查失败的查询:

$task = "SELECT * FROM product WHERE item_name='$item_name' AND type='$type'";

$restask = $con->query($task);
if ($restask) {
  while ($row3 = $restask->fetch_array()) {
    ...
  }
} else {
  /* Query failed */
}