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.
<?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'];
}
}
?>
Answer
Solution:
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:
Answer
Solution:
Code:
Error message:
The
method returns a
object from a successful
"SELECT"
query, orFALSE
on error. The error message above means that your query has failed. Check your error logs.To avoid getting this error, you have to explicitly check for failed queries: