0

Good day,

I am a PHP beginner, but have managed to set up a shopping cart on my jewelry website (with the help of video tutorials found online). Everything is working well, but I need to add a text box to my product page where people can add the engraving they would like to have on the specific product. This information then needs to be sent to the cart together with all the other details when they press Add to cart.

This is the Product page: Click Here

My product.php page has the following code:

<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" value="" 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>

The "engraving" field is what I need to be sent to cart.php and be displayed on in the cart's Engraving column.
Right now the Engraving column is empty and I get an Notice: Undefined index: engraving in /var/www/vhosts/personalizedjewellery.co.za/httpdocs/store/cart.php on line 13 error.

This is my cart.php code:

<?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'];
    $engraving = $_POST['engraving'];
    $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, "engraving" => $engraving, "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 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 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>' . $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" />
  <script src="storescripts/gen_validatorv4.js" type="text/javascript"></script>
</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">
    <h3>If you buy 6 items, you will receive the 6th item for free.</h3>
    We will make the necessary changes to your invoice before sending it to you.<br />
    <br />
    <h3>Postage</h3>
    Shipping cost needs to be added to the shopping cart's total.<br />
    You only pay once for shipping regardless of how many items you order.<br />
    <br />
    <br />
    <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 />
    <center>
    <b>Total: <?php echo $cartTotal; ?></b><br />
    </center>
    <br />

Can someone please help me with this? Will be forever grateful as I am completely stuck.

Thanks in advance,
Susan

Edited by Susan_4: added code

2
Contributors
13
Replies
46
Views
2 Years
Discussion Span
Last Post by Susan_4
0

Hi!

Notice: Undefined index: engraving in /path/httpdocs/store/cart.php on line 13 error

This usually happens when you try to access an array index key that does not exists, for example:

$a = array(
    'apple'  => 'fuji',
    'orange' => 'vanilla'
);

echo $a['apple'];
echo $a['coconut']; # will emit a notice because 'coconut' index does not exists

Now, it seems that your issue is in this line:

$engraving = $_POST['engraving'];

But I see in section 5 you print the $engraving variable apparently without defining it anywhere. It is defined only when a POST request is executed, but if you access the cart with a GET request then you should get a notice for undefined variable: engraving. So check if this is related to the cart saved in the session array. Do:

<?php

    echo "<pre>" . print_r($_SESSION['cart'], true) . "</pre>";

To get the contents, then if it does not help print the results and the code in which you define the variable.

0

Thanks so much for your answer. I do realize that the variable "engraving" needs to be defined - can you maybe tell me why it is not working when I place it in the code at this spot?

<?php 
//Section 1 (if user attempts to add something to the cart from the product page)//
    if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
    $engraving = $_POST['engraving'];
    $wasFound = false;
    $i = 0;

I've tried to do what you asked, but got another error: Notice: Undefined index: cart in /var/www/vhosts/personalizedjewellery.co.za/httpdocs/store/cart.php on line 346

Regards,
Susan

Edited by Susan_4: typo

0

I have now added the $engraving variable to this part of the code and it is no longer giving me an error, but also the variable is not being carried over from the form...

$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"];

        }
        $engraving = $row["engraving"];
        $pricetotal = $price * $each_item['quantity'];
        $cartTotal = $pricetotal + $cartTotal;
        $pricetotal = money_format("%.2n", $pricetotal);

Please help if you can

0

Sorry I meant cart_array:

<?php

    session_start();

    echo "<p>Session array:</p>";
    echo "<pre>" . print_r($_SESSION['cart_array'], true) . "</pre>";

Then point the form to a dummy cart script:

<?php

    echo "<p>Post array:</p>";
    echo "<pre>" . print_r($_POST, true) . "</pre>";

To see if all input fields are sent by the form.

0

This is what I get:

Session array:

Array
(
    [0] => Array
        (
            [item_id] => 1
            [quantity] => 7
        )

)

So the engraving is not sent... how do I get it to send from the form?
I've used this but no joy:

<input type="hidden" name="engraving" id="engraving" value="<?php echo $_POST['engraving']; ?>"><br />
0

Using $_POST['engraving'] as value of the input form assumes a previous step in which you set the value, i.e. another form, but if this form is accessed through a GET request the value will get lost.

Check how you set the values in the cart_array session, because on section 3 it seems you're setting only item_id and quantity, an example:

<?php


    $a[] = [
        'item_id'   => 123,
        'quantity'  => 21,
        'engraving' => 'hello world'
    ];

    $a[] = [
        'item_id'   => 124,
        'quantity'  => 17,
        'engraving' => 'hello to you'
    ];

    $i = 0;
    $item_to_adjust = 123;
    $quantity = 34;

    foreach($a as $each_item)
    {
        $i++;
        while (list($key, $value) = each($each_item))
            if ($key == "item_id" && $value == $item_to_adjust)
                array_splice($a, $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
    }

    print_r($a);
    print PHP_EOL;

It will return:

Array
(
    [0] => Array
        (
            [item_id] => 123
            [quantity] => 34
        )

    [1] => Array
        (
            [item_id] => 124
            [quantity] => 17
            [engraving] => hello you
        )

)

Try to simply replace the array_splace line with:

array_splice($a, $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity, "engraving" => $each_item['engraving'])));

And it should work.

0

Thank you so much for your help, but I simply can't get it to work (I've literally sat with this code the whole day). I can get the variable to be sent to the cart.php page and get it to echo, but I can't get the array to work at all. But thanks again for trying to help - I appreciate it.

0

You're welcome! If the above is full code I can try few tests, otherwise I can only suggest you to break each step to see where it fails, you can do this by:

  1. rewriting each part and feeding some example arrays;
  2. or by using die(print_r($var)) statements in the original code, where $var is the variable you want to check.
0

Hi cereal,

Thank you so much for trying to help me. I've given up trying to pass the variable from the form on the product.php page into the array on the cart.php page.

I've now added a text box into the shopping cart on the cart.php page and I would like people to now add the engraving they want in there.

An example: Click Here
Click on Add to cart to see the text box I now have.

How do I get the user's input in this text box to be sent to me with the specific item's details and the client's name, etc. upon submit? Is this even possible?

My cart.php code:

<?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 
//Engraving

if (isset($_POST['engraving']) && $_POST['engraving'] != "") {
    // execute some code
    $engraving = $_POST['engraving'];
    $i = 0;
    foreach ($_SESSION["cart_array"] as $each_item) { 
              $i++;
              while (list($key, $value) = each($each_item)) {
                  if ($key == "item_id" && $value == $engraving) {
                      // 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" => $engraving)));
                  } // close if condition
              } // close while loop
    } // close foreach loop
}
?>

<?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"];
            $price = $row["price"];
            $details = $row["details"];
        }
        $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="50" height="50" border="1" /></td>';
        $cartOutput .= '<td><form action="cart.php" method="post"><input name="text' . $item_id . '" type="text" class="submit" value="" /><input name="engraving" type="hidden" value="' . $i . '" /></form></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>
  <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="google-site-verification" content="bUmj7-OUJs-vqTz5T8ewp9S7t1qusFVXTsjPJCuoFp0" />
  <meta name="msvalidate.01" content="24177DD2A9E1F0F02F77DC28A542D3BC" />
  <meta name="description" content="Personalized Jewellery made from stainless steel and beautifully hand engraved with any name. Gifts for men and women! Bracelets, necklaces, rings, 
  keyrings, bag tags, pet tags, etc." />
  <meta name="keywords" content="personalized jewellery, personalized jewellery south africa, personalized gifts, personalized gifts south africa, personalized gifts for her, name 
  engraved, personalized gifts for him, birthday, mother's day, father's day, christmas, men, women, baby, bracelets, necklaces, keyrings, bag tags, pet tags, medical data, rings, 
  bidorbuy, stainless steel jewellery, engraved by hand, bidorbuy seller, susan wiese, hope floats website design, host4africa" />
  <meta name="geography" content="Bloemfontein, South Africa" />
  <meta name="city" content="Bloemfontein" />
  <meta name="state" content="Free State" />
  <meta name="author" content="Susan Wiese" />
  <meta name="robots" content="noodp,noydir"/>
  <link rel="stylesheet" href="css/style.css" type="text/css" />
  <script src="storescripts/gen_validatorv4.js" type="text/javascript"></script>
</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">
    <h3>If you buy 6 items, you will receive the 6th item for free.</h3>
    We will make the necessary changes to your invoice before sending it to you.<br />
    <br />
    <h3>Postage</h3>
    Shipping cost needs to be added to the shopping cart's total.<br />
    You only pay once for shipping regardless of how many items you order.<br />
    <br />
    <br />
    <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 />
    <center>
    <b>Total: <?php echo $cartTotal; ?></b><br />
    </center>
    <br />

    <?php 
    if( isset($_POST['submit'])) {
    if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
    // Insert code for processing the form here, e.g emailing the submission
    $to = "susan@personalizedjewellery.co.za"; 
    $subject = "Order Received"; 
    $name_field = $_POST['name']; 
    $email_field = $_POST['email']; 
    $contact_field = $_POST['contact']; 
    $street_field = $_POST['street']; 
    $suburb_field = $_POST['suburb']; 
    $city_field = $_POST['city'];
    $postalcode_field = $_POST['postalcode']; 
    $province_field = $_POST['province'];
    $shipping_field = $_POST['shipping']; 
    $payment_field = $_POST['payment'];  
    $codes_field = $_POST['codes']; 

    $total_field = $_POST['total']; 

    $from = "From: $email_field\r\n";

    $body = "\n Name: $name_field\n Email: $email_field\n Contact Number: $contact_field\n Street/PO Box: $street_field\n Suburb: $suburb_field\n City: $city_field\n Postal Code: $postalcode_field\n Province: $province_field\n Shipping: $shipping_field\n Payment: $payment_field\n Codes: $codes_field\n Total: $total_field"; 

    echo "<br /><center><h3>Thank you $name_field! Your order has been submitted and you will receive an invoice shortly (during office hours).</h3></center>"; 
    mail($to, $subject, $body, $from); 

    unset($_SESSION['security_code']);
    } else {
    // Insert your code for showing an error message here
    echo 'Sorry, you have provided an invalid security code.';
    }
    } else {
    ?>

    <center>
    <br />
    <form action="cart.php" id="myform" method="post">
    <label for="name">Full Name</label><br />
    <input type="text" name="name" id="name" size="35" /><br />
    <br />
    <label for="email">Email</label><br />
    <input type="text" name="email" id="email" size="35" /><br />
    <br />
    <label for="contact">Contact Number</label><br />
    <input type="text" name="contact" id="contact" size="35" /><br />
    <br />
    <label for="adress1">Street/PO Box</label><br />
    <input type="text" name="street" id="street" size="35" /><br />
    <br />
    <label for="adress2">Suburb</label><br />
    <input type="text" name="suburb" id="suburb" size="35" /><br />
    <br />
    <label for="city">City</label><br />
    <input type="text" name="city" id="city" size="35" /><br />
    <br />
    <label for="postalcode">Postal Code</label><br />
    <input type="text" name="postalcode" id="postalcode" size="35" /><br />
    <br />
    <label for="province">Province</label><br />
    <input type="text" name="province" id="province" size="35" /><br />
    <br />
    <label for="shipping">Shipping Options</label><br />
    <select name="shipping" id="shipping">
    <option selected disabled hidden value=''>- Please select -</option>
    <option value="Post Office Registered Mail: R50">Post Office Registered Mail: R50</option>
    <option value="Fastway Couriers (Limited Service): R55">Fastway Couriers (Limited Service): R55</option>
    <option value="Speed Services: R90">Speed Services: R90</option>
    <option value="Aramex Couriers (Full Service): R105">Aramex Couriers (Full Service): R105</option>
    </select><br />
    <br />
    <label for="shipping">Payment Options</label><br />
    <select name="payment" id="payment">
    <option selected disabled hidden value=''>- Please select -</option>
    <option value="EFT">EFT Payment</option>
    <option value="Cash Deposit">Cash Deposit at a Capitec branch</option>
    </select>
    <br />   
    <textarea name="codes" class="area"> <?php echo $product_id_array; ?></textarea><br />
    <input type="hidden" name="total" value="<?php echo $cartTotal; ?>">
    <br />
    <img src="captchasecurityimages.php?width=100&height=40&characters=5" /><br />
    <label for="security_code">Security Code</label>
    <br /><input id="security_code" name="security_code" type="text" /><br />
    <br />
    <input type="submit" class="submit" name="submit" value="Submit" />
    </form>

If you could point in me the right direction, I would be forever grateful. I'm not good at coding at all, but at least I'm trying. :)

0

Ok, at line 146 you set:

$cartOutput .= '<td><form action="cart.php" method="post"><input name="text' . $item_id . '" type="text" class="submit" value="" /><input name="engraving" type="hidden" value="' . $i . '" /></form></td>';

It means that $_POST['engraving'] will assume the value of $i which is starting from 0 because the $i++ is placed at the bottom of the loop. Also $_POST['text123'] is defined by the item_id, so you must read this index to access the engraving message, not $_POST['engraving'].

At line 58 we have:

if (isset($_POST['engraving']) && $_POST['engraving'] != "") {

    $engraving = $_POST['engraving'];
    $i = 0;

    foreach ($_SESSION["cart_array"] as $each_item) {

        $i++;
        while (list($key, $value) = each($each_item)) {

            if ($key == "item_id" && $value == $engraving) {

              array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $engraving)));

            }
        }
    }
}

Here $i++ starts from 1 because is not at the end of the foreach loop, then the IF statement that should match the item_id:

if ($key == "item_id" && $value == $engraving) {

is trying to match the value of $engraving which is the value assigned by the $i in the table block code: this can match only by accident, in most cases it will correctly fail. Also the array_splice is going to rewrite only the item_id by the $i value, not including the engraving nor the quantity.

Here you must decide if you want to update the cart_array by index key or by item_id and then move all the forms in this direction.

At the moment, to just patch the above code you can change line 146 with:

$cartOutput .= '<td><form action="cart.php" method="post">
    <input name="text' . $i . '" type="text" class="submit"><input name="engraving" type="hidden" value="' . $i . '" /></form></td>';

And line 58 with:

if (isset($_POST['engraving']) && $_POST['engraving'] != "") {

    $engraving = $_POST['engraving'];
    $message = $_POST['text' . $engraving];
    $i = 0;

    foreach ($_SESSION["cart_array"] as $each_item) { 
        if($engraving == $i)
            array_splice($_SESSION["cart_array"], $i, 1, array(array(
                "item_id"   => $each_item['item_id'],
                "engraving" => $message,
                "quantity"  => $each_item['quantity'])));
        $i++;
    }
}

Then it should start to work fine. Please note that I didn't any extensive tests.

Consider also to rewrite all the steps, at the moment this page has many forms and each will update itself without transporting the input filled in the other forms. You should consider to use a single form with arrays:

But it requires some rewrites in your current code.

0

Hi cereal - thanks so much. I went through your code line by line to make sure I understand what you were talking about. Then I added the code to my page. I'm no longer getting any error messages, so I must be moving in the right direction. Only thing now is that the engraving is still not sent to my email address. The email I get looks like this:

Name: Susan Wiese
Email: tikburo@vodamail.co.za
Contact Number: 0727044604
Street/PO Box: 12 Vlakfontein Avenue
Suburb: Pellissier
City: Bloemfontein
Postal Code: 9301
Province: Free State
Shipping: Post Office Registered Mail: R50
Payment: EFT
Codes: A3-1-
Total: R30.00

The engraving should appear right after A3-1- (the product code, the quantity and then the engraving).

It is at this line in my code:

// Create the product array variable
$product_id_array .= "$product_code-".$each_item['quantity']."-$message "; 

My full code for this page now looks like this:

<?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 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
//Engraving
    if (isset($_POST['engraving']) && $_POST['engraving'] != "") {
        $engraving = $_POST['engraving'];
        $message = $_POST['text' . $engraving];
        $i = 0;
        foreach ($_SESSION["cart_array"] as $each_item) { 
            if($engraving == $i)
                array_splice($_SESSION["cart_array"], $i, 1, array(array(
                    "item_id"   => $each_item['item_id'],
                    "engraving" => $message,
                    "quantity"  => $each_item['quantity'])));
            $i++;
        }
    }
?>

<?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"];
            $price = $row["price"];
            $details = $row["details"];
        }
        $message = $row["message"];
        $pricetotal = $price * $each_item['quantity'];
        $cartTotal = $pricetotal + $cartTotal;
        $pricetotal = money_format("%.2n", $pricetotal);

// Create the product array variable
        $product_id_array .= "$product_code-".$each_item['quantity']."-$message "; 
        // 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="55" height="55" border="1" /></td>';
            $cartOutput .= '<td><form action="cart.php" method="post"><input name="text' . $i . '" type="text" class="submit"><input name="engraving" type="hidden" value="' . $i . '" /></form></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>

<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 />
    <center>
    <b>Total: <?php echo $cartTotal; ?></b><br />
    </center>
    <br />

    <?php 
    if( isset($_POST['submit'])) {
    if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
    // Insert code for processing the form here, e.g emailing the submission
    $to = "susan@personalizedjewellery.co.za"; 
    $subject = "Order Received"; 
    $name_field = $_POST['name']; 
    $email_field = $_POST['email']; 
    $contact_field = $_POST['contact']; 
    $street_field = $_POST['street']; 
    $suburb_field = $_POST['suburb']; 
    $city_field = $_POST['city'];
    $postalcode_field = $_POST['postalcode']; 
    $province_field = $_POST['province'];
    $shipping_field = $_POST['shipping']; 
    $payment_field = $_POST['payment'];  
    $codes_field = $_POST['codes']; 

    $total_field = $_POST['total']; 

    $from = "From: $email_field\r\n";

    $body = "\n Name: $name_field\n Email: $email_field\n Contact Number: $contact_field\n Street/PO Box: $street_field\n Suburb: $suburb_field\n City: $city_field\n Postal Code: $postalcode_field\n Province: $province_field\n Shipping: $shipping_field\n Payment: $payment_field\n Codes: $codes_field\n Total: $total_field"; 

    echo "<br /><center><h3>Thank you $name_field! Your order has been submitted and you will receive an invoice shortly (during office hours).</h3></center>"; 
    mail($to, $subject, $body, $from); 

    unset($_SESSION['security_code']);
    } else {
    // Insert your code for showing an error message here
    echo 'Sorry, you have provided an invalid security code.';
    }
    } else {
    ?>

    <center>
    <br />
    <form action="cart.php" id="myform" method="post">
    <label for="name">Full Name</label><br />
    <input type="text" name="name" id="name" size="35" /><br />
    <br />
    <label for="email">Email</label><br />
    <input type="text" name="email" id="email" size="35" /><br />
    <br />
    <label for="contact">Contact Number</label><br />
    <input type="text" name="contact" id="contact" size="35" /><br />
    <br />
    <label for="adress1">Street/PO Box</label><br />
    <input type="text" name="street" id="street" size="35" /><br />
    <br />
    <label for="adress2">Suburb</label><br />
    <input type="text" name="suburb" id="suburb" size="35" /><br />
    <br />
    <label for="city">City</label><br />
    <input type="text" name="city" id="city" size="35" /><br />
    <br />
    <label for="postalcode">Postal Code</label><br />
    <input type="text" name="postalcode" id="postalcode" size="35" /><br />
    <br />
    <label for="province">Province</label><br />
    <input type="text" name="province" id="province" size="35" /><br />
    <br />
    <label for="shipping">Shipping Options</label><br />
    <select name="shipping" id="shipping">
    <option selected disabled hidden value=''>- Please select -</option>
    <option value="Post Office Registered Mail: R50">Post Office Registered Mail: R50</option>
    <option value="Fastway Couriers (Limited Service): R55">Fastway Couriers (Limited Service): R55</option>
    <option value="Speed Services: R90">Speed Services: R90</option>
    <option value="Aramex Couriers (Full Service): R105">Aramex Couriers (Full Service): R105</option>
    </select><br />
    <br />
    <label for="shipping">Payment Options</label><br />
    <select name="payment" id="payment">
    <option selected disabled hidden value=''>- Please select -</option>
    <option value="EFT">EFT Payment</option>
    <option value="Cash Deposit">Cash Deposit at a Capitec branch</option>
    </select>
    <br />   
    <textarea name="codes" class="area"> <?php echo $product_id_array; ?></textarea><br />
    <input type="hidden" name="total" value="<?php echo $cartTotal; ?>">
    <br />
    <img src="captchasecurityimages.php?width=100&height=40&characters=5" /><br />
    <label for="security_code">Security Code</label>
    <br /><input id="security_code" name="security_code" type="text" /><br />
    <br />
    <input type="submit" class="submit" name="submit" value="Submit" />
    </form>

I am nowhere near good enough to try and rewrite the code at this point, but thanks for letting me know about the forms. I really hope to one day be as good at writing code as you quite obviously are. :)

0

The engraving does not arrive because it is not included in the form used to send the email message, in order to work you should do something like this:

<textarea name="codes" class="area"> <?php echo $product_id_array; ?></textarea><br />

but for the engravings which can be multiple if the cart handles more than one item.

I want to point you to a problem: the textarea even if hidden can be modified and used by the user to submit whatever he wants, the same applies to the total. It is extremely unsafe. You should not accept this input from this form, but calculate it on server side basing on what you have saved in the session. It's correct to display this information to the user, but never retrieve it, as you already have what you need to define totals and item list.

So best solution is to elaborate all this information on server side, create and a table that will be included in your email message, so instead of $codes_field = $_POST['codes']; do:

$rows = [];

foreach($_SESSION["cart_array"] as $each_item)
{
    $rows[] = "
        <tr>
            <td>{$each_item['item_id']}</td>
            <td>{$each_item['engraving']}</td>
            <td>{$each_item['quantity']}</td>
        </tr>
    ";
}

$codes_field = "
<table>
    <thead>
        <tr>
            <th>Item ID</th>
            <th>Engraving</th>
            <th>Quantity</th>
        </tr>
    </thead>
    <tbody>
        ". implode(PHP_EOL, $rows) ."
    </tbody>
</table>
";

Instead of $total_field = $_POST['total']; generate the cart total as in section 5, do not trust the form. To avoid repetition of tasks you could update a session variable each time the cart is updated, so on section 5, after line 118 you could add:

$cartTotal = money_format("%.2n", $cartTotal);
$cartTotal = "R".$cartTotal." ";
$_SESSION['cart_total'] = $cartTotal;

And in your mail script use:

$total_field = $_SESSION['cart_total'];

If still in doubt let us know.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.