View Full Version : Shopping Cart - Not Working

11-17-2007, 12:16 AM
On executing the code below, an error message appears. Why is this?

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\Documents and Settings\User\Desktop\Xampp\htdocs\cart.php on line 51

$total = 0;
echo '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM books WHERE id = '.$id;
$result = mysql_query($sql);

$row = mysql_fetch_array($result);

echo '<tr>';
echo '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
echo '<td>'.$row['title'].' by '.$author.'</td>';
echo '<td>&pound;'.$price.'</td>';
echo '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
echo '<td>&pound;'.($price * $qty).'</td>';
$total += $price * $qty;
echo '</tr>';
echo '</table>';
echo '<p>Grand total: &pound;'.$total.'</p>';

echo writeShoppingCart();
echo '<a href="cart.php?action=add&id=1">Add to cart</a>';

11-17-2007, 12:38 AM
Add error checking to your query to find out what the real problem is.

$result = mysql_query($query);

if (!$result) {
die("Query failed. Query text: $query<br />Error: ".mysql_error());

11-17-2007, 01:30 AM
Shouldn't this:

$sql = 'SELECT * FROM books WHERE id = '.$id;
Look like this ?:

$sql = "SELECT * FROM books WHERE id = '$id'";

11-17-2007, 01:38 AM
Actually, no. Either way should work, but you shouldn't wrap integers in quotes.

11-17-2007, 01:41 AM
Actually, no. Either way should work, but you shouldn't wrap integers in quotes.

oh sorry didn't know, what's the reason not to do it though?

11-17-2007, 02:23 AM
Because when you put it in quotes it will be treated as a string, and that can cause problems when doing comparisons or inserts. Like I said, most of the time using quotes will work, but there's no reason to use them, and it's poor coding practice.

11-17-2007, 02:48 AM
Also, by putting numeric values in quotes, making them strings, in a numeric column, forces mysql to do extra work to convert them back to the numeric value, unnecessarily slowing down the query and if the value is large enough or small enough can result in an inexact conversion. From the mysql manual -

If a numeric expression contains any strings, they are converted to double-precision floating-point values and the expression is approximate. Short answer - only put quotes around strings.