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.
Related
I have been trying to find this out for weeks and I'm not seeing it. how do I store the quantities alongside the products which the user has added to their cart? I need to have this because I need the users to be able to update the quantity from the items.
already tried a few things such as creating an array and trying to store quantity in a array but it only remembers the last number that the user put in. This is because its a post request. and to fix that I need to store quantities alongs side the products in cart. and thats where I'm stuck.
I tried:
if(isset($_POST['quantity'])){
$quantity = $_POST['quantity'];
$_SESSION['basket'][] = $quantity;
}
but this put the last item a lot in the shopping cart
like this:
then I tried:
if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
$_SESSION['quantity'] = $_POST['quantity'];
// //$qty = $_SESSION["qty"] + 1;
if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
if ($_POST['broodnaam'] == $row['broodnaam']){
$quantity = $_POST['quantity'];
// //array_push($_SESSION['qty'], $quantity);
// // var_dump($_SESSION['qty']);
}
}
}
but this only updates the last updated item from the cart.
I really don't know how to fix this can someone help me
code: ( part of the code as I don't feel like I need to share the styling and sessions_start() part
<?php
$broodjes = $_GET['broodjes_ID'];
if (isset($_SESSION['basket'])){
if( in_array( $broodjes ,$_SESSION['basket']) )
{
}else{
$_SESSION['basket'][] = $broodjes;
}
}else{
$_SESSION['basket'][]= $broodjes;
}
$sumtotal = 0;
foreach($_SESSION['basket'] as $key => $value){
//echo "Key = $key; value = $value; <br>";
$sql = "SELECT broodjes_ID, broodnaam, prijs, voorraad FROM broodjes WHERE broodjes_ID=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $value);
$stmt->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()){
//session for quantity
$_SESSION["qty"] = array();
echo '<div class="cart-items">';
echo '<div class="cart-row">';
echo '<div class="cart-item cart-column">';
echo $row['broodnaam'];
echo '</div>';
echo '<div class="cart-item cart-column">';
echo '€ ' . $row['prijs'];
echo '</div>';
//quantity
echo '<div class="cart-item cart-column">';
echo '<form method="POST" action="">';
echo '<div class="col-xs-4">';
echo '<input type="hidden" name="broodnaam" id="broodnaam" value="' . $row['broodnaam'] . '">';
echo '<input type="number" name="quantity" id="quantity" class="form-control input-sm" value="1" min="1" max="'.$row['voorraad'].'">';
echo '</div>';
echo '</form>';
echo '</div>';
//ik moet de quantity ergens in opslaan , denk in db, om zo nog de voorraad te verminderen
if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
$_SESSION['quantity'] = $_POST['quantity'];
// //$qty = $_SESSION["qty"] + 1;
if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
if ($_POST['broodnaam'] == $row['broodnaam']){
$quantity = $_POST['quantity'];
////array_push($_SESSION['qty'], $quantity);
//// var_dump($_SESSION['qty']);
}
}
}
echo '<div class="cart-item cart-column">';
$rowtotaal = $row['prijs'] * $quantity;
$sumtotal += $rowtotaal;
echo $rowtotaal;
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?> <br />
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> € <?php echo $sumtotal;?></span>
</div>
<br/>
what you need is a unique column in your products' table.
generally, the unique column is either id or alias.
Then when you need to add an item to the cart:
// supposing you have the product id in the $pid variable and quantity in the $qty variable
$_SESSION['cart'][$pid] = $qty;
Then when you need to access it you can easily loop through the session's cart.
foreach($_SESSION['cart'] as $product => $qty) {
// do something with the product and quantity.
}
how this works is, it creates an item in the cart array with the index of the product's unique column value and the item's value would be the quantity of the product added to the cart.
Update the new quantity ($_POST['quantity']) by adding the old one ($_SESSION['qty']).like this -
if (isset($_POST['quantity'])){
if (isset($_POST['broodnaam'])){
if ($_POST['broodnaam'] == $row['broodnaam']){
$_SESSION['qty'] = $_POST['quantity'] + $_SESSION['qty'];
}
}
}
Before i start to explain in details, let me show the screenshot of what I want the result to be.
What I want to achieve is quite simple, display all the items that are added to cart and calculate the total for each individual product. However, looks like my Multidimensional Arrays and array_key_exists didn't do it correctly and that's why didn't get the result i want.
As you can see from the screenshot, if the same product being added to cart, the quantity didn't plus 1 and it just display below the previous item.
products.php -> nothing special, just to display all the products in database
<?php
require 'config.php';
$q = mysqli_query( $db->conn(), "SELECT * FROM product" );
if( mysqli_num_rows($q) > 0 ) { // Check if there are results
while( $row = mysqli_fetch_assoc($q)){
//echo "id: " . $row["id"]. " <br>- Name: " . $row["product_name"]. " " . $row["product_price"]. "";
echo '<p>ID->'.$row['id'].' | '.$row['product_name'].' | $'.$row['product_price'].'
| Add to Cart</p>';
}
}
?>
cart.php
<?php
session_start();
if(isset($_GET['id'])){
require 'config.php';
$id=$_GET['id'];
$q = mysqli_query( $db->conn(), "SELECT * FROM product where id='$id'" );
$row = mysqli_fetch_assoc($q);
$product_name=$row['product_name'];
$product_price=$row['product_price'];
$quantity=1;
$total=$quantity*$product_price;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'][]=[]; //Create session 1st time
}
if(isset($_SESSION['cart'])){
if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
}
echo '<table border="1" cellpadding="10">';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
foreach ($_SESSION['cart'] as $key => $row) { // list out all the items in Multi array
echo "<tr>";
foreach ($row as $key2 => $val) {
echo "<th>";
echo $_SESSION['cart'][$key][$key2]." ";
echo "</th>";
}
echo "</tr>";
}
echo '</table>';
}
}
?>
May i know which part of the coding went wrong?
Revisiting the Code in your cart.php File would be of great Benefit here. Below is what you may want to consider:
<?php
$product_name = $row['product_name'];
$product_price = $row['product_price'];
$quantity = 1;
$total = $quantity*$product_price;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
if(isset($_SESSION['cart'])){
// DOES THE PRODUCT ID EXIST IN THE $_SESSION['cart'] COLLECTION?
// IF IT DOESN'T WE CREATE IT AND LET IT BE...
if(!array_key_exists( $id, $_SESSION['cart'] )){
$_SESSION['cart'][$id] = [$id, $product_name, $product_price, $quantity, $total];
}else {
// IF IT ALREADY EXIST; WE SIMPLY GET THE OLD VALUES & APPEND NEW ONE TO IT...
// HERE YOU ASKED FOR array_key_exits($id, $_SESSION['cart']);
// WHICH MEANS $id MUST BE THE KEY HERE
// HERE IS WHERE THE PROBLEM IS....
$storedPrice = $_SESSION['cart'][$id][2];
$storedQuantity = $_SESSION['cart'][$id][3];
$storedTotal = $_SESSION['cart'][$id][4];
$_SESSION['cart'][$id] = [
$id,
$product_name,
$product_price,
$storedQuantity+1,
round( ($storedQuantity+1)*($product_price), 2),
];
}
echo '<table border="1" cellpadding="10">';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
foreach ($_SESSION['cart'] as $key => $row) {
echo "<tr>";
foreach ($row as $key2 => $val) {
echo "<th>";
echo $_SESSION['cart'][$key][$key2]." ";
echo "</th>";
}
echo "</tr>";
}
echo '</table>';
}
You have made the mistake, when add a Cart and Update Cart:
So change the following line:
if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
}
Into
$find = false;
if(!empty($_SESSION['cart'])){
foreach($_SESSION['cart'] as $key=>$cart){
if(isset($cart[0]) && $cart[0] == $id){ //Already exists in Cart
$_SESSION['cart'][$key][3] = $_SESSION['cart'][$key][3] + 1; //$_SESSION['cart'][$key][3] is quantity
$_SESSION['cart'][$key][4] = $_SESSION['cart'][$key][3] * $_SESSION['cart'][$key][2] ; //$_SESSION['cart'][$key][4] update the total
$find = true;
}
}
}
if(!$find){ //Not in the Cart
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}
Note: Before check, clear the cookies
With the foreach loop I'm trying to connect to my database and display in a list the products that have been added to the cart. Each product has a product ID which is correctly working and being stored in the session variable through the cart.php. I can't figure out how to connect to the database to display the information gathered about the product added - I also tried doing var_dump $SESSION['cart'] and its prints out null even after I use the "Add" button in cart.php.
<div class="row">
<h4>Shopping Cart</h4>
<?php
foreach($_SESSION['cart'] as $proid => $proq) {
// $proid is product id and $proq is quantity
// use $proid to select the product detail from database
}
?>
</div>
<!--Below is my cart.php page-->
<?php
session_start();
$productID = $_GET['product'];
$action = $_GET['action'];
switch($action) {
case "add":
$_SESSION['cart'][$productID]++;
break;
case "remove":
$_SESSION['cart'][$productID]--;
if($_SESSION['cart'][$productID] == 0) unset($_SESSION['cart'][$productID]);
break;
case "empty":
unset($_SESSION['cart']);
break;
}
header("Location: browse.php");
?>
For product view (index.php)
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$results = $mysqli->query("SELECT * FROM products");
if ($results) {
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
echo '<div class="product">';
echo '<form method="post" action="update_cart.php">';
echo '<div class="product-content">';
echo '<div class="product-info">';
echo 'Price '.$currency.$obj->price.' | ';
echo 'Qty <input type="text" name="product_qty" value="1" size="3" />';
echo '<button class="add_to_cart">Add To Cart</button>';
echo '</div></div>';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
}
?>
For Update cart (Update_cart.php)
//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$product_code = filter_var($_POST["product_code"], 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
ySqli query - get details of item from db using product code
$results = $mysqli->query("SELECT product_name,price FROM products WHERE product_code='$product_code' 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->product_name, 'code'=>$product_code, 'qty'=>$product_qty, 'price'=>$obj->price));
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"] == $product_code){ //the item exist in array
$product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$product_qty, '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"], 'qty'=>$cart_itm["qty"], '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);
}
For View Cart(View_cart.php)
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="checkout.php">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj->price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->product_desc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '</form>';
}
?>
Need remove product from cart
use this in update cart (update_cart.php)
//remove item from shopping cart
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["products"]))
{
$product_code = $_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"]!=$product_code){ //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);
}
Create database connection
<?php
$db_username = 'root';//username
$db_password = '';//password
$db_name = '';//database name
$db_host = 'localhost';//your host
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);
?>
> Important Use this in every page
<?php
error_reporting(0);
include("config.php");
session_start();
?>
Based on your explanation, you are trying to retrieve data from a session value to populate a database query.
However, when your for loop executes, you have not de-serialized the session data into memory (so it cannot be accessed and you get null values).
You need to start the session before your for loop:
session_start();
foreach($_SESSION['cart'] as $proid => $proq) {
Please see more information in the php manual
Also, you can configure PHP to start the session automatically if desired (see more details in the manual linked above), however keep in mind that this will have a performance impact even on pages which do not rely on session data.
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;
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
<?}?>