First of all I am new to OOP in PHP and a beginner to PHP in general.
I am working on a shopping cart for a friend's website. I found some code for a basic cart and am attempting to modify it to suit my purposes.
the code uses an ID that matches with a prod in the database and im ok with that. the problem begins when I try to add modifiers to the product. ex prod 1d and a color. this is sent to the cart in the form of a get and in this format. cart.php?action=add&id=1&color=c1
the cart then queries the database and pulls the prod name it also checks for dup id's. This is where I am getting lost.
Here is the cart code.
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<img src="images\cart.jpg" alt="cart" />You have <a href="/cart/cart.php">'.count($items).' item'.$s.' in your cart</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;
}
/*$colors = explode('c',$item);
foreach ($item as $cid) {
}*/
$output[] = '<form action="cart.php?action=update" method="post" id="cart">';
$output[] = '<table>';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE id = '.$id;
//$sql2 = 'SELECT * FROM colors WHERE id = '.$cid;
$result = $db->query($sql);
//$result2 = $db->query($sql2);
$row = $result->fetch();
//$row2 = $result2->fetch();
extract($row);
//extract($row2);
$output[] = '<tr>';
$output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
$output[] = '<td>'.$type.'</td>';
//$output[] = '<td>'.$color.'</td>';
$output[] = '<td>$'.$price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>$'.($price * $qty).'</td>';
$total += $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>Your cart is empty.</p>';
}
return join('',$output);
}
I have commented out the lines that I modified in an attempt to figure this out. I am thinking if I explode and break on 'c', the color identifier, then loop through again with a foreach then I can create a var for each c. then I need to either change the id in my database to show c# or parse out the c then query based on that. I am having trouble writing the code for that though.
Also if you dont mind can someone explain the => and how its used in PHP. I have done searches but they dont really explain it well. neither does the php.net site.
thanks.