I have a problem with my shopping cart functionality of my restaurant website.
For example, if i add an item to the cart, then i add another item, then if I delete the one I added last and add it again, it's adding itself doubled in the session. Here I have the functions for adding and removing the items in the shopping cart:
function AddProd($id_prod, $quant) {
if(isset($_SESSION['cart'])){
$_SESSION['cart'].=$id_prod.'>'.$quant.",";
} else {
$_SESSION['cart']=$id_prod.'>'.$quant.",";
}
}
function RemoveFromCart($id_prod) {
if(isset($_SESSION['cart'])) {
$n = $_SESSION['cart'];
$prod_id = substr($n, 0, -1);
$ids = explode(',', $prod_id);
$prods = '';
foreach ($ids as $id) {
$i = explode('>', $id);
if($i[0] != $id_prod) $prods = $prods.''.$id.',';
}
$_SESSION['cart'] = $prods;
}
}
Here i have the function which sets the quantity of the item:
function SetCartNumber($conn) {
if(isset($_SESSION['cart'])) {
$n = $_SESSION['cart'];
$prod_id = substr($n, 0, -1);
$ids = array_map('trim', explode(',', $prod_id));
foreach ($ids as $id) {
$i = explode('>', $id);
$total = $total + $i[1];
}
return $total;
}
return 0;
}
Here it inserts into databse:
function LastId($conn, $tbl){
$s = 'SELECT `id` FROM `'.$tbl.'` ORDER BY `id` DESC LIMIT 1';
if ($r = mysqli_query($conn, $s)) {
$rowd = mysqli_fetch_array($r, MYSQLI_NUM);
return $rowd[0];
}
return -1;
}
$t_price = (empty(GetPromotion($connect))) ? $total_price : '<span style="color: white; font-weight: bold;">'.SetPromotion($connect).'</span> <span style="text-decoration: line-through; color: red;">'.$total_price.'</span>';
if(isset($_POST['delete_prod'])) {
RemoveFromCart($_POST['delete_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if(isset($_POST['decrease_prod'])) {
ProdsDecrease($_POST['decrease_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if(isset($_POST['increase_prod'])) {
ProdsIncrease($_POST['increase_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if (!empty($_POST['trimite']))
{
$str_name = ($str_name[strlen($str_name)-2] == ',') ? substr($str_name, 0, -2) : $str_name;
$str_name2 = ($str_name2[strlen($str_name2)-2] == ',') ? substr($str_name2, 0, -2) : $str_name2;
$price = (empty(SetPromotion($connect))) ? SetCartPrice($connect) : SetPromotion($connect);
$price = (!empty(GetPromotion($connect))) ? $price.' lei(Promotie activa: '.GetPromotion($connect).'%)' : $price;
$prods = MailProds($connect);
$quantity = SetCartNumber($connect);
$price1 = (empty(SetPromotion($connect))) ? SetCartPrice($connect) : SetPromotion($connect);
$price1 = floatval($price1);
$quantity = floatval($quantity);
$email = filter_input(INPUT_POST, 'email');
$telefon = filter_input(INPUT_POST, 'telefon');
$mentiuni = filter_input(INPUT_POST, 'mentiuni');
$tacamuri = filter_input(INPUT_POST, 'tacamuri');
if(!empty(get())) { $email = getEmail($connect); }
$sql = "INSERT INTO `comenzi`(`name`, `pret`, `cantitate`, `adresa_mail`, `nr_telefon`, `mentiuni`, `tacamuri`) VALUES ('$prods', '$price1', '$quantity', '$email', '$telefon', '$mentiuni', '$tacamuri')";
How could I solve the issue?
the problem is in addProd funtion function. you session must contains unique prodId values. but when you are adding the same product again. you are not deleting the first then you will face the problem.
so you should check if the product is already is in session or not, before adding it.
or you should update it.
Related
I created a very simple shopping cart that just add item s to it and delete items from it and empty the cart too now I know I have a lot of issues in my code but I am trying to fix them as well
first see my code
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $c) {
echo $c['name'] . '<br />';
echo $c['price'] . '<br />';
echo 'Remove item<br />';
}
}
if (isset($_POST['buy'])) {
//header("Location:?pid=18&pl=" . $pl);
if (isset($_POST['buy'])) {
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if (($pn = $res->fetch_object()) !== null) {
$proCode = rand(1, 100);
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
$item['code'] = $proCode;
$_SESSION['cart'][] = $item;
}
}
}
}
echo 'Empty Cart';
if (isset($_GET['rc']) && isset($_SESSION['cart'])) {
$rem = $_GET['rc'];
$ses = $_SESSION['cart'];
foreach ($_SESSION['cart'] as $cartItem) {
if ($cartItem["code"] == $rem) {
unset($ses[$rem]);
}
}
/*if (($key = array_search($rem, $ses)) !== false) {
unset($ses[$key]);
}*/
var_dump($ses);
}
if (isset($_GET['ac']) == 'empty' && isset($_SESSION['cart'])) {
unset($_SESSION['cart']);
}
for now the adding new products is working fine with me but the issue
comes when I am trying to remove one item from the caret it return back and noting seems to happened, and the item still there in the cart
you are unsetting $ses variable not $_SESSION...
Please have a look at the updated code, you dont even need to use a forloop, you can just unset the variable as I done below
if (isset($_GET['rc']) && isset($_SESSION['cart']))
{
$rem = $_GET['rc'];
if(isset($_SESSION['cart'][$rem]))
{
unset($_SESSION['cart'][$rem]);
}
}
let me know if this help you
EDIT
Please update your buy product function to below one.. you are using auto increament key for array.. it should be the primary key (here your product code)
if (isset($_POST['buy'])) {
//header("Location:?pid=18&pl=" . $pl);
if (isset($_POST['buy'])) {
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if (($pn = $res->fetch_object()) !== null) {
$proCode = rand(1, 100);
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
$item['code'] = $proCode;
$_SESSION['cart'][$proCode] = $item;
}
}
}
}
try to change your deleting cycle to this:
foreach ($_SESSION['cart'] as $key=>$cartItem) {
if ($cartItem["code"] == $rem) {
unset($_SESSION['cart'][$key]);
}
I am trying to crate a very simple shopping cart
I am using a session and array to add the items to an array and save the array into session and display the items in this session properly like
item 1 name -- price
item 2 name -- price
and then take the total to my payment method.
here is the code I am using.
print_r($_SESSION['cart']);
if (isset($_POST['buy'])) {
//header("Location:?pid=18&pl=" . $pl);
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if ($pn = $res->fetch_object()) {
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
if (isset($_SESSION['cart'])) {
$_SESSION['cart'] = $item;
}
}
}
}
Issues
( ! ) Notice: Undefined index: cart
EDIT
this is what I end with
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $c) {
echo $c['name'] . '<br />';
echo $c['price'] . '<br />';
echo 'Remove item<br />';
}
}
if (isset($_POST['buy'])) {
//header("Location:?pid=18&pl=" . $pl);
if (isset($_POST['buy'])) {
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if (($pn = $res->fetch_object()) !== null) {
$proCode = range(1, 100);
shuffle($proCode);
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
$item['code'] = $proCode;
$_SESSION['cart'][] = $item;
}
}
}
}
if (isset($_GET['rc']) && isset($_SESSION['cart'])) {
$rem = $_GET['rc'];
if (($key = array_search($rem, $_SESSION['cart'])) !== false) {
unset($_SESSION['cart'][$key]);
}
}
but still the delete not working
As I can see, you're trying to print a variable that isn't set. Plus, with this code:
if (isset($_SESSION['cart'])) {
$_SESSION['cart'] = $item;
}
You'll never be able to add an item to your cart. My way to do this is the following:
if (isset($_POST['buy'])) {
$getData = $db->prepare('SELECT * FROM plans WHERE id=?');
$getData->bind_param('i', $pl);
if ($getData->execute()) {
$res = $getData->get_result();
if ($pn = $res->fetch_object()) {
$item['name'] = $pn->plan_name;
$item['price'] = $pn->price_dollar;
$_SESSION['cart'][] = $item;
}
}
}
This way, even if the cart key isn't set, it will be set anyway. By the same time, it will permit you to have multiple items in your cart.
EDIT: The next thing to do, if you want to show your items is the following:
foreach ($_SESSION['cart'] as $k => $item) {
echo "item $item->id $item->plan_name -- $item->price_dollar";
}
Below is my code:
$id = $_GET['id'];
$qty = $_GET['qty'];
$product_id=$_GET['product_id'];
This is how I receive in the browser
http://example.com/shopping_cart.php?id=17,18&qty=4,5&product_id=3
$_SESSION['test'][]= array('product_id'=>$product_id,array('id'=>$id,'qty'=>$qty));
//print_r($_SESSION['test']);
foreach($_SESSION['test'] as $item=>$value)
{
echo "Main Array ID=". $item;
echo "<br/>";
foreach($value as $v=>$v1)
{
if(is_array($v1))
{
echo "Sub Array ID=". $v;
echo "<br/>";
echo "size id=". $v1['id'];
echo "<br/>";
echo "Quantity=". $v1['qty'];
echo "<br/>";
}
}
}
Output:
Main Array ID=0
Sub Array ID=0
size id=12,13
Quantity=1,2
Main Array ID=1
Sub Array ID=0
size id=17,18
Quantity=4,5
Since size_id and quantity are in implode form, I mean they have a comma ',' in between the value. I need to explode them and use foreach to display one by one.
I mean something like this:
$size_id1=explode(',',$v1['qty']);
foreach($size_id1 as $size_id2)
{
echo $size_id2;
}
$qty1=explode(',',$v1['qty']);
foreach($qty1 as $qty2)
{
echo $qty2;
}
What I need is, I want to display matching size_id and qty. For example, instead of displaying:
size_id 1
size_id 2
Qty 1
Qty 2
It should display:
Size_id 1 Qty 1
Size_id 2 Qty 2
How can I achieve this?
$ids = $_GET['id']
$qtys = $_GET['qty']
$product_id = $_GET['product_id'];
$tmp_result = array();
$ids = explode(',',$ids );
$i = 0;
foreach($ids as $id)
{
$tmp_result[$i]['id'] = $id;
$i++;
}
$i = 0;
$qtys =explode(',',$qtys );
foreach($qtys as $qty)
{
$tmp_result[$i]['qty'] = $qty;
$i++;
}
$_SESSION['tmp_results'][$product_id] = $tmp_result;
$temp_arr = array();
$id_str = '17,18';
$qty_str = '4,5';
foreach(array_combine(explode(',', $id_str), explode(',', $qty_str)) as $k => $v) {
$temp_arr[]['id'] = $k;
$temp_arr[]['qty'] = $v;
}
diffrence betwen 2 implode fetch from database
<?php
$select_tbl=mysql_query("select * from user_reg where uid='". $_SESSION['user1']."'");
while($fetch=mysql_fetch_object($select_tbl))
{
$r=$fetch->specialised;
$i=explode(",",$r);
$length = count($i);
for ($x=0; $x<$length; $x++)
{
echo $i[$x]; }
}?><tbody>
<?php
mysql_connect("localhost","root","");
mysql_select_db("freelancer");
$query=mysql_query("select * from post_proj where status = 1 and payment = '' ") or die(mysql_error());
$j = 1;
while($result=mysql_fetch_array($query))
{
if($result['uid'] == "")
{$d2 = $result['proj_skill'];
$pantry_food1 = explode(",",$d2);
$count_total1 = count($pantry_food1);
for ($counter=0; $counter<$count_total1; $counter++){
$line1 = each ($pantry_food1);
// echo $pantry_food1[$counter];
} $rrt = array_intersect($i,$pantry_food1);
I'm developing a system for a client that creates a csv of packing labels which is sent to a printer. The client has six different items. Customers order products in bulk from my client. Two items (product A and product B) share the same packing line. In order to make packing more efficient my client wants to alternate between packing product A and packing product B first.
For example, if John, Sally, and James all ordered both products, the system needs to write John's orders to the csv starting with product A, Sally's orders starting with product B, and James' orders starting with product A again.
I've pasted my non-working code below, but this is really screwing with my head and I'm having a really tough time with it.
foreach($orders as $order) {
$name = null;
$phone = null;
$account = DAO_ContactPerson::get($order->account_id);
$delivery = false;
if($account->is_agency) {
$name = $order->getAttribute('name');
$phone = $order->getAttribute('phone');
} else {
$name = sprintf("%s %s",
$account->getPrimaryAddress()->first_name,
$account->getPrimaryAddress()->last_name
);
$phone = $account->phone;
}
$name = trim($name);
$phone = trim($phone);
$items = $order->getItems();
if($order->getAttribute('delivery')) {
$type = 'deliveries';
$destination = 'Delivery';
$address = sprintf("%s %s %s",
$order->getAttribute('delivery_address.line1'),
$order->getAttribute('delivery_address.line2'),
$order->getAttribute('delivery_address.postal')
);
} else {
$type = 'pickups';
$agency = DAO_ContactPerson::getAgency($order->getAttribute('pickup'));
$destination = $agency->name;
// Override account id so orders are grouped by agency
$order->account_id = $agency->id;
$address = null;
}
// var_dump($order->id);
// Init account array
if(!isset($rows[$type][$order->account_id]))
$rows[$type][$order->account_id] = array('combined' => array(), 'separate' => array());
foreach($items as $item) {
$packing = 'separated';
if($item->product_id == 3 || $item->product_id == 4)
$packing = 'combined';
if(!isset($rows[$type][$order->account_id][$packing][$item->product_id]))
$rows[$type][$order->account_id][$packing][$item->product_id] = array();
$i = 0;
while($i < $item->quantity) {
$rows[$type][$order->account_id][$packing][$item->product_id][] = array(
'number' => $order->id,
'destination' => $destination,
'size' => $item->product_id,
'name' => $name,
'address' => $address,
'phone' => $phone
);
$i++;
}
}
// if($order->id == 176) {
// var_dump($rows[$type][$order->account_id][$packing]);
// }
}
$this->weight = 1;
$pickups = count($rows['pickups']);
for($i = 0; $i < $pickups; $i++) {
$account =& $rows['pickups'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$deliveries = count($rows['deliveries']);
for($i = 0; $i < $deliveries; $i++) {
$account =& $rows['deliveries'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$rows['output'] = $rows['pickups'];
array_push($rows['output'], $rows['deliveries']);
$output = '';
foreach($rows['output'] as $account_id => $boxes) {
if(!empty($boxes['output'])) {
foreach($boxes['output'] as $labels) {
if(!empty($labels)) {
foreach($labels as $label) {
$output .= implode(',', $label) . "<br>";
}
}
}
}
}
The _compareBoxes method looks like this:
private function _compareBoxes($a, $b) {
if($a['size'] == $b['size']) {
return 0;
}
if($this->weight == 1) {
// Medium first, then Large
return ($a['size'] < $b['size']) ? -1 : 1;
}
if($this->weight == -1) {
// Large first, then Medium
return ($a['size'] > $b['size']) ? -1 : 1;
}
}
I am trying to build an array of cart items that has a mix of a la carte items and package deals. I want to pull the products from the packages and enter the products into my order table. Below is what I have. It pulls the data, but will only add the last record of the inner array (package products) to the outer array. The a la carte items are fine.
$sql = "SELECT id, item_id, package
FROM cart WHERE user_id = $userId";
$result = dbQuery($sql);
$arrCartContent = array();
while ($row = dbFetchAssoc($result)) {
if ($row['package'] == 1) {
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
$numItem = count($arrProductData);
if ($numItem > 0) {
for ($i = 0; $i < $numItem; $i++) {
extract($arrProductData[$i]);
$row['product_id'] = $product_id;
$row['description'] = $pack_product_name;
}
}
} else {
$itemDetails = fetchProductDetails($row['item_id']);
$row['product_id'] = $row['item_id'];
$row['description'] = $itemDetails['name'];
}
$arrCartContent[] = $row;
}
if(!empty($arrCartContent)) {
foreach ($arrCartContent as $cartData) {
$product_id = $cartData['product_id'];
$description = $cartData['description'];
$sqlInsert = "INSERT INTO shop_order_x_product
(order_id, product_id, description)
VALUES
($orderId, $product_id, '$description')";
$resultInsert = dbQuery($sqlInsert) or die('Cannot add order products: ' . mysql_error());
}
}
You mixed it up a bit, your general approach is fine, maybe streamlining it a bit will make this a breeze and prevent you from overwriting the $row variable inside the loop:
$arrCartContent = array();
while ($row = dbFetchAssoc($result))
{
if ($row['package'] == 1)
{
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
foreach($arrProductData as $productData)
{
$new = array();
$new['product_id'] = $productData['product_id'];
$new['description'] = $productData['description'];
$arrCartContent[] = $new;
}
}
else
{
$itemDetails = fetchProductDetails($row['item_id']);
$new = array();
$new['product_id'] = $row['item_id'];
$new['description'] = $itemDetails['name'];
$arrCartContent[] = $new;
}
}
You're overwriting the $row array elements with each iteration. Try...
if ($row['package'] == 1) {
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
$numItem = count($arrProductData);
if ($numItem > 0) {
for ($i = 0; $i < $numItem; $i++) {
extract($arrProductData[$i]);
$row['product_id'] = $product_id;
$row['description'] = $pack_product_name;
$arrCartContent[] = $row;
}
}
} else {
$itemDetails = fetchProductDetails($row['item_id']);
$row['product_id'] = $row['item_id'];
$row['description'] = $itemDetails['name'];
$arrCartContent[] = $row;
}