4 Replies - 13166 Views - Last Post: 10 January 2013 - 03:52 PM Rate Topic: -----

#1 chase552  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 09-January 13

problem with php shopping cart

Posted 10 January 2013 - 02:45 PM

Hi, I am new to programming in php and I am having a couple issues. I followed a tutorial on building a php shopping cart and I am trying to add an option to choose a size in the shopping cart. On the product page, it carries over the item ID but not the size option I am trying to implement. Below is my code for the product page:

<?php 
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php 
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
	// Connect to the MySQL database  
    include "storescripts/connect_to_mysql.php"; 
	$id = preg_replace('#[^0-9]#i', '', $_GET['id']); 
	// Use this var to check to see if this ID exists, if yes then get the product 
	// details, if no then exit this script and give message why
	$sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
	$productCount = mysql_num_rows($sql); // count the output amount
    if ($productCount > 0) {
		// get all the product details
		while($row = mysql_fetch_array($sql)){ 
			 $id1 = $row["id"];
			 $product_name = $row["product_name"];
			 $price = $row["price"];
			 $details = $row["details"];
			 $category = $row["category"];
			 $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
         }
		 
	} else {
		echo "That item does not exist.";
	    exit();
	}
		
} else {
	echo "Data to render this page is missing.";
	exit();
}
mysql_close();
?>
<?php 
// Run a select query to get my letest 6 items
// Connect to the MySQL database  
include "storescripts/connect_to_mysql.php"; 
$dynamicList = "";
$sql = mysql_query("SELECT * FROM products where category='other_products' LIMIT 4");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
	while($row = mysql_fetch_array($sql)){ 
             $id = $row["id"];
			 $product_name = $row["product_name"];
			 $price = $row["price"];
			 $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
			 $dynamicList .= '
        <tr>
          <a href="product.php?id=' . $id . '"><img style="border:#666 1px solid;" src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="77" height="102"/></a></td>
		  
        <h3> ' . $product_name . ' </h3>
		  
           <h3> $' . $price . ' </h3>
			
            <a href="product.php?id=' . $id . '"><h5>View Product Details</h5></a></td>';
    }
} else {
	$dynamicList = "We have no products listed in our store yet";
}
mysql_close();
?>



<CTYPE HTML>
<html>

<body>


	        <div id="content">
          <h1><?php echo $product_name; ?></h1>
           
           <img src="inventory_images/<?php echo $id; ?>.jpg" width="242" height="288" alt="<?php echo $product_name; ?>" />
            <h6><a href="inventory_images/<?php echo $id; ?>.jpg">See Full Size Image</a></h6>
            <p>&nbsp; </p>
           <h3>Price: <?php echo "$".$price; ?></h3>
          
        
          <h3> <form id="form1" name="form1" method="post" action="cart.php">
           <select name="myvalue" id = "myvalue">
           <option value="value1">Value 1</option>
           <option value="value2">Value 2</option>
           <option value="value3">Value 3</option>
           </select>
		<input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" />
        <input type="submit" name="button" id="button" value="Add to Cart" />
      </form></h3>
     
      
    
            
<h2>Product Discription</h2>
<h4><?php echo $details; ?></h4>
           
  </div>
            
        <div id="rightside">
         
            <h2>Extras</h2>
            <?php echo $dynamicList; ?>
            
        </div>
	
		
        

</body>

</html>



and this is my shopping cart code:



<? ob_start(); ?>
<?php 
session_start(); // Start session first thing in script
// Script Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Connect to the MySQL database  
include "storescripts/connect_to_mysql.php"; 
?>

<?php 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//       Section 1 (if user attempts to add something to the cart from the product page)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
	$myvalue = $_POST['myvalue'];
	$wasFound = false;
	$i = 0;
	// If the cart session variable is not set or cart array is empty
	if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { 
	    // RUN IF THE CART IS EMPTY OR NOT SET
		$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1, "ink" => $myvalue));
	} else {
		// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
		foreach ($_SESSION["cart_array"] as $each_item) { 
		      $i++;
		      while (list($key, $value) = each($each_item)) {
				  if ($key == "item_id" && $value == $pid) {
					  // That item is in cart already so let's adjust its quantity using array_splice()
					  array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'])));
					  $wasFound = true;
				  } // close if condition
		      } // close while loop
	       } // close foreach loop
		   if ($wasFound == false) {
			   array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
		   }
	}
	header("location: cart.php"); 
    exit();
}
?>
<?php 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//       Section 2 (if user chooses to empty their shopping cart)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
    unset($_SESSION["cart_array"]);
}
?>
<?php 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//       Section 4 (if user wants to remove an item from cart)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
    // Access the array and run code to remove that array index
 	$key_to_remove = $_POST['index_to_remove'];
	if (count($_SESSION["cart_array"]) <= 1) {
		unset($_SESSION["cart_array"]);
	} else {
		unset($_SESSION["cart_array"]["$key_to_remove"]);
		sort($_SESSION["cart_array"]);
	}
}
?>
<?php 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//       Section 5  (render the cart for the user to view on the page)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$cartOutput = "";
$cartTotal = "";
$pp_checkout_btn = '';
$product_id_array = '';
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartOutput = "<h1>Your shopping cart is empty</h1>";
} else {
	// Start PayPal Checkout Button
	$pp_checkout_btn .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
    <input type="hidden" name="cmd" value="_cart">
	<input type="hidden" name="upload" value="1">
    <input type="hidden" name="business" value="">';
	// Start the For Each loop
	$i = 0; 
    foreach ($_SESSION["cart_array"] as $each_item) { 
		$item_id = $each_item['item_id'];
		
		$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
		while ($row = mysql_fetch_array($sql)) {
			$product_name = $row["product_name"];
			$price = $row["price"];
			$details = $row["details"];
			$category = $row["category"];
		}
		$pricetotal = $price * $each_item['quantity'];
		$cartTotal = $pricetotal + $cartTotal;
		setlocale(LC_MONETARY, "en_US");
        $pricetotal = money_format("%10.2n", $pricetotal);
		// Dynamic Checkout Btn Assembly
		$x = $i + 1;
		$pp_checkout_btn .= '<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">
        <input type="hidden" name="amount_' . $x . '" value="' . $price . '">
        <input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '">  ';
		// Create the product array variable
		$product_id_array .= "$item_id-".$each_item['quantity'].","; 
		// Dynamic table row assembly
		$cartOutput .= "<tr>";
		$cartOutput .= '<td><a href="product.php?id=' . $item_id . '">' . $product_name . '</a><br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name. '" width="40" height="52" border="1" /></td>';
		$cartOutput .= '<td>$' . $price . '</td>';
		
		if($category == 'fountain_pens')
		{
		
		$cartOutput .= '<td>' . $ink . '</td>';
		
		}
		else
		{
			$cartOutput .= '<td>None</td>';
		}
		
		
		$cartOutput .= '<td>' . $pricetotal . '</td>';
		$cartOutput .= '<td><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>';
		$cartOutput .= '</tr>';
		$i++; 
    } 
	setlocale(LC_MONETARY, "en_US");
    $cartTotal = money_format("%10.2n", $cartTotal);
	$cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : ".$cartTotal." USD</div>";
    // Finish the Paypal Checkout Btn
	$pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '">
	
	<input type="hidden" name="notify_url" value="">
	<input type="hidden" name="return" value="">
	<input type="hidden" name="rm" value="2">
	<input type="hidden" name="cbt" value="Return to The Store">
	<input type="hidden" name="cancel_return" value="">
	<input type="hidden" name="lc" value="US">
	<input type="hidden" name="currency_code" value="USD">
	<input type="image" align="right" src="" name="submit" alt="Make payments with PayPal - its fast, free and secure!">
	</form>';
}
?>
<CTYPE HTML>
<html>

<head>
	
	<title>Your Cart</title>

	
</head>

<body>

<div id="wrapper">
		
        <div id="content">
          <h1>Your Cart</h1>
           
         <div style="margin:24px; text-align:left;">
	
    <br />
    <table width="100%" border="1" cellspacing="5" cellpadding="10">
      <tr>
        <td width="18%" bgcolor="#666666"><strong>Product</strong></td>
        <td width="10%" bgcolor="#666666"><strong>Unit Price</strong></td>
        <td width="9%" bgcolor="#666666"><strong>Size</strong></td>
        <td width="9%" bgcolor="#666666"><strong>Total</strong></td>
        <td width="9%" bgcolor="#666666"><strong>Remove</strong></td>
      </tr>
     <?php echo $cartOutput; ?>
     <!-- <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr> -->
    </table>
    <?php echo $cartTotal; ?>
    <br />
<br />
 <?php echo $pp_checkout_btn; ?>
 
    <br />
    <br />
    
    <a href="cart.php?cmd=emptycart">Click Here to Empty Your Shopping Cart</a>
    </div>
   <br />
   
   
           
  </div>
  </body>
</html>
<? ob_flush(); ?>



Basically, I just need the size variable(my value) from the drop down menu on the products page to be able to carry over to the shopping cart.I am also having trouble adding this item to the array. I apologize if this is too much code, this is the first time I have posted something on here. Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: problem with php shopping cart

#2 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3608
  • View blog
  • Posts: 12,399
  • Joined: 12-December 12

Re: problem with php shopping cart

Posted 10 January 2013 - 03:27 PM

I think you need to be more specific about what your issue is. I can see that you are posting the SELECT data and then reading it on the cart page:

if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
	$myvalue = $_POST['myvalue'];


so I can't see the issue..?

Please also correct CTYPE to:

<!DOCTYPE html>
on both pages.

Use print_r($_POST); towards the top of your page to check the posted data (View Source from the page to read it more easily).

Your cart page is also missing a closing </div> I believe.

This post has been edited by andrewsw: 10 January 2013 - 03:29 PM

Was This Post Helpful? 1
  • +
  • -

#3 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3608
  • View blog
  • Posts: 12,399
  • Joined: 12-December 12

Re: problem with php shopping cart

Posted 10 January 2013 - 03:33 PM

BTW You shouldn't place your form in an h3-tag. Use a DIV and style it as necessary. Also, bgcolor attribute is obsolete: use CSS or an inline-style:

<td style="background-color:#666666"

This post has been edited by andrewsw: 10 January 2013 - 03:35 PM

Was This Post Helpful? 0
  • +
  • -

#4 chase552  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 09-January 13

Re: problem with php shopping cart

Posted 10 January 2013 - 03:41 PM

View Postandrewsw, on 10 January 2013 - 03:33 PM, said:

BTW You shouldn't place your form in an h3-tag. Use a DIV and style it as necessary. Also, bgcolor attribute is obsolete: use CSS or an inline-style:

<td style="background-color:#666666"


Thanks for your response. I am sorry if I was not clear about the issue. Basically, when I post the myvalue variable to the cart page, it does not allow me to do anything with it. When I try to echo it out to the page, it doesn't print out anything. Also, there is an array that is used as a custom variable for paypal. I am trying to add this myvalue to that array. Also, thanks for the tips, I will be sure to make those changes.
Was This Post Helpful? 0
  • +
  • -

#5 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3608
  • View blog
  • Posts: 12,399
  • Joined: 12-December 12

Re: problem with php shopping cart

Posted 10 January 2013 - 03:52 PM

You don't use

echo $myvalue;

anywhere to display the value?! And you are not pushing this value into any other array, like you are here:

array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));

I've been looking for an error but you haven't written the code that might generate the error that you seem to be indicating :dozingoff:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1