Member Avatar for jpknoob

Hi, I have been trying to debug this error all day and am having problems. The script connects to the database and displays the results as as it should, however, when it loops, I get the error "Warning: mysql_fetch_array(): 3 is not a valid MySQL result resource". I tried to use

echo "<hr />".$query."<hr />";exit();

but found no error with my query, I'm sure the problem lies in my loop. Am I doing this wrong? Can anyone offer any help?

My code is;

$query="SELECT make, model, price, year, fuel, miles, transmission, description, image, id FROM stock";
$result=mysql_query($query) or die(mysql_error());				
$num=mysql_num_rows($result);
mysql_close();
					
if ($num > 0){
echo "<p>We currently have $num cars in stock;</p>";
echo "<table>";
						
$i = 0;
for ($i=0; $i < $num; $i++)
{		
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
echo "	<tr>
<th></th>
<th>$row[make]</th>
</tr>
<tr>
<td><a href=\"details.php?id=$row[id]\"><img src=\"view-image.php?id=$row[id]\" width='200' alt='error- no image found' />Click for more images</a></td>
<td>$row[description]</td>
</tr>
<tr>
<td>Miles: $row[miles]</td>
<td>Transmission: $row[transmission]</td>
</tr>
<tr>
<td>Fuel Type: $row[fuel]</td>
<td>Price: &pound;$row[price]</td>
</tr>";
echo '</table>';
mysql_free_result($result);
}								
}
}
?>

You closed the connection, before looping the rows.

Member Avatar for jpknoob

Thanks for the reply, however, I too thought this might be the problem and even when I remove the close statement, I still get the error.

You use

mysql_free_result($result)

as part of your loop

so the second time in the while loop $result is empty

Member Avatar for jpknoob

Thank you for the help pzuurveen, that did indeed fix my problem! The looped results were not placed inside the table, but all it took was to shift the opening table tag to the while statement. Thanks for the help!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.