Please help me add some code for my shopping cart

Hello everyone,

Let me first say that I am a PHP beginner. With the use of online video tutorials I have setup a shopping cart for my online store that sells stainless steel jewelry. Everything is working well, but I want to add something and even though I know what needs to e done - I don’t know how to go about it. Can someone please help me out?

So I have a product page that gets the product’s name, code, price and details from the database. This is the page’s code:

<?php 
    // Script Error Reporting
    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)){ 
             $product_code = $row["product_code"];
             $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 "The item does not exist.";
        exit();
    }
        
    } else {
    echo "Data to render this page is missing.";
    exit();
    }
    mysql_close();
?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
      <title><?php echo $product_code; ?></title>
      <meta http-equiv="Content-type" content="text/html; charset=us-ascii" /> 
      <meta http-equiv="Content-Language" content="en-us" />
      <meta http-equiv="imagetoolbar" content="no" />
      <meta name="MSSmartTagsPreventParsing" content="true" />
      <meta name="description" content="" />
      <meta name="keywords" content="" />
      <meta name="author" content="Susan Wiese" />
      <link rel="stylesheet" href="css/style.css" type="text/css" />
    </head>
    
    <body>
    
    <div id="page-container">
      
        <div id="header">
        <?php
        include "storescripts/header.php";
        ?>
        </div>
    
        <div id="center-panel">
        
        <div class="box1">
        <?php
        include "storescripts/menu.php";
        ?>
        </div>
        
        <div class="box1">
        <table width="100%" border="0" cellspacing="0" cellpadding="15" align="center">
        <tr>
        <td width="25%" valign="top">
        <img src="inventory_images/<?php echo $id; ?>.jpg" width="200" height="200" alt="<?php echo $product_name; ?>" /><br />
        <a href="inventory_images/<?php echo $id; ?>.jpg">View full size</a></td>
        <td width="75%" valign="top">
        <h3><?php echo $product_code; ?></h3>
        <?php echo $product_name; ?><br />
        <br />
        <?php echo $details; ?><br />
        <br />
        <?php echo "R".$price; ?><br />
        <br />
        <form id="form1" name="form1" method="post" action="cart.php">
        <label for="engraving">Engraving</label><br />
        <input type="text" name="engraving" id="engraving" size="35" /><br />
        <input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" /><br />
        <input type="submit" name="button" id="button" class="submit" value="Add to cart" />
        </form>
        </td>
        </tr>
        </table>
        </div>
        
        <div class="box1">
        <?php
        include "storescripts/order.php";
        ?> 
        </div>
        
        </div>
    
        <div id="footer">
        <?php
        include "storescripts/footer.php";
        ?>
        </div>
        
    </div>
    
    </body>
    </html>

The product page looks like this: Product

You’ll notice I’ve added an “Engraving” label to the form. I want a visitor to be able to add the engraving they want to be done on this product. This information should then be sent to the cart with all the other details when the person adds the item to their cart. I want the text to be engraved to be displayed in the cart’s table with the image, price, etc. This output should be in the
//Create the product array section of cart.php (where I have added $engraving)

Cart.php

<?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'];
 $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));
 } 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'] + 1)));
       $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 3 (if 
user chooses to adjust item 
quantity)//
///////////////////////////////////////////////////////
if 
(isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") 
{
    // execute some code
 $item_to_adjust = 
$_POST['item_to_adjust'];
 $quantity = $_POST['quantity'];
 $quantity = 
preg_replace('#[^0-9]#i', '', $quantity); // filter everything but 
numbers
 if ($quantity >= 100) { $quantity = 99; }
 if ($quantity < 
1) { $quantity = 1; }
 if ($quantity == "") { $quantity = 1; }
 $i = 
0;
 foreach ($_SESSION["cart_array"] as $each_item) { 
        
$i++;
        while (list($key, $value) = each($each_item)) {
      if 
($key == "item_id" && $value == $item_to_adjust) {
       // 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" => $item_to_adjust, "quantity" => 
$quantity)));
      } // close if condition
        } // close while 
loop
 } // close foreach loop
}
?>
 
<?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 = "<h3 align='center'>Your shopping cart is 
empty</h3>";
} else {
 
// 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_code = 
$row["product_code"];
   $product_name = $row["product_name"];
   $price = 
$row["price"];
   
  }
  $pricetotal = $price * 
$each_item['quantity'];
  $cartTotal = $pricetotal + $cartTotal;
        
$pricetotal = money_format("%.2n", $pricetotal);
 
// 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_code . '</a><br 
/><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_code. 
'" width="75" height="75" border="1" /></td>';
  $cartOutput .= 
'<td>R' . $engraving . '</td>';
  $cartOutput .= '<td>R' . 
$price . '</td>';
  $cartOutput .= '<td><form 
action="cart.php" method="post">
  <input name="quantity" type="text" 
value="' . $each_item['quantity'] . '" size="1" maxlength="2" /><br 
/>
  <br />
  <input name="adjustBtn' . $item_id . '" 
type="submit" class="submit" value="Change" />
  <input 
name="item_to_adjust" type="hidden" value="' . $item_id . '" 
/>
  </form></td>';
  //$cartOutput .= '<td>' . 
$each_item['quantity'] . '</td>';
  $cartOutput .= '<td>R' . 
$pricetotal . '</td>';
  $cartOutput .= '<td><form 
action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" 
type="submit" class="submit" value="X" /><input name="index_to_remove" 
type="hidden" value="' . $i . '" 
/></form></td>';
  $cartOutput .= '</tr>';
  $i++; 

    } 
    $cartTotal = money_format("%.2n", $cartTotal);
 $cartTotal 
= "R".$cartTotal." ";
}
?>
 
<!DOCTYPE html 
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
  
<title>Your Cart</title>
    <link rel="stylesheet" 
href="css/style.css" type="text/css" />
  
</head>
 
<body>
 
<?php 
include_once("storescripts/analyticstracking.php") ?>
 
<div 
id="page-container">
  
 <div id="header">
    
<?php
 include 
"storescripts/header.php";
 ?>
 </div>
 
 <div 
id="center-panel">
 
 <div class="box1">
 <?php
 include 
"storescripts/menu.php";
 ?>
 </div>
 
 <div 
class="box1">
 <center>
 <img src="images/cart.png" alt="Cart" 
title="Cart" border="0" />
 <h3>Your Cart</h3> 

 </center>
 <div style="margin:24px; 
text-align:left;">
    <table width="80%" border="1" cellspacing="0" 
cellpadding="6" align="center">
 <tr>
    <td width="20%" 
bgcolor="#FFFFFF"><strong>Product</strong></td>
    
<td width="35%" 
bgcolor="#FFFFFF"><strong>Engraving</strong></td>
    
<td width="10%" 
bgcolor="#FFFFFF"><strong>Price</strong></td>
    <td 
width="10%" 
bgcolor="#FFFFFF"><strong>Quantity</strong></td>
    
<td width="10%" 
bgcolor="#FFFFFF"><strong>Total</strong></td>
    <td 
width="10%" 
bgcolor="#FFFFFF"><strong>Remove</strong></td>
    
</tr>
    <?php echo $cartOutput; ?>
    </table>
    
<br />
 Cart Total: <?php echo $cartTotal; ?> | <a 
href="cart.php?cmd=emptycart">Empty your cart</a><br 
/>
 <br />
 <h3>If you buy 6 items, you will receive the 
6th item for free</h3>
 This adjustment will be made on your invoice 
before we send it to you.<br />
 <br 
/>
 <h3>Postage</h3>
 The postage cost is to be added to 
the total above.<br />
 &#8226; Post Office Registered Mail: 
R50<br />
 &#8226; Fastway Couriers (Limited Service): R55<br 
/>
 &#8226; Speed Services: R90<br />
 &#8226; Aramex 
Couriers (Full Service): R105<br 
/>
 </div>
 
 </div>
 
 </div>
 
 <div 
id="footer">
    <?php
 include 
"storescripts/footer.php";
 ?>
 </div>
 
</div>
 
</body>
</html> 

Could someone please help me get the text to be engraved added to the cart? I would really appreciate it. It is probably very simple, but I’m completely stuck.

Thanks
Susan

Hi Susan, Welcome to Sitepoint.

I’m too rusty on php so I wont try to recommend any solution.

Though I think you have some errors that could cause the failing:
In the page’s form1 you have a hidden input with the same ID as the engrave field. You need to change that.
cart.php line 48: the line-comment is wrapping to new line is illegal so the let’s apostrophe comes effective.

Please post again the result.

EDIT)
Should have mentioned there are several wrapping line-comments.

Thank you Erik_J.

The line-wrapping issue is only visible in this post - I copied and pasted my code and now it doesn’t look as clean as it should.

Let me just say that the code on my product and cart pages work very well - I just want to add code to send the engraving text on the product page to the cart. I don’t know how to do that. :worried:

Good, I thought so afterwards.

The cart:
I think you have overlooked, the “$engraving” need to be defined, maybe here:

array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));

Thank you Erik_J - I’ve tried to add it like this, but it is still not working:

array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "engraving" => $engraving, "quantity" => $each_item['quantity'] + 1)));

I said I’m rusty. :blush:

I think it should be made picking up the “post” value here i.e. like:

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

Still no joy unfortunately, but thank you so much for trying to help :blush:

You’re wide open to SQL Injection attack there as the user submitted data being sent to mysql isn’t being escaped. If the id is always going to be numeric then use (int) to typecast it as an integter, anything that isn’t an integter will result in a value of 0.

The mysql_* extension that you’re using was deprecated in version 5.5 of PHP and is being removed in version 7 of PHP. You should now be using either the mysqli_* extension or PDO (whichever of them two you migrate to, you should always use prepared statements when sending any data to the database.) PDO has the advantage of allowing named parameters.

1 Like

I saw your parallel post at PHP Freaks and I think you have already got the best answer in PHPFreaks forum.

Please, in the future, don’t post the same question in more than one place at the same time. Give them time to answer first. :wink:

I posted my question here first. Didn’t know I wasn’t allowed to post in more than one forum.

At the very least, giving each other forum the link to the other thread is the bare minimum. It helps us see if the other forum has figured it out so we don’t waste our precious time :slight_smile: .

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.