mysqli - Looping under a loop on php not working well


I'm trying to create a table on html from MySQL. I'm trying to run while loop under a while loop. But unfortunately my script has a weird behaviour. It's showing following error and not displaying out put correctly.

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

Here is my code. Please tell me what wrong I've done.

$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>
    //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_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'];



This may not be your particular issue, assuming you have data in the database, but PHP will throw "Call to a member function fetch_array() on a non-object" when you attempt to grab a row from a result with 0 rows.

You can prevent this by wrapping your while loop inside of:

if($result->num_rows > 0){
  while($row = $result->fetch_assoc()){
    do stuff here...

People are also looking for solutions to the problem: How can i separate php code with html to have them both clean and separate in different files?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.