Shopping cart output - php

I have an online store. A products page that allows the user to view a product and add it to the basket. It is added to the basket by clicking "Add to basket" button.
When a user clicks "add to basket", the script redirects them to the basket page and adds the product to the basket.
My question is, how do I print the basket output on the "basket.php" page? How do I pass the session content into variables to be printed?
Thank you.
"products" table in the database:
id int(11), name varchar(255), price int(11)
product.php
...
<form id="basket" name="basket" method="post" action="basket.php">
<input type="hidden" name="p_id" value="<?php echo $id; ?>"/>
<input type="submit" name="submit" value="Add to basket"/>
</form>
...
basket.php
<?php
//add product to cart with product ID passed from previous script
if (isset($_POST["p_id"]))
{
$p_id = $_POST["p_id"];
$q = mysql_query("SELECT * FROM products WHERE id='$p_id'");
$is = mysql_fetch_row($q); $is = $is[0];
$result = "";
while($row = mysql_fetch_array($q)) {
$name = $row["name"];
$price = $row["price"];
$info = $row["info"];
}
$result .= $name .= $price .= $info;
//$_SESSION['p_id'] contains product IDs
//$_SESSION['counts'] contains item quantities
// ($_SESSION['counts'][$i] corresponds to $_SESSION['p_id'][$i])
//$_SESSION['p_id'][$i] == 0 means $i-element is 'empty' (does not refer to any product)
if (!isset($_SESSION["p_id"]))
{
$_SESSION["p_id"] = array();
$_SESSION["counts"] = array();
}
//check for current product in visitor's shopping cart content
$i=0;
while ($i<count($_SESSION["p_id"]) && $_SESSION["p_id"][$i] != $_POST["p_id"]) $i++;
if ($i < count($_SESSION["p_id"])) //increase current product's item quantity
{
$_SESSION["counts"][$i]++;
}
else //no such product in the cart - add it
{
$_SESSION["p_id"][] = $_POST["p_id"];
$_SESSION["counts"][] = 1;
}
}
?>
<div>
<?php echo $result ?>
</div>

create ajax request on button click, to basket.php with GET veriable todo='add_to_basket', witch you will handle in basket.php
HTML of you add product button or link
Your count of product, you will get by Jquery, just type your count html selectors with IDs
<select id="count_<?=$YOUR_PRODUCT_ID?>"></select>
function add_to_basket(product_id){
var product = {};
product['prod_id'] = product_id;
//here you get count of current product
product['count'] = $("count_"+product_id).val();
$.ajax({
type: "GET",
url: "your_domain/basket.php?todo=add_to_basket",
data: "product",
success:function () {
}
});
}
on your basket.php you handle this request like that
if ($GET['todo'] == "add_to_basket"){
// here you add your data(witch comes from ajax) to SESSION
$_SESSION['basket'] [$GET['prod_id']] = $GET['count'];
return true;
}
then when user click on basket image you redirect him to basket page, in wich you display all product in session
<?foreach ($_SESSION['basket'] as $item){?>
// here you get product info by product id from your database and product count from $_SESSION print it to view , price wille be count*price
<?}?>

Related

Add to cart / Remove from cart without refreshing the page

I am new at some things and I need help about my store page.
For each item you wanna add to the cart or remove from the cart, the page refreshs and it is really annoying if you wanna buy several items.
I have read that I could use AJAX, I have read a lot of methods and nothing worked for me.
What do I need to do in order to make it work?
These are my add / remove:
<form action="" method="post">
<input type="hidden" name="item_id" value="{sid}">
<input type="hidden" name="parent" value="{parent_category}">
<input type="submit" name="atc" value="Añadir" class="sub-link">
</form>
<form action="" method="post">
<input type="hidden" name="item_id" value="{cid}">
<input type="hidden" name="parent" value="{parent_category}">
<input type="submit" name="rfc" value="Remover" class="sub-link">
</form>
And this is the function handling the submit:
function add_to_cart() {
global $db, $db_data, $db_acc, $login;
if (!empty($_POST['atc']) || !empty($_POST['rfc'])
&& isset($_GET['page']) && isset($_GET['data'])
&& $_GET['page'] == "store_shop") {
$data = $_GET['data'];
$pos = strpos($data, "-");
if ($pos == TRUE) {
$ndt = explode("-", $data);
$d1 = clean($ndt[0]);
$d2 = clean($ndt[1]);
if ($d1 == FALSE) {
$d1 = 0;
}
} else {
$d1 = 0;
$d2 = 0;
}
$sqli = $db->query("SELECT id, rname, char_db FROM $db_data.realms WHERE id='$d1'");
$numi = $db->num($sqli);
$geti = $db->get($sqli);
$cdb = $geti['char_db'];
$sqla = $db->query("SELECT id, username FROM $db_acc.account WHERE username='$login'");
$geta = $db->get($sqla);
$acid = $geta['id'];
if ($numi == 1) {
$sqlc = $db->query("SELECT guid, account, name FROM $cdb.characters WHERE account='$acid' AND guid='$d2'");
$numc = $db->num($sqlc);
$getc = $db->get($sqlc);
if ($numc == 1) {
$item = clean($_POST['item_id']);
$parent = clean($_POST['parent']);
if (!empty($_POST['atc'])) {
$sqll = $db->query("INSERT INTO $db_data.cart (`realm`, `account`, `character`, `item`, `parent`) VALUES ('$d1', '$acid', '$d2', '$item', '$parent')");
} else if (!empty($_POST['rfc'])) {
$sqll = $db->query("DELETE FROM $db_data.cart WHERE id='$item'");
}
header("Location: ?page=store_shop&data={$data}");
} else {
header("Location: ?page=store_shop&data={$data}");
}
} else {
header("Location: ?page=store_shop&data={$data}");
}
}
}
Edit: I think I am missing some details:
After clicking "add" ("Añadir" in Spanish) o "remove" ("Remover" in Spanish), the page reloads and the item is added to the cart div.
When I try the solutions I have read in stackoverflow or in other website, most of them does not work for my store and the only thing I can get is to prevent the page from reloading but the cart does not update.
Maybe should I use a iframe in the cart div?
I am still reading about ajax but I can not get it by myself.
Try this out
Remove the submit button and call the function Add to cart and same for Remove from cart using onclick="addtocart()" in anchor tag
function addtocart(){
get 'sid' and 'parent' value from anchor tag using jquery
$.ajax({
type: 'POST',
url: '/cart/add.php',
data:{ 'sid':sid, 'parent':parent }
success : function(data) { alert('success'); }
});
}
This is a form when generally causes a page load unless the default onsubmit action is overridden and the override function causes a stopPropagation on the event object. AJAX requires JS in which an XMLHttpRequest object is created (or ActiveX for IE) and communicates with server without a refresh by default ( although it can be done programatically). Then your server could return JSON for example or some indicator as to whether the call was successful and erroneous and the client side can handle it accordingly

How do I display a summary of items in a cart from a $_SESSION onto another page

I need my cart page to show a summary "line item" like view of all vending machines purchased on my vend page with $_SESSION['cart']
Here is my code which allows me to add multiple items to the cart: (Vend Page)
session_start();
//Check if $_SESSION['cart] exists
if (!isset($_SESSION['cart'])) {
//initiate cart as empty array
$_SESSION['cart'] = [];
}
if (isset($_POST['add'])) {
//add product id to session cart
$_SESSION['cart'][$_POST['add']] =1;
}
else if (isset($_POST['remove'])) {
//remove product id from session cart
unset($_SESSION['cart'][$_POST['remove']]);
}
I just need a way to display the items I "Add to Cart" on the Vend Page" to display in a list onto another page "Cart page". Ive made an image to show how it should be displayed: HERE
in your cart page add this -
session_start();
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $name => $price){
echo $name . " - " . $price;
}
}else{
// optional(if cart is empty it will redirect to another page)
header("location:products.php");
}
something like
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $name => $price){
echo $name . " - " . $price;
}
}

how to create a button using html and php

I have created two php codes one is for add product to cart and the other php code is to remove product from cart.However I was just wondering will I need to create a button using html near the product table so that users are able to add or remove the product from their basket.
<?php
session_start();
// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
/*
* check if the 'cart' session array was created
* if it is NOT, create the 'cart' session array
*/
if(!isset($_SESSION['cart_items'])){
$_SESSION['cart_items'] = array();
}
// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
}
// else, add the item to the array
else{
$_SESSION['cart_items'][$id]=$name;
// redirect to product list and tell the user it was added to cart
header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}
?>
You provide just php code. If you want use it on frontend - you need to create link, form, ajax.
link
<a href="yourcode.php?id=ID&name=NAME&quantity=QUANTITY">
form
<form action="yourcode.php">
<input type="hidden" name="id" value="ID">
<input type="hidden" name="name" value="NAME">
<input type="text" name="quantity" value="1">
<input type="submit" value="Add or Delete">
</form>
ajax (jquery). For ajax you need to return json response as {success: true, message: "Product has been added to the cart"} also you can use $.ajax instead $.get.
$.get('yourcode.php', {id: 'ID', name: 'NAME', quantity: 'QUANTITY'},
function (response) {
if (response.success && response.message) {
alert(response.message);
} else {
alert('Something went wrong');
}
}
);

PHP Notice: Undefined offset: 36

I have a simple php checkout but when adding the product to basket i get the following error:
PHP Notice: Undefined offset: 36 in C:\inetpub\wwwroot\shopping\cart.php on line 76
If i then refresh the page or go back to add another product it displays a product fine, it seems to be when adding to first product to the cart we get this error. any help would be much appreciated as all the answers i have tried have not worked.
<?php
// connect to the database
include("databasedrop.php");
?>
<div class="post">
<h2>Shopping Basket<span class="title-bottom"> </span></h2>
</div>
<!-- End Post -->
<?php
if (empty($_GET['id'])) {
$_GET['id'] = "";
}
$ProductID = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
switch ($action) { //decide what to do
case "add":
$_SESSION['cart'][$ProductID] ++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$ProductID] --; //remove one from the quantity of the product with id $product_id
if ($_SESSION['cart'][$ProductID] == 0)
unset($_SESSION['cart'][$ProductID]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if (empty($_SESSION['cart'])) {
$_SESSION['cart'] = "";
}
if ($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" padding=\"3\" width=\"40%\">"; //format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach ($_SESSION['cart'] as $ProductID => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
if ($stmt = $conn->prepare("SELECT * FROM products WHERE ProductID=?")) {
$stmt->bind_param("i", $ProductID);
$stmt->execute();
$stmt->bind_result($ProductID, $Title, $Description, $Price, $Stock, $Image, $Category, $Status);
$stmt->fetch();
// show the form
}
$total = "";
$line_cost = $Price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">$Title</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">$line_cost</td>";
echo "</tr>";
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\">Total</td>";
echo "<td align=\"right\">$total</td>";
echo "</tr>";
//show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
} else {
//otherwise tell the user they have no items in their cart
echo "You have no items in your shopping cart.";
}
?>
Shot in the dark, but only solution I can see.
Do you ever create the $_SESSION['cart']-array?
Try this:
switch ($action) {
case "add":
if (!isset($_SESSION['cart'][$ProductID])) {
$_SESSION['cart'][$ProductID] = 1;
}
else {
$_SESSION['cart'][$ProductID]++;
}
break;

Saving a value from a drop down to a variable PHP

I am trying to save the value selected in the date drop down box to a variable '$AvailabilityID' which is retrieved on the next page. The drop down box is populated from the MYSQL table bs_availability. From what I've read I need to use Javascript but really no idea how to do it.
Any help appreciated.
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$results = $mysqli->query("SELECT SessionType, SessionName, SessionCost, SessionID FROM bs_session
GROUP BY SessionName ORDER BY SessionType ASC;");
if ($results) {
//output results from database
while($obj = $results->fetch_object())
{
$availabilityresults = $mysqli->query("SELECT * From bs_availability WHERE sessionID = ".$obj->SessionID.";");
echo '<tr>';
echo '<form method="post" action="cart_update.php">';
echo '<td>'.$obj->SessionName.'</td>';
echo '<td>'.$obj->SessionType.'</td>';
echo '<td><select name="date">';
//While loop to populate drop down with table data
while($objdate = $availabilityresults->fetch_object())
{
echo '<option value ="'.$objdate->AvailabilityID.'">'.$objdate->Date.'</option>';
}
echo '</select>';
echo '</td>';
echo '<td>Price '.$currency.$obj->SessionCost.' <button class="add_to_cart">Add To Cart</button></td>';
echo '</tr>';
echo '<input type="hidden" name="SessionID" value="'.$obj->SessionID.'" />';
echo '<input type="hidden" name="AvailabilityID" value="'.$objdate->AvailabilityID.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
}
?>
EDIT: This code is the cart_update.php. So when Add to Basket is pressed this script is run using the $SessionID from the selected item but I also need the AvailabiltyID of the chosen date so that I can run the right query to add the right date to the basket.
<?php
session_start(); //start session
include_once("config.php"); //include config file
//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
$return_url = base64_decode($_GET["return_url"]); //return url
session_destroy();
header('Location:'.$return_url);
}
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$SessionID = filter_var($_POST["SessionID"], FILTER_SANITIZE_STRING); //product code
$AvailabilityID = filter_var($_POST["AvailabilityID"], FILTER_SANITIZE_STRING); //product code
$product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
$return_url = base64_decode($_POST["return_url"]); //return url
//limit quantity for single product
if($product_qty > 10){
die('<div align="center">This demo does not allowed more than 10 quantity!<br />Back To Products.</div>');
}
console.log($availabilityID);
//MySqli query - get details of item from db using product code
$results = $mysqli->query("SELECT SessionName, SessionCost FROM bs_session WHERE SessionID=$SessionID LIMIT 1");
//$results = $mysqli->query("SELECT bs_session.SessionName, bs_availability.Date, bs_session.SessionCost FROM bs_availability INNER JOIN bs_session ON bs_session.SessionID=bs_availability.SessionID WHERE bs_availability.AvailabilityID=$AvailabilityID LIMIT 1");
$obj = $results->fetch_object();
if ($results) { //we have the product info
//prepare array for the session variable
$new_product = array(array('name'=>$obj->SessionName, 'code'=>$SessionID, 'date'=>$obj->Date, 'price'=>$obj->SessionCost));
if(isset($_SESSION["products"])) //if we have the session
{
$found = false; //set found item to false
foreach ($_SESSION["products"] as $cart_itm) //loop through session array
{
if($cart_itm["code"] == $SessionID){ //the item exist in array
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'date'=>$cart_itm["date"], 'price'=>$cart_itm["price"]);
$found = true;
}else{
//item doesn't exist in the list, just retrive old info and prepare array for session var
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'date'=>$cart_itm["date"], 'price'=>$cart_itm["price"]);
}
}
if($found == false) //we didn't find item in array
{
//add new user item in array
$_SESSION["products"] = array_merge($product, $new_product);
}else{
//found user item in array list, and increased the quantity
$_SESSION["products"] = $product;
}
}else{
//create a new session var if does not exist
$_SESSION["products"] = $new_product;
}
}
//redirect back to original page
header('Location:'.$return_url);
}
//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
$SessionID = $_GET["removep"]; //get the product code to remove
$return_url = base64_decode($_GET["return_url"]); //get return url
foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
{
if($cart_itm["code"]!=$SessionID){ //item does,t exist in the list
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
}
//create a new product list for cart
$_SESSION["products"] = $product;
}
//redirect back to original page
header('Location:'.$return_url);
}
In PHP, this is done through the POST array on your cart_update.php page:
if (isset($_POST['date'])){
$AvailabilityID = $_POST['date'];
}
You could also change the existing add to cart button to give it a name that will appear in the POST array:
echo '<td>Price '.$currency.$obj->SessionCost.' <button class="add_to_cart" name="add_to_cart">Add To Cart</button></td>';
This is often used as a check on the processing page, with an if block around all of the processing code.
if (isset($_POST['add_to_cart'])){
//all processing code here
}
Just use the POST Variable $_POST['date'] which holds the selected option value.

Categories