Shopping cart weird interaction that I don't understand - php

I am creating a shopping cart with an array in php. The array first array is to store the ShoeId and the quantity which was POST from the previous page. It is stored in the $_SESSION['cart'].
I then compared the cart with a new array called $cleanArray to find duplicates and replace it by increasing the quantity. However I came into an issue that I don't understand and after spending countless of hours I decided to ask here.
//creating a final cart
$cleanArray = array();
//to prevent sql injection
$shoeID = $conn->real_escape_string($_POST['shoeID']);
$quantity = $conn->real_escape_string($_POST['quantity']);
// $_SESSION['cart'] = array();
If I leave the $_SESSION['cart'] = array(); in the code the cart will keep clearing itself.
However, If i add it, refresh my webpage and then remove that code again. My shopping cart would work as intended.
//checking if Cart Array exist and if ShoeID and quantity has been selected
if (isset($_POST['shoeID']) && ($_POST['quantity'])){
if(isset($_SESSION['cart'])){
echo "shoeID: $shoeID";
echo "<br>";
echo "Quantity: $quantity";
echo "<br>";
$_SESSION['cart'][] = array('shoeId' => $shoeID, 'quantity' => $quantity);
$cartArray = $_SESSION['cart'];
//find for duplicate shoeId and then increase the quantity.
foreach($cartArray as $item){
if(isset($cleanArray[$item['shoeId']])){
$cleanArray[$item['shoeId']]['quantity'] += $item['quantity'];
} else {
$cleanArray[$item['shoeId']] = $item;
}
}
} else {
echo "Cart Is Empty!";
}
$cleanArray = array_values($cleanArray);
print_r($cleanArray);
$_SESSION['finalCart'] = $cleanArray;
Any forms of suggestion would be helpful as I am new to php and I am trying to understand more about it. thank you!

Related

Limit the max number of cart items in $_SESSION

This is my php script for adding item to shopping cart:
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
switch($_GET['action']) {
case 'add':
$productByCode = $db_handle->runQuery("SELECT item, brand, price, catalog FROM products WHERE catalog='".$_GET['catalog']."'");
$itemArray = array($productByCode[0][‘catalog']=>array(
'item'=>$productByCode[0]['item'],
'brand'=>$productByCode[0]['brand'],
'price'=>$productByCode[0]['price'],
'catalog'=>$productByCode[0]['catalog']));
if(!empty($_SESSION['cart_item'])) {
if(!in_array($productByCode[0]['catalog'],($_SESSION['cart_item']))) {
$_SESSION['cart_item'] += $itemArray;
}
}
else {
$_SESSION['cart_item'] = $itemArray;
}
I want to limit the max number of cart item to 20, that means when the cart items has reach 20, even if the user click the add button with new item not found in the $_session, the new item will not be added anymore. Is there any way to do this? Pls help. Thanks in advance.
You have a couple of issues. in_array won't work the way you have it because it compared the array value not the key. So use array_keys to test for that. You could also use isset($_SESSION['cart_item'][$productByCode[0]['catalog']) instead of in_array(array_keys(...)) to get the same effect.
I updated the add code to use array_merge so it is clear what is happening with the new cart items.
Also you should parameterize your sql query to avoid SQL injection issues (I didn't correct this in your code)
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
switch($_GET['action']) {
case 'add':
$productByCode = $db_handle->runQuery("SELECT item, brand, price, catalog FROM products WHERE catalog='".$_GET['catalog']."'");
$itemArray = array($productByCode[0][‘catalog']=>array(
'item'=>$productByCode[0]['item'],
'brand'=>$productByCode[0]['brand'],
'price'=>$productByCode[0]['price'],
'catalog'=>$productByCode[0]['catalog']));
if(!empty($_SESSION['cart_item'])) {
if(count($_SESSION['cart_item']) < 20 && !in_array($productByCode[0]['catalog'],array_keys($_SESSION['cart_item']))) {
$_SESSION['cart_item'] = array_merge($_SESSION['cart_item'], $itemArray);
}
}
else {
$_SESSION['cart_item'] = $itemArray;
}

How to create stock management in PHP

I want to create stock management system in my website using php. It sounds like 'balancing' stock in database with amount of items that will purchased. If the item's amount is more than the item's stock, the website should displaying an alert. So, the amount of item cannot be more than the item's stock in database.
Here's my code :
$stock = array();
foreach ($_SESSION['cart'] as $k => $v) {
$sql = mysql_query("SELECT book_stock FROM book WHERE book_title='$k'");
while ($row = mysql_fetch_assoc($sql)) {
$stock[] = $row['book_stock'];
}
if ($stock < $v) {
echo "Stock less than the amount";
}
else {
echo "Stock sufficient";
}
}
The $k variable store the item's name in the session cart. And the $v variable store the item's amount in the transaction.
The item's amount will be increased if the visitor click 'Increase' button.
But if i increase the item's amount, the if and else logic like "isn't working". No matter how much the item's amount is added, the if and else logic keep print "Stock Sufficient".
Can anyone help me to solve this? Thanks in advance :)
Edit :
The variable in original code is in indonesian. So when i'm typing this post, i'm editing the variables too here. So if the variables is different, i'm just forget to rename it. So i edit the script again :)
$sql = mysql_query("SELECT book_stock FROM ooku WHERE book_title='$k'");
I am assuming that your query will return unique book (single book) stock detail, you have to use $stok instead of $stok[] Array
while ($row = mysql_fetch_assoc($sql)) {
$stok = $row['book_stock'];
}

How to exclude data from an array?

On a product page I want to show 4 other products selected randomly, but never the product that is already being displayed. The product id of the displayed one is $_product->getId() and all the products go into a $result[] array like this:
foreach($collection as $product){
$result[]=$product->getId();
}
I'm using $need = array_rand($result, 4); to get the ids of the 4 random products, but it might include the id of the product on display. How do I exclude $_product->getId() from the $need[] array? Thank you.
Don't put id of the product you don't want to show into $result:
$currentProductId = $_product->getId();
foreach ($collection as $product) {
if ($product->getId() != $currentProductId) $result[] = $product->getId();
}
Is it acceptable to just not put the current product ID in the array?
foreach($collection as $product) {
if( $product != $_product) $result[] = $product->getId();
}
You might generate your random numbers first, like so:
$rands = array();
while ($monkey == false){
$banana = rand(0,4);
if (in_array($banana, $rands) && $banana != $_product->getId()){ $rands[] = $banana; }
if (sizeOf($rands) == 4){
$monkey = true;
}
}
Then you could pipe them through your product grabber. Obviously, you'd need to figure out the bounds for rand yourself but you know more about your app than I do. Picking your numbers first is much cheaper computationally than pulling records and THEN checking to make sure that they're unique.
Of course, if this is database-backed, you could solve it much more elegantly by writing a new query.
If you use the product id as the index $result[] in result, you can remove the current product from the $result array with unset() before making the call to array_rand() like so:
foreach($collection as $product){
$result[$product->getId()] = $product->getId();
}
unset($result[$_product->getId()]);
$need = array_rand($result, 4);
This approach saves you from having to use the values in $need to look up the product id in your $result[] array, since the values in $need will be your product ids.

How do I add new items to a cart and iterate through them to display using php?

I am trying to pass data from a product page into a shopping cart page using an array. There are multiple attributes that the viewcart.php will receive from the previous page (price, link, title, and retailer). I’d like to save them all using an array. For each additional item a customer adds to the shopping cart, I’m trying to get a counter variable ($i) to increment an array $_SESSION[‘cart’][$i][‘attribute’]. How do I do this?
I’m not sure this is the right way to add new products to the cart. In the end, I’d like a way to be able to display all the products in the cart using a for loop. This is the start I have so far on the shopping cart script:
<?php
// The shopping cart needs sessions, so start one
session_start();
#$link = $_GET['link'];
$price = $_GET['price'];
$title = $_GET['title'];
$retailer = $_GET['retailer'];
if($link) {
//new item selected
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
$_SESSION['items'] = 0;
$_SESSION['total_price'] ='0.00';
}
if(isset($_SESSION['cart'][$link])) {
$_SESSION['cart'][$link]++;
} else {
$_SESSION['cart'][$link] = 1;
}
}
if(($_SESSION['cart']) && (array_count_values($_SESSION['cart']))) {
echo " in your cart and we're working to display them";
}
else {
echo "<p>There are no items in your cart</p><hr/>";
}
?>
This is the for loop that I’m thinking I could use. I’m looking for some way to display all the items in the array.
for ($x=0; $x<=$i; $i++)
{
echo "The price is " . $_SESSION['cart'][$x][price] . " Retailer is " . $_SESSION['cart'][$x] [retailer] . "<br>";
}
The easiest way to do this is by creating a temp_cart table in your database.. in which you should store the items that user adds to their cart.. Then on checkout page.. you can simply display them using select query. In that way.. it will be easier for you to allow the user to edit their cart on viewcart.php page.
You could:
Have another session variable with the counter and increment it each add?
Or
$i= Count($_SESSION['cart'])+1;
Or
Don't specify an index at all:
$tmp["cart"]["retailer"] = "123";
Etc etc..
$_SESSION['cart'][] = $tmp["cart"];
I would be storing the products into a database if I was you..
I don't like the way you are doing this. Session management is very simple for shopping carts. Keep your session as lite as possible. Storing price in the session is very bad way, as it can be easily manipulated.
Here is a simple example of what you can use.
if(isset($_SESSION['items'][$_GET['item_id']])) {
$_SESSION['items'][$_GET['item_id']]++; //add one to the total count
} else {
$_SESSION['items'][$_GET['item_id']] = 1; //If added for the first time
}
Now process it
foreach($_SESSION['items'] as $id => $count) {
echo $id; // product id
echo $count; // product count
}
P.S: Remember to sanitize the input. I have omitted that

add item into add cart

I'm trying to add product into add cart. Please tell me what is the best way.
My mess code is.
if(isset($_SESSION['id'])) {
echo "IF part";
$_SESSION['id'] = $_SESSION['id'] + $_SESSION['id'];
$k = $_SESSION['id'];
// store session data
$_SESSION[$k]['product_name']=$_REQUEST['product_name_value'];
$_SESSION[$k]['product_price']=$_REQUEST['product_price_value'];
$_SESSION[$k]['shop_name']=$_REQUEST['shop_name_value'];
$_SESSION[$k]['Quantity']=$_REQUEST['selquantity'];
$_SESSION[$k]['color']=$_REQUEST['txtcolor'];
$_SESSION[$k]['Size']=$_REQUEST['selsize'];
$_SESSION[$k]['Product_Type']=$_REQUEST['selproducttype'];
$_SESSION[$k]['Remarks']=$_REQUEST['Remarks'];
$_SESSION[$k]['final_price']=$_REQUEST['final_price_value'];
$_SESSION[$k]['txturl']=$_REQUEST['txturl'];
}else {
echo "else part";
$_SESSION['id'] = 1;
// store session data
$_SESSION[$k]['product_name']=$_REQUEST['product_name_value'];
$_SESSION[$k]['product_price']=$_REQUEST['product_price_value'];
$_SESSION[$k]['shop_name']=$_REQUEST['shop_name_value'];
$_SESSION[$k]['Quantity']=$_REQUEST['selquantity'];
$_SESSION[$k]['color']=$_REQUEST['txtcolor'];
$_SESSION[$k]['Size']=$_REQUEST['selsize'];
$_SESSION[$k]['Product_Type']=$_REQUEST['selproducttype'];
$_SESSION[$k]['Remarks']=$_REQUEST['Remarks'];
$_SESSION[$k]['final_price']=$_REQUEST['final_price_value'];
$_SESSION[$k]['txturl']=$_REQUEST['txturl'];
}
I'm trying to add these product details into array.
thanks
Don't repeat yourself ;) means if you have two lines of code that are identical check if you really need to write it twice!
if(!isset($_SESSION['cart'])) {
// create cart
$_SESSION['cart'] = array();
}
// create item
$item = array();
// fill item
$item['product_name']=$_REQUEST['product_name_value'];
$item['product_price']=$_REQUEST['product_price_value'];
$item['shop_name']=$_REQUEST['shop_name_value'];
$item['Quantity']=$_REQUEST['selquantity'];
$item['color']=$_REQUEST['txtcolor'];
$item['Size']=$_REQUEST['selsize'];
$item['Product_Type']=$_REQUEST['selproducttype'];
$item['Remarks']=$_REQUEST['Remarks'];
$item['final_price']=$_REQUEST['final_price_value'];
$item['txturl']=$_REQUEST['txturl'];
// add item to cart
$_SESSION['cart'][] = $item;
You should first do some factorization on your code with creating a function to add the data to the $_SESSION.
Then, it's impossible to give you an answer, there's no "best way", there's only a way that suits your need and you're the only one which can find it.
See below.
$sql = "INSERT INTO ordertb (time, cust_id, prod_id, quantity, pmt_mode, city, delivery_state,amtval) VALUES ( '".date("Y-m-d H:i:s")."','".$idval1."','".$item["product_code"]."','".$item["qty"]."','".$_SESSION['spmt1']."','".$_SESSION['scity']."','1','".$item["subtotal"]."')";

Categories