Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hello

 

I keep getting "Your cart is currently empty." regardless of what is added to the cart.

 

Here are two scripts: add_cart.php and view_cart.php

 

view_cart.php

<?php # Script 19.10 - view_cart.php
// This page displays the contents of the shopping cart.
// This page also lets the user update the contents of the cart.

// Set the page title and include the HTML header:
$page_title = 'View Your Shopping Cart';
include ('header.html');

// Check if the form has been submitted (to update the cart):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	// Change any quantities:
	foreach ($_POST['qty'] as $k => $v) {

		// Must be integers!
		$pid = (int) $k;
		$qty = (int) $v;
		
		if ( $qty == 0 ) { // Delete.
			unset ($_SESSION['cart'][$pid]);
		} elseif ( $qty > 0 ) { // Change quantity.
			$_SESSION['cart'][$pid]['quantity'] = $qty;
		}
		
	} // End of FOREACH.
	
} // End of SUBMITTED IF.

// Display the cart if it's not empty...
if (!empty($_SESSION['cart'])) {

	// Retrieve all of the information for the prints in the cart:
	include_once('common.php'); // Connect to the database.
	$q = "SELECT print_id, CONCAT_WS(' ', first_name, middle_name, last_name) AS artist, print_name FROM artists, prints WHERE artists.artist_id = prints.artist_id AND prints.print_id IN (";
	foreach ($_SESSION['cart'] as $pid => $value) {
		$q .= $pid . ',';
	}
	$q = substr($q, 0, -1) . ') ORDER BY artists.last_name ASC';
	$r = mysqli_query ($con, $q);
	
	// Create a form and a table:
	echo '<form action="view_cart.php" method="post">
	<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
	<tr>
		<td align="left" width="30%"><b>Artist</b></td>
		<td align="left" width="30%"><b>Print Name</b></td>
		<td align="right" width="10%"><b>Price</b></td>
		<td align="center" width="10%"><b>Qty</b></td>
		<td align="right" width="10%"><b>Total Price</b></td>
	</tr>
	';

	// Print each item...
	$total = 0; // Total cost of the order.
	$count=1;
	while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {
	
		// Calculate the total and sub-totals.
		$subtotal = $_SESSION['cart'][$row['print_id']]['quantity'] * $_SESSION['cart'][$row['print_id']]['price'];
		$total += $subtotal;
		
		// Print the row:
		echo "\t<tr>
		<td align=\"left\">{$row['artist']}</td>
		<td align=\"left\">{$row['print_name']}</td>
		<td align=\"right\">£{$_SESSION['cart'][$row['print_id']]['price']}</td>
		<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['print_id']}]\" value=\"{$_SESSION['cart'][$row['print_id']]['quantity']}\" /></td>
		<td align=\"right\">$" . number_format ($subtotal, 2) . "</td>
		</tr>\n";
		 $string_of_item_names = $string_of_item_names.' <input type="hidden" name="item_name_'.$count.'" Value="'.$row['print_name'].'" >'; # build item name string of all items in the basket
  $string_of_item_amounts = $string_of_item_amounts.' <input type="hidden" name="amount_'.$count.'" Value="'. number_format ($subtotal, 2).'" >'; # build string of prices for items in basket
  # use count as a reference to match names with prices in paypal
  $count++;
	
	} // End of the WHILE loop.

	mysqli_close($con); // Close the database connection.

	$checkout_button = ('<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">

    <!-- Identify your business so that you can collect the payments.
    HELP: https://www.paypal.com/us/cgi-bin/webscr?cmd=_pdn_xclick_techview_outside
    https://developer.paypal.com/webapps/developer/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/#id08A6HF00TZS
    
    We use cart becuase we have our own (third party which is us)
     -->
    <input type="hidden" name="business" value="mystore@gmail.com">
    <input type="hidden" name="cmd" value="_cart">
    <input type="hidden" name="upload" value="1">
    
    
    <!--- this is where the user comes back to after they finished making the payment --->
    <input type="hidden" name="notify_url" Value="http://www.ecom/thankyou.php" />

    <!-- Specify details about the item that buyers will purchase. -->
    '.$string_of_item_names.'
	'.$string_of_item_amounts.'
    <input type="hidden" name="currency_code" value="GBP">


    <!-- Display the payment button. -->
    <input type="image" name="submit" border="0"
        src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif"
        alt="PayPal - The safer, easier way to pay online">
    <img alt="" border="0" width="1" height="1"
        src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >
</form>');
	// Print the total, close the table, and the form:
	echo '<tr>
		<td colspan="4" align="right"><b>Total:</b></td>
		<td align="right">$' . number_format ($total, 2) . '</td>
	</tr>
	</table>
	<div align="center"><input type="submit" name="submit" value="Update My Cart" /></div>
	</form><p align="center">Enter a quantity of 0 to remove an item.
	<br /><br />'.$checkout_button.'</p>';

} else {
	echo '<p>Your cart is currently empty.</p>';
}

include ('footer.html');
?>

add_cart.php

<?php # Script 19.9 - add_cart.php
// This page adds prints to the shopping cart.

// Set the page title and include the HTML header:
$page_title = 'Add to Cart';
include ('header.html');

if (isset ($_GET['pid']) && filter_var($_GET['pid'], FILTER_VALIDATE_INT, array('min_range' => 1))  ) { // Check for a print ID.
	$pid = $_GET['pid'];

	// Check if the cart already contains one of these prints;
	// If so, increment the quantity:
	if (isset($_SESSION['cart'][$pid])) {

		$_SESSION['cart'][$pid]['quantity']++; // Add another.

		// Display a message:
		echo '<p>Another copy of the print has been added to your shopping cart.</p>';
		
	} else { // New product to the cart.

		// Get the print's price from the database:
		include_once('common.php'); // Connect to the database.
		$q = "SELECT price FROM prints WHERE print_id=$pid";
		$r = mysqli_query ($con, $q);		
		if (mysqli_num_rows($r) == 1) { // Valid print ID.
	
			// Fetch the information.
			list($price) = mysqli_fetch_array ($r, MYSQLI_NUM);
			
			// Add to the cart:
			$_SESSION['cart'][$pid] = array ('quantity' => 1, 'price' => $price);

			// Display a message:
			echo '<p>The print has been added to your shopping cart.</p>';

		} else { // Not a valid print ID.
			echo '<div align="center">This page has been accessed in error!</div>';
		}
		
		mysqli_close($con);

	} // End of isset($_SESSION['cart'][$pid] conditional.

} else { // No print ID.
	echo '<div align="center">This page has been accessed in error!</div>';
}

include ('footer.html');
?>

Thanks

Share this post


Link to post
Share on other sites

Hi Larry cc all,

 

I have tried to code the view_cart.php script for several times. The error returned saying that MySQL error: Unknown column '$pid' in 'where clause'.

 

I first thought that it was my typing mistake or so. So, i later tried copying and pasting your original script 19.10 - view_cart.php into my site to test it. The same error happened too.

 

Note:

 

1/ I added or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q") after the $r = mysqli_query($dbc, $q) to turn on the error message. When I commented it out, the error message returned like this:

 

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/content/.../view_cart.php on line 55, which means the error happens at while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {...

 

2/ I use Linux shared web hosting package at godaddy.com

 

3/ PHP version: 5.3.21

 

Your help will be appreciated.

 

Eric

Share this post


Link to post
Share on other sites

That would suggest that you're passing the actual value $pid in the query, not the value of the variable $pid. If you apply the standard PHP-MySQL debugging techniques (step 1: print the query being executed), you'll see this is the case.

Share this post


Link to post
Share on other sites

That would suggest that you're passing the actual value $pid in the query, not the value of the variable $pid. If you apply the standard PHP-MySQL debugging techniques (step 1: print the query being executed), you'll see this is the case.

 

Thanks. but the point is that I haven't changed anything in your script.

/ check if the form has been submitted (to update cart)
if($_SERVER['REQUEST_METHOD'] == 'POST'){
	
	// update quantities:
	foreach ($_POST['qty'] as $k => $v) {
		
		// Must be interger
		$pid = (int) $k;
		$qty = (int) $v;
		
		if ($qty == 0){ // Delete
			unset ($_SESSION['cart']['$pid']);
		} elseif ($qty > 0){ // change quantity
			$_SESSION['cart']['$pid']['quantity'] = $qty;
		} //end of IF
		
	} // end of foreach 
	
} // end of submitted IF

// Display the cart if it's not empty...
if (!empty($_SESSION['cart'])) {
	
	// Retrieve all of the information for the prints in the cart:
	require ('./mysqli_connect.php'); // Connect to the database.
	$q = "SELECT print_id, CONCAT_WS(' ', first_name, middle_name, last_name) AS artist, print_name FROM artists, prints WHERE artists.artist_id = prints.artist_id AND prints.print_id IN (";
	foreach ($_SESSION['cart'] as $pid => $value) {
		$q .= $pid . ',';
	}
	$q = substr($q, 0, -1) . ') ORDER BY artists.last_name ASC';
	
	$r = mysqli_query($dbc, $q) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q");
	
// Create a form and a table:
	echo '<form action="view_cart_19.php" method="post">
	<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
	<tr>
		<td align="left" width="30%"><b>Artist</b></td>
		<td align="left" width="30%"><b>Print Name</b></td>
		<td align="right" width="10%"><b>Price</b></td>
		<td align="center" width="10%"><b>Qty</b></td>
		<td align="right" width="10%"><b>Total Price</b></td>
	</tr>
	';

	// Print each item...
	$total = 0; // total cost of the order
	while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC) ) {
		
		// Calculate the total and subtotal:
		$subtotal = $_SESSION['cart'][$row['print_id']]['quantity'] * $_SESSION['cart'][$row['prnt_id']]['price'];
		$total += $subtotal;
		
		// Print the row:
		
		echo "\t<tr>
			<td align=\"left\">{$row['artist']}</td>
			<td align=\"left\">{$row['print_name']}</td>
			<td align=\"right\">\${$_SESSION['cart'][$row['print_id']]['price']}</td>
			<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['print_id']}]\" value=\"{$_SESSION['cart'][$row['print_id']]['quantity']}\" /></td>
			<td align=\"right\">$" . number_format ($subtotal, 2) . "</td>
		
		</tr>\n";
		
	} // End of WHILE loop
	
	mysqli_close($dbc); // Close the database connection.
	
	// Print the total, close the table, and the form:
	
	echo '<tr>
		<td colspan="4" align="right"><b>Total:</b></td>
		<td align="right">$' . number_format ($total, 2) . '</td>
	</tr>
	</table>
	<div align="center"><input type="submit" name="submit" value="Update My Cart" /></div>
	</form>
	<p align="center">Enter a quantity of 0 to remove an item.
	<br /><br /><a href="checkout_19.php">Checkout</a></p>';

} else {
	
	echo "<p>Your cart is currently empty!</p>";
	
}

And the error still happens. What should I be wrong?

 

Eric

Share this post


Link to post
Share on other sites

Okay, my point is that if you want to debug what's going on here, you need to implement the standard PHP-MySQL debugging technique I recommended. The error message you posted is this:

MySQL error: Unknown column '$pid' in 'where clause'.

That clearly indicates a problem with the query. There's no reason why the literal text $pid should be in the query. 

 

Now, the thing is, it doesn't matter whose script it is. There's a problem with the query. You may think that there isn't a problem with this script because you downloaded it from my site. And that may be 100% the case. But the query uses information that's established in another script. That other script could be causing the problem. 

 

Regardless of all that, if you want to debug this, print out the value of the query being run. In fact, the debugging code you added already does this:

or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q")

Taking this a step further, if you want help debugging this problem, you'll need to provide to us that query value. Knowing the error message and the actual query being run can illuminate the problem.

Share this post


Link to post
Share on other sites

Okay, my point is that if you want to debug what's going on here, you need to implement the standard PHP-MySQL debugging technique I recommended. The error message you posted is this:

MySQL error: Unknown column '$pid' in 'where clause'.

That clearly indicates a problem with the query. There's no reason why the literal text $pid should be in the query. 

 

Now, the thing is, it doesn't matter whose script it is. There's a problem with the query. You may think that there isn't a problem with this script because you downloaded it from my site. And that may be 100% the case. But the query uses information that's established in another script. That other script could be causing the problem. 

 

Regardless of all that, if you want to debug this, print out the value of the query being run. In fact, the debugging code you added already does this:

or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $q")

Taking this a step further, if you want help debugging this problem, you'll need to provide to us that query value. Knowing the error message and the actual query being run can illuminate the problem.

 

Instead of typing $_SESSION['cart'][$pid], I did $_SESSION['cart']['$pid']

 

That's the reason....and it took me days to find it out....

 

Thanks for your help.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...