I want to update the quantity of an item in the cart
These are the actions:
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM menu WHERE item_code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["item_code"]=>array('name'=>$productByCode[0]["item_name"], 'code'=>$productByCode[0]["item_code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["item_price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["item_code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["item_code"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
This is the cart code:
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["quantity"]; ?></td>
<td><?php echo "₹".$item["price"]; ?></td>
<td><a id="remove" href="index.php?action=remove&code=<?php echo $item["code"]; ?>"><span class="fa fa-times fa-lg" style="color:red;"></span></a></td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
I need something like when click on update button so it can take the value and update the session array of particular product quantity
Please help me out...
This is a pretty basic example, but you should make a function per action so you can more easily port the cart. Also, I am not sure why you have a $_GET in the switch and a $_POST in the case():
function AddToCart($default = 1)
{
// Set a default quantity (1). Check that the value is set and is number
// Not sure why you are using a get for the code but not for these
// attributes. Should it not be $_GET['quantity']??
$qty = (isset($_POST['quantity']) && is_numeric($_POST['quantity']))? $_POST['quantity']:$default;
// Check that there is a valid numeric itemcode
$item = (isset($_POST['item_code']) && is_numeric($_POST['item_code']))? $_POST['item_code']:false;
// If false, stop
if(!$item)
return;
// Do your product query
$productByCode = $db_handle->runQuery("SELECT * FROM menu WHERE item_code='" . $_GET["code"] . "'");
// Assign the item code
$itmcd = $_GET["code"];
$itemArray['code'] = $itmcd;
$itemArray['name'] = $productByCode[0]["item_name"];
$itemArray['price'] = $productByCode[0]["item_price"];
$itemArray['quantity'] = (isset($_SESSION["cart_item"][$itmcd]))? $_SESSION["cart_item"][$itmcd]['quantity']+$qty : $qty;
$_SESSION["cart_item"][$itmcd] = $itemArray;
}
To use:
if(isset($_GET["action"]) && $_GET["action"] == 'add'))
AddToCart();
Related
I'm building a shopping cart using a free script I found. I am trying to count the items in each category to determine shipping charges. Categories are numeric in the database 1,2,3, etc. The script I have groups the items by item number (code) when displayed, and I can't seem to figure how to group by category and produce a total amount of items in each category. I'm pretty terrible with arrays. Thanks for the help.
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM products WHERE code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"],
'code'=>$productByCode[0]["code"],
'category'=>$productByCode[0]["category"],
'quantity'=>$_POST["quantity"],
'price'=>$productByCode[0]["price"],
'image'=>$productByCode[0]["image"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["code"],array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["code"] == $k) {
if(empty($_SESSION["cart_item"][$k]["quantity"])) {
$_SESSION["cart_item"][$k]["quantity"] = 0;
}
$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
}
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
Here is the code to show items in the cart:
foreach ($_SESSION["cart_item"] as $item){
$item_price = $item["quantity"]*$item["price"];
echo $item['image'];
echo $item["name"];
echo $item["code"];
echo #item["category"];
echo $item["quantity"];
echo $item["price"];
}
$total_quantity += $item["quantity"];
$total_price += ($item["price"]*$item["quantity"]);
Ok, I took a step back and kept it simple. I went back and created a category counter before the foreach loop. In the loop I checked which category was registering and added the quantity of item to the counter for that category. Simple but it works.
I'm trying to loop all rows of a table name cart but the foreach is only displaying the last row entered and always ignore the previous ones. Say I have 5 products in the cart_table well only product_id[5] will be displayed. If user adds a sixth item, only product_id[6] will now be displayed. The $item_count will also always equal 1 as if there is only one item when there are multiple. To my understanding in the foreach($items as $item) $items is not seen as an array even with multiple items. when I var_dump($items); it shows array(1) { [0]=>...
add_cart.php
<?php
ob_start();
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/core/init.php';
$product_id = isset($_POST['product_id'])? sanitize($_POST['product_id']):'';
$size = isset($_POST['size'])? sanitize($_POST['size']):'';
$available = isset($_POST['available'])? sanitize($_POST['available']):'';
$quantity = isset($_POST['quantity'])? sanitize($_POST['quantity']):'';
$item = array();
$item[] = array(
'id' => $product_id,
'size' => $size,
'quantity' => $quantity,
'available' => $available
);
$domain =($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$query = $db->query("SELECT * FROM product WHERE id = '{$product_id}'");
$product = mysqli_fetch_assoc($query);
$_SESSION['success_flash'] = $product['prod_name']. ' was added to your cart.';
//check if the cart cookie exists
if (is_array($cart_id != ' ')) {
$cartQ = $db->query("SELECT * FROM cart WHERE id = '{$cart_id}'");
$cart = mysqli_fetch_assoc($cartQ);
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach($previous_items as $pitem){
if ($item[0]['id'] == $pitem['id'] && $item[0]['size'] == $pitem['size']) {
$pitem['quantity'] = $pitem['quantity'] + $item[0]['quantity'];
if ($pitem['quantity'] > $available) {
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if ($item_match != 1) {
$new_items = array_merge($item,$previous_items);
}
$items_json = json_encode($new_items);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = '{cart_id}'");
setcookie(CART_COOKIE,'',1,"/",$domain,false);
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}else{
// add to databse and set cookie
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}')");
$cart_id = $db->insert_id;
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
?>
cart.php
<?php
require_once 'core/init.php';
//include 'includes/headerpartial.php';
if($cart_id != ' ') {
$cartQ = $db->query("SELECT * FROM cart WHERE id ='{$cart_id}' ");
$result = mysqli_fetch_assoc($cartQ);
$items = json_decode($result['items'], true);
$i = 1;
$sub_total = 0;
$item_count = 0;
}
?>
<?php if($cart_id == ' '): ?>
<div class="bg-danger">
<p class='text-center text-danger'>Your cart is empty.</p>
</div>
<?php else: ?>
<?php
foreach ($items as $item) {
var_export($items);
$product_id = $item['id'];
$productQuery = $db->query("SELECT * FROM product WHERE id ='{$product_id}' ");
$product = mysqli_fetch_assoc($productQuery);
$sArray = explode(',', $product['sizes']);
/* foreach ($sArray as $sizeString) {
$s = explode(':', $sizeString);
if($s[0] == $item['size']) {
$available = $s[1];
}
}*/
?>
<tr class="p">
<td class="image"><img src="<?= $product['image_1']; ?>"/></td>
<td class="name"><?= $product['prod_name']; ?></td>
<td class="price"><?= money($product['price']); ?></td>
<td class="quantity"><?= $item['quantity']; ?></td>
<td class="pricesubtotal"><?= money($item['quantity'] * $product['price']); ?></td>
<td class="remove">
<div>×</div>
</td>
</tr>
<?php
$i ++;
$item_count += $item['quantity'];
$sub_total += ($product['price'] * $item['quantity']);
}
$tax = TAXRATE * $sub_total;
$tax = number_format($tax, 2);
$grand_total = $tax + $sub_total;
<?php endif;?>
Here is one of the problems. You told me that your id is an auto increment int, so I would like to propose this answer. The problem is in your sql command.
UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = {cart_id}
Be sure to put that command in quotes. Also, I highly recommend preparing the JSON with this command:
$itemJson = addslashes($itemJson);
then, you can run the command. Another possibility would be to use the prepare method from mysqli. Here is a link to some examples:
w3schools.com
if you have any further questions, feel free to update your question, but be sure to #McStuffins in the comments.
I have no idea where to get size value and input it to my database
this is my database table called transaksi with these column
idtransaksi, noinvoice, idproduk, size, jumlah
and here is my script
chart.php
<?php
if (!isset($_SESSION)) {
session_start();
}
cek_status_login($_SESSION['idpelanggan']);
include ('chart.inc.php');
// Process actions
$chart = isset ($_SESSION['chart']) ? $_SESSION['chart'] : '';
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'add' :
if ($chart) {
$chart .= ',' . $_GET['id'];
} else {
$chart = $_GET['id'];
}
break;
//
//B002,5,S,B003,10,M
case 'delete' :
if ($chart) {
$items = explode(',', $chart);
$newchart = '';
foreach ($items as $item) {
if ($_GET['id'] != $item) {
if ($newchart != '') {
$newchart .= ',' . $item;
} else {
$newchart = $item;
}
}
}
$chart = $newchart;
}
break;
case 'update' :
if ($chart) {
$newchart = '';
foreach ($_POST as $key => $value) {
if (stristr($key, 'qty')) {
$id = str_replace('qty', '', $key);
$items = ($newchart != '') ? explode(',', $newchart) : explode(',', $chart);
$newchart = '';
foreach ($items as $item) {
if ($id != $item) {
if ($newchart != '') {
$newchart .= ',' . $item;
} else {
$newchart = $item;
}
}
}
for ($i = 1; $i <= $value; $i++) {
if ($newchart != '') {
$newchart .= ',' . $id;
} else {
$newchart = $id;
}
}
}
}
}
$chart = $newchart;
break;
}
$_SESSION['chart'] = $chart;
?>
<section class="main-content">
<div class="row">
<div class="span9">
<?php echo writeShoppingchart();
echo showchart();
if (isset($_GET['s'])) {
if ($_GET['status'] == OK) {
echo "proses pembelian berhasil dilakukan sudah selesai";
} else {
echo "operasi gagal";
}
}
?>
</div>
<script type="text/javascript">
$('.input').on('input',function(e){
if($(this).data("lastval")!= $(this).val()){
$(this).data("lastval",$(this).val());
//change action
alert('Anda Mengubah Jumlah SubTotal barang, Silahkan Update Keranjang Belanja');
};
});
</script>
<?php
include ('inc/sidebar-front.php');
?>
</div>
</section>
chart.inc.php
<?php
function kd_transaksi() {
$kode_temp = fetch_row("SELECT noinvoice FROM invoice ORDER BY noinvoice DESC LIMIT 0,1");
if ($kode_temp == '')
$kode = "E00001";
else {
$jum = substr($kode_temp, 1, 6);
$jum++;
if ($jum <= 9)
$kode = "E0000" . $jum;
elseif ($jum <= 99)
$kode = "E000" . $jum;
elseif ($jum <= 999)
$kode = "E00" . $jum;
elseif ($jum <= 9999)
$kode = "E0" . $jum;
elseif ($jum <= 99999)
$kode = "E" . $jum;
else
die("Kode pemesanan melebihi batas");
}
return $kode;
}
function writeShoppingchart() {
$chart = $_SESSION['chart'];
if (!$chart) {
return '<h4 class="title"><span class="text pull-left"><strong>Keranjang Belanja Masih Kosong</strong></span></h4>';
} else {
// Parse the chart session variable
$items = explode(',', $chart);
$s = (count($items) > 1) ? 's' : '';
return '<h4 class="title"><span class="text pull-left"><strong>Periksa Jumlah Pesanan Anda Sebelum Check Out</strong></span></h4>';
}
}
function chartNotification() {
$chart = $_SESSION['chart'];
if (!$chart) {
return '0';
} else {
// Parse the chart session variable
$items = explode(',', $chart);
return count($items);
}
}
function getQty() {
$chart = $_SESSION['chart'];
if (!$chart) {
return 0;
} else {
// Parse the chart session variable
$items = explode(',', $chart);
$s = (count($items) > 1) ? 's' : '';
return count($items);
}
}
function showchart() {
$chart = $_SESSION['chart'];
// print_r($chart);
if ($chart) {
$items = explode(',', $chart);
$contents = array();
$total='';
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$output[] = "<table class=\"table table-striped \">";
$output[] = "<th><td>Nama</td><td>size</td><td> Harga</td><td>jumlah</td><td>diskon</td><td>subtotal</td><td>Aksi</td></th>";
$output[] = '<form action="index.php?mod=chart&pg=chart&action=update" method="post" id="chart">';
$no = 1;
foreach ($contents as $id => $qty) {
$sql = "SELECT produk.*, stok.harga_barang, stok.harga_jual, stok.jumlah, stok.ext_disc, stok.disc, stok.size FROM stok LEFT OUTER JOIN produk ON stok.idproduk = produk.idproduk WHERE produk.idproduk = '$id'";
$result = mysql_query($sql);
$row = mysql_fetch_object($result);
$size = explode(',', $row->size);
$quantity = ($row->jumlah);
$diskonext =(($row->harga_jual)*($row->ext_disc)/100);
$output[] = '<tr><td>' . $no . '</td>';
$output[] = '<td>'.$row ->nama_produk. '<br /><img src=\'upload/produk/' . $row ->foto .' \' width=\'100px\' height=\'100px\'></td>';
$output[] = '<td><select name="size" style="width:50px;">';
for ($i = 0; $i < count($size); $i++){
$output[] = '<option value="'. $size[$i] .'">'. $size[$i] .'</option>';
}
$output[] = '</select></td>';
$output[] = '<td>' . format_rupiah($row -> harga_barang) . '</td>';
if ($qty >= 10){
$total += (($row -> harga_jual) - $diskonext) * $qty;
}else {
$total += $row -> harga_jual * $qty;
}
if ($qty > $quantity){
$output[] = '<td><input type="text" class="input-mini" name="qty' . $id . '" value="'.$quantity.'"/><br /><span class="label label-warning pull-right">Stok hanya '.$quantity.'</span></td>';
} else {
$output[] = '<td><input type="text" onkeypress="alert(\'jumlah barang terganti, silahkan Update Keranjang belanja anda sebelum chekout\');" class="input-mini" name="qty' . $id . '" value="' . $qty . '"/></td>';
}
if ($qty >= 10){
$output[] = '<td>' . $row->disc . ' % + '. $row -> ext_disc .'% </td>';
} else {
$output[] = '<td>' . $row->disc . ' %</td>';
}
if ($qty >= 10){
if ($qty > $quantity){
$output[] = '<td>'.format_rupiah(($row->harga_jual - $diskonext)*$quantity).'</td>';
} else {
$output[] = '<td>'.format_rupiah(($row->harga_jual - $diskonext)*$qty).'</td>';
}
}else{
if ($qty >= $quantity){
$output[] = '<td>'.format_rupiah($row->harga_jual*$quantity).'</td>';
} else {
$output[] = '<td>'.format_rupiah($row->harga_jual*$qty).'</td>';
}
}
$output[] = '<td>Hapus</td></tr>';
$no++;
}
$output[] = '<tr><td colspan=\'6\' ><h4>Total Belanja Anda</h4></td><td colspan=\'2\'><h4>'. format_rupiah($total) .'</h4></td></tr>';
$output[] = "</table>";
$qty = getQty();
$_SESSION['totalbayar'] = $total;
$output[] = '<button type="submit" class=\'btn btn-primary\'>Update Keranjang Belanja</button>';
if ($qty >= ($row->jumlah)){
$output[] ='<button type="submit" class=\'btn btn-success pull-right\'>Update Keranjang Belanja Anda</button>';
} else {
$output[] ='<a href=\'chart/chart_action.php\' class=\'btn btn-success pull-right\'>Check out</a>';
}
$output[] = '</form>';
} else {
$output[] = '<p>Keranjang belanja masih kosong.</p>';
}
return join('', $output);
}
function insertToDB($kd_transaksi, $idpelanggan, $totalbayar, $sizes) {
$chart = isset($_SESSION['chart'])? $_SESSION['chart']: '';
if ($chart) {
$items = explode(',', $chart);
$contents = array();
foreach ($items as $item) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
}
$sql_transaksi = "insert into invoice (noinvoice,tanggal,totalbayar,idpelanggan)
values( '$kd_transaksi', now(),'$totalbayar','$idpelanggan')";
//echo "SQL transaksi:".$sql_transaksi;
mysql_query($sql_transaksi) or die(mysql_error());
foreach ($contents as $id => $qty) {
$sql = "insert into transaksi(noinvoice,idproduk,size,jumlah)
values('$kd_transaksi','$id','$sizes','$qty')";
// echo "SQL transaksi:".$sql;
$result = mysql_query($sql) or die(mysql_error());
}
} else {
$output[] = '<p>Keranjang belanja masih kosong.</p>';
}
}
?>
and chart.action.php
<?php
session_start();
require_once ('../inc/config.php');
require_once ('../inc/function.php');
require_once ('../chart/chart.inc.php');
$idpelanggan=$_SESSION['idpelanggan'];
/* menambahkan kode pesan dan detail pesan kedalam database*/
$kd_transaksi = kd_transaksi();
$total_bayar = $_SESSION['totalbayar'];
insertToDB($kd_transaksi,$idpelanggan,$total_bayar);
//check if query successful
$link="location:../index.php?mod=chart&pg=chart_ship&total_bayar=$total_bayar&kd_transaksi=$kd_transaksi";
header($link);
?>
Still get confused how to input size value to database. and if you need more information to help me just tell me what I have to do
Thanks
The function insertToDB is defined with 4 parameters in the code above:
function insertToDB($kd_transaksi, $idpelanggan, $totalbayar, $sizes) {
But it is called with only 3 values:
insertToDB($kd_transaksi,$idpelanggan,$total_bayar);
So I suggest passing the value posted for variable size when calling the function:
insertToDB($kd_transaksi,$idpelanggan,$total_bayar,$_POST["size"]);
Btw: commenter #giraff is absolutely right when meaning the SQL injection. Your scripts are vulnerable to it. You should definitely check and sanitize user-submitted data!
Am having issues with my cart script, i've managed to get it to work by adding an item to the cart, but its not allowing any more items to be added but rather it allows the quantity to be added even when i add another item, its the quantity of the first item that will be increased, here is my code snippet
This my function script that wrietes and generates the cart
<?php
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 '<p>You have '.count($items).' item'.$s.' in your shopping cart</p>';
}
}
function showCart() {
$currency = 'UGX';
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 class="table table-striped">';
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM products WHERE product_id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<tr>';
$output[] = '<td>Remove</td>';
$output[] = '<td>'.$product_name.'</td>';
$output[] = '<td>'.$currency.''.$product_price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '<td>'.$currency.''.($product_price * $qty).'</td>';
$total += $product_price * $qty;
$output[] = '</tr>';
}
$output[] = '</table>';
$output[] = '<p>Grand total: <strong>'.$currency.''.$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);
}
?>
This is my cart script that handles actions from the cart buttons(add, delete and update)
<?php
session_start();
$cart = $_SESSION['cart'];
$action = $_GET['action'];
switch ($action) {
case 'add':
if ($cart) {
$cart .= ','.!isset($_GET['product_id']);
} else {
$cart = !isset($_GET['product_id']);
}
break;
case 'delete':
if ($cart) {
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $item) {
if (!isset($_GET['product_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;
?>
And this is how send actions to my cart from the add button
<form action="cart.php?action=add&id=<?php echo $row_prdt_details['product_id']; ?>" method="post" id="cart">
<fieldset>
<address>
<strong>Name:</strong> <span><?php echo $row_prdt_details['product_name']; ?></span><br>
<strong>Cake Code:</strong> <span><?php echo $row_prdt_details['product_id']; ?></span><br>
<strong>Availability:</strong> <span>
</span><br>
</address>
<h4><strong>Price: UGX <?php echo $row_prdt_details['product_price']; ?></strong></h4>
<p> </p>
<label>Qty:</label>
<input type="text" class="span1" name="qty" placeholder="1">
<input type="submit" onClick="window.location.reload()" />
</fieldset>
</form>
All i want to achieve is to be able to add more items
Any help is greatly welcomed, if u have any questions about what am doing please ask me
I've coded out my cart page and it seems that it is not showing anything. Previously on my product page, I have a form action that will lead me to cart.php upon clicking add to cart. I am not sure what went wrong here.
<?php
session_start();
//script error reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Connect to the MySQL database
include "storescripts/connect.php";
?>
<?php
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(1 => 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_slice()
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));
}
}
}
?>
<?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 (render the cart for the user to view)
$cartOutput = "";
if (!isset($_SESSION["crt_array"]) || count($_SESSION["cart_array"]) < 1) {
$cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>";
} else {
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
$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"];
}
$cartOutput .= "<h2>Cart Item $i</h2>";
//while(list($key, $value) = each($each_item))
// $cartOutput .= "$key: $value<br/>";
$cartOutput .= "Item ID:" . $each_item['item_id'] . "<br/>";
$cartOutput .= "Item Quantity:" . $each_item['quantity'] . "<br/>";
$cartOutput .= "Item Name:" . $product_name . "<br/>";
$cartOutput .= "Item Price: $" . $price . "<br/>";
}
}
?>
You have a minor error there. Spelling mistake my dear. It happens. Human error always happens(: And its at session cart array(: