Jump to content

Create Cart That Allows User To Choose Additional Info About Product


frshjb373
 Share

Recommended Posts

Trying to create a shopping cart that allows user to select not only the product, but the condition of the item (poor condition, good condition, excellent condition), and additional accessories based on the form data submitted. Basically, I'd like to use the same ID for a product with different conditions and accessories. Just not sure how to get there. Any help, advice, or resources is much appreciated! Thank you.

 

Here is the form data I'm collecting from the user:

// Phone Type
$field_Phone = $_POST['field_Phone'] = $_SESSION['field_Phone'];
// Accessories
$field_Charger = $_POST['field_Charger'] = $_SESSION['field_Charger'];
$field_Case = $_POST['field_Case'] = $_SESSION['field_Case'];
$field_Manual = $_POST['field_Manual'] = $_SESSION['field_Manual'];
$field_Box = $_POST['field_Box'] = $_SESSION['field_Box'];
// Item Condition
$field_Condition = $_POST['field_Condition'] = $_SESSION['field_Condition'];

 

Here's the item from the database:

<?php
// DB Query
$query = "SELECT * FROM phones WHERE name = '{$field_Phone}'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$output[] = '<a href="cart-demo/cart.php?action=add&id='.$row['id'].'">Add to cart</a>';
}
?>

 

Here's the functions that output the product selected:

<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return 'Cart (Empty)';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return 'Cart (<a href="cart-demo/cart.php">'.count($items).'</a>)';
}
}
function showCart() {
global $db;
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM phones WHERE id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
$output[] = "<td>" .$name. "</td>";
$output[] = "<td><img src=\"../images/catalog-images/" .$photo_image. "\" width=\"50\"/></td>";
$output[] = "<td> ".$_SESSION['accessories']." </td>";
$output[] = '<td> $ '.$price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td> $'.($base_price * $qty).'</td>';
$total += $base_price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Grand total: <strong>$ '.$total.'</strong></p>';
$output[] = '<div><button type="submit">Update cart</button></div>';
$output[] = '</form>';
} else {
$output[] = '<p>You shopping cart is empty.</p>';
}
return join('',$output);
}
?>

 

Here's the cart code:

$cart = $_SESSION['cart'];
$action = $_GET['action'];
$_SESSION['accessories'];
switch ($action) {
case 'add':
if ($cart) {
$cart .= ','.$_GET['id'];
} else {
$cart = $_GET['id'];
}
break;
case 'delete':
if ($cart) {
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if ($_GET['id'] != $item) {
 if ($newcart != '') {
 $newcart .= ','.$item;
 } else {
 $newcart = $item;
 }
}
}
$cart = $newcart;
}
break;
case 'update':
if ($cart) {
$newcart = '';
foreach ($_POST as $key=>$value) {
if (stristr($key,'qty')) {
$id = str_replace('qty','',$key);
$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
 if ($id != $item) {
 if ($newcart != '') {
 $newcart .= ','.$item;
 } else {
 $newcart = $item;
 }
 }
}
for ($i=1;$i<=$value;$i++) {
 if ($newcart != '') {
 $newcart .= ','.$id;
 } else {
 $newcart = $id;
 }
}
}
}
}
$cart = $newcart;
break;
}
$_SESSION['cart'] = $cart;

Link to comment
Share on other sites

To store data for any id as you have asked will require that you change the definition of your cart from a comma separated list of id's to an array of arrays, where the 1st dimension array index is the id and you store the additional information (quantity, condition, accessories) for each selection of that id as a sub-array. The accessories would also be an array of arrays with the accessory id, quantity, condition,... of each accessory selected.

 

Doing this will also greatly simplify your existing code because you won't need to copy, explode, loop over the contents of the cart, and implode it every time you need to do anything to it. You will just reference the correct array element by using the id as the index - $_SESSION['cart'][$id]

 

Also, you should not have any database queries inside of loops. You would use one query that gets all the rows you want at one time, then loop over the rows the query matched.

Link to comment
Share on other sites

This is definitely a brain buster! Thank you for the help. So as far as bringing additional accessories and variables to the cart page so it belongs to that same product id, what would be the best method to bring those values to the cart page? I'm probably trying to do something well above my skill level, but I'd still like to figure this out and ask questions. Thanks again.

Link to comment
Share on other sites

You would end up with a parent/child association (see this thread - http://forums.phpfreaks.com/topic/271801-mysql-hierarchy-structure/ ). I have modified the displayHierarchy() function from that thread so that it allows multiple entries (an additional array dimension) for any id (to allow the same id with different conditions to be added to your cart.) See the following example code for how the cart would/could look and how you can iterate over it -

 

<?php
session_start();

// fake cart contents for demo purposes
$_SESSION['cart'] = array();
$_SESSION['cart'][0][123][] = array('qty'=>2,'condition'=>3); // main item 123, qty 2, condition 3
$_SESSION['cart'][0][123][] = array('qty'=>2,'condition'=>2); // main item 123, qty 2, condition 2
$_SESSION['cart'][123][555][] = array('qty'=>1,'condition'=>1); // accessory item 555 for item 123, qty 1, condition 1
$_SESSION['cart'][456][555][] = array('qty'=>1,'condition'=>1); // accessory item 555 for item 456, qty 1, condition 1
$_SESSION['cart'][123][555][] = array('qty'=>1,'condition'=>2); // accessory item 555 for item 123, qty 1, condition 2
$_SESSION['cart'][123][555][] = array('qty'=>1,'condition'=>3); // accessory item 555 for item 123, qty 1, condition 3
$_SESSION['cart'][0][456][] = array('qty'=>1,'condition'=>1); // main item 456, qty 1, condition 1

function displayHierarchy(&$arr, $parent, $indent=0){
   // define condition value/legend
   $conditions = array(1=>'poor',2=>'good',3=>'excellent');
   $ind = $indent * 30;
   if (isset($arr[$parent]))
       foreach($arr[$parent] as $id=>$rec){

           // $rec is an array of 1 or more entries for the same id
           foreach($rec as $item){

               echo "<div style='width:400px; margin-top:5px; margin-left: {$ind}px; padding:5px; border:1px solid gray;'>
               ID: $id - " . (($parent) ? "Accessory for: $parent - " : '') . "Qty: {$item['qty']} - Condition: {$conditions[$item['condition']]}
               </div>" ;
           }
           displayHierarchy($arr, $id, $indent+1);
       }
}

// call the recursive display function
displayHierarchy($_SESSION['cart'], 0);

Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  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.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.