Show Cart Session Item - php

I have successful to display cart and add to cart those thing.
but i wanted to show the cart item list on the payment page to let the user
to confirm their item quantity and prices. how to display them those data in the
session. here is how my coding. Below code is cart.php
i wanted to display item to payment.php
switch($action)
{
case "add":
if (isset($_SESSION['cart'][$proid]))
$_SESSION['cart'][$proid]++;
else
$_SESSION['cart'][$proid]=1;
break;
case "remove":
if (isset($_SESSION['cart'][$proid]))
{
$_SESSION['cart'][$proid]--;
if ($_SESSION['cart'][$proid]==0)
unset($_SESSION['cart'][$proid]);
}
else
$_SESSION['cart'][$proid]=1;
break;
case "empty" :
unset($_SESSION['cart']);
break;
}
if (isset($_SESSION['cart']))
{
$total = 0;
foreach($_SESSION['cart'] as $proid =>$x)
{
$results = mysqli_query($con,"Select * from product where Product_ID = $proid");
$myrow = mysqli_fetch_array($results);
$productname = $myrow['Product_Name'];
$productprice= $myrow['Product_Price'];
$line_cost = $productprice * $x;
$total=$total+$line_cost;
?>
<li class = "cartlist">
<?php echo '<img src="data:image/jpeg;base64,' . base64_encode($myrow['Product_Pic']) . '" width="196" height="120">';?>
<p><span style = "font-weight: bold; font-size: 1.2em;">
<?php echo $productname ?>
</span></br />RM <?php echo $productprice;?>
</br />Quantity : <?php echo $x ?></br><a href='cart.php?proid=<?php echo $proid;?>&action=add'>Add </a> <a href ='cart.php?proid=<?php echo $proid;?>&action=remove'> Reduce </a></br>RM<?php echo $line_cost; ?> <br/>
</p> </li>
<?php
}
?>

Related

how to store cart session for logged in user using php

Hello i am creating a simple web app, that users can log in and purchase food stuffs. i have used a tutorial i got online link to tutorial
to implement the ordering aspect of this web app,
now i have implemented a user syatem so that users have to sign in to make an order.
my problem is i noticed that the same cart information is shown to multiple users when logged in, which is wrong. every user should have their own different cart information based on what they might have added up.
so i am asking how can i tie cart information to logged in users or each users.
this is my code snippet
product.php
<head>
<script>
function showEditBox(editobj,id) {
$('#frmAdd').hide();
$(editobj).prop('disabled','true');
var currentMessage = $("#message_" + id + " .message-content").html();
var editMarkUp = '<textarea rows="5" cols="80" id="txtmessage_'+id+'">'+currentMessage+'</textarea><button name="ok" onClick="callCrudAction(\'edit\','+id+')">Save</button><button name="cancel" onClick="cancelEdit(\''+currentMessage+'\','+id+')">Cancel</button>';
$("#message_" + id + " .message-content").html(editMarkUp);
}
function cancelEdit(message,id) {
$("#message_" + id + " .message-content").html(message);
$('#frmAdd').show();
}
function cartAction(action,product_code) {
var queryString = "";
if(action != "") {
switch(action) {
case "add":
queryString = 'action='+action+'&code='+ product_code+'&quantity='+$("#qty_"+product_code).val();
break;
case "remove":
queryString = 'action='+action+'&code='+ product_code;
break;
case "empty":
queryString = 'action='+action;
break;
}
}
jQuery.ajax({
url: "ajax_action.php",
data:queryString,
type: "POST",
success:function(data){
$("#cart-item").html(data);
if(action != "") {
switch(action) {
case "add":
$("#add_"+product_code).hide();
$("#added_"+product_code).show();
break;
case "remove":
$("#add_"+product_code).show();
$("#added_"+product_code).hide();
break;
case "empty":
$(".btnAddAction").show();
$(".btnAdded").hide();
break;
}
}
},
error:function (){}
});
}
</script>
</head>
<body>
<div id="product-grid">
<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="product-item">
<form id="frmCart">
<img width="100" src="<?php echo $product_array[$key]["image"]; ?>">
<div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
<div class="product-price"><?php echo "MUR".$product_array[$key]["price"]; ?></div>
<div><input type="range" name="quantity" id="qty_<?php echo $product_array[$key]["code"]; ?>" value="1" min="1" max="10">
<?php
$in_session = "0";
if(!empty($_SESSION["cart_item"])) {
$session_code_array = array_keys($_SESSION["cart_item"]);
if(in_array($product_array[$key]["code"],$session_code_array)) {
$in_session = "1";
}
}
?>
<input data-theme="a" type="button" data-icon="cutlery" value="Add to cart" class="btnAddAction cart-action" onClick = "cartAction('add','<?php echo $product_array[$key]["code"]; ?>');cartAction('add','<?php echo $product_array[$key]["code"]; ?>')" />
</div>
</form>
</div>
<?php
}
}
?>
</div>
</div><div class="clear-float"></div>
<div id="shopping-cart">
</div>
<script>
$(document).ready(function () {
cartAction('','');
})
</script>
</div>
</div>
</body>
and my ajax_action.php
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["action"])) {
switch($_POST["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_POST["code"] . "'");
$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["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($_POST["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
?>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<img width="50" src="<?php
$img = $item["name"];
$sql = "select * FROM tblproduct where name = '$img'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['image'];
}
?>" /><input type="hidden" name="itemname[]" id="text-basic" value="<?php echo $item["name"]; ?>"><input type="hidden" name="itemprice[]" id="text-basic" value="<?php echo $item["price"]; ?>"><strong><?php echo $item["name"]; ?></strong><br />
<?php echo "MUR".$item["price"]; ?> x <?php echo $item["quantity"]; ?>
<a style="color:#F30" href="#" onClick="cartAction('remove','<?php echo $item["code"]; ?>')" class="btnRemoveAction cart-action">Remove Item</a><br /><br />
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<br /><br /><strong>Total:</strong> <?php echo "MUR".$item_total; ?><input type="hidden" name="amount" id="text-basic" value="<?php echo "N".$item_total; ?>">
<?php
}
?>
i have tried to change the $_SESSION["cart_item"] to something that would always change $_SESSION["MM_Username"], my thinking was that it would probably create the cart variable name based on who was logged in, but that approach didnt seem to go well,
can some one please help here

Cart update with ajax and php

I'm learning how can i use ajax, jquery and php to update a cart. I found this code and i'm trying to adapt it, but without success. The problem is that i can't add any item to the cart and after a search on google still don't understand where is the problem.
<script>
$(document).ready(function(){
$(".form-item").submit(function(e){
var form_data = $(this).serialize();
var button_content = $(this).find('button[type=submit]');
button_content.html('Adding...'); //Loading button text
$.ajax({ //make ajax request to cart_process.php
url: "../../cart_process.php",
type: "POST",
dataType:"json", //expect json value from server
data: form_data
}).done(function(data){ //on Ajax success
$("#cart-info").html(data.items); //total items in cart-info element
button_content.html('Add to Cart'); //reset button text to original text
alert("Item added to Cart!"); //alert user
if($(".shopping-cart-box").css("display") == "block"){ //if cart box is still visible
$(".cart-box").trigger( "click" ); //trigger click to update the cart box.
}
})
e.preventDefault();
});
//Show Items in Cart
$( ".cart-box").click(function(e) { //when user clicks on cart box
e.preventDefault();
$(".shopping-cart-box").fadeIn(); //display cart box
$("#shopping-cart-results").html('<img src="images/ajax-loader.gif">'); //show loading image
$("#shopping-cart-results" ).load( "../../cart_process.php", {"load_cart":"1"}); //Make ajax request using jQuery Load() & update results
});
//Close Cart
$( ".close-shopping-cart-box").click(function(e){ //user click on cart box close link
e.preventDefault();
$(".shopping-cart-box").fadeOut(); //close cart-box
});
//Remove items from cart
$("#shopping-cart-results").on('click', 'a.remove-item', function(e) {
e.preventDefault();
var pcode = $(this).attr("data-code"); //get product code
$(this).parent().fadeOut(); //remove item element from box
$.getJSON( "../../cart_process.php", {"remove_code":pcode} , function(data){ //get Item count from Server
$("#cart-info").html(data.items); //update Item count in cart- info
$(".cart-box").trigger( "click" ); //trigger click on cart-box to update the items list
});
});
});
prodotto.php Here i have the description of the product, the form to select quantity and the button to add the product to the cart
<?php
require_once("../inc/config.php");
require_once(ROOT_PATH . "inc/database.php");
require_once(ROOT_PATH . "prodotti/prod.php");
require_once(ROOT_PATH . "login/user.php");
sec_session_start();
if(isset($_GET['sku'])) {
$sku = intval($_GET['sku']);
$prodotto = get_product_single($sku);
}
if(empty($prodotto)){
header("Location:" . BASE_URL);
exit();
}
include(ROOT_PATH . "inc/header.php");
include(ROOT_PATH . "inc/side-menu.php");
try{
$results = $db->prepare("SELECT * from prodotti WHERE sku = ?");
$results->bindParam(1,$sku);
$results->execute();
$prodotto = $results->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Nessun prodotto da visualizzare con queste caratteristiche";
die();
}
?>
<div id="content" class="large-8 columns round-all" role="main" itemscope itemtype="http://schema.org/LocalBusiness" style="background-color:#eee;padding-right:1em;">
<div class="row" style="padding-right:1em;">
<?php
$categoria = get_category($prodotto['categoria']);
?>
<nav class="breadcrumbs" role="menubar" aria-label="breadcrumbs" itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
<li role="menuitem"><span itemprop=”title”><?php echo $categoria['nome'];?></span></li>
<li role="menuitem" class="current"><span itemprop=”title”><?php echo $prodotto['nome'];?></span></li>
</nav>
<a href="#" class="cart-box" id="cart-info" title="View Cart">
<?php
if(isset($_SESSION["products"])){
echo count($_SESSION["products"]);
}else{
echo 0;
}
?>
<div class="shopping-cart-box">
<a href="#" class="close-shopping-cart-box" >Close</a>
<h3>Your Shopping Cart</h3>
<div id="shopping-cart-results">
</div>
</div>
<?php
echo '<li role="menuitem" style="list-style-type:none;">
<div class="large-12 columns" style="background-color:#fff;" itemscope itemtype="http://schema.org/Product">
<div class="small-1 medium-2 large-4 columns" style="border:10px #eee solid">
<span itemprop ="image"><img src="' . BASE_URL . 'img/profumo-hugo-boss.jpg";/></span>
</div>
<div class="small-1 medium-4 large-8 columns" >
<span itemprop="name"><h3>'.$prodotto['nome'].'</h3></span>
<h6>Codice: ' . $prodotto['sku'] . '</h6>
<span itemprop="price"><h6>Prezzo: <span style="color:red;font-weight:bold;";>' . $prodotto['prezzo'] . '<span itemprop="priceCurrency">€</span></span></h6></span>
<span itemprop="description"><p>'.$prodotto['descrizione'].'</p></span>';?>
<form class="form-item">
<div class="small-1 medium-2 large-4">
<label for="quantita">Quantità</label>
<select name="quantita" id="quantita">
<option value="1">1 </option>
<option value="2">2 </option>
<option value="3">3 </option>
<option value="4">4 </option>
<option value="5">5 </option>
<option value="6">6 </option>
<option value="7">7 </option>
<option value="8">8 </option>
<option value="9">9 </option>
<option value="10">10 </option>
</select>
</div>
<div class="small-1 medium-2 large-4">
<input type="hidden" name="sku" value="<?php echo $prodotto['sku'];?>"/>
<input type="hidden" name="id_sessione" value="<?php echo $_SESSION['id'];?>"/>
<input type="submit" value="Aggiungi al carrello" class="button" name="submit">
</div>
</form>
</div>
</div>
</li>
</div>
</div>
</div>
</div>
Cart_process.php
include_once("../inc/config.php");
sec_session_start();
############# add products to session #########################
if(isset($_POST["sku"]))
{
foreach($_POST as $key => $value){
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array
}
//we need to get product name and price from database.
$statement = $db->prepare("SELECT nome, sku FROM prodotti WHERE sku=? LIMIT 1");
$statement->bindParam(1, $new_product['sku']);
$statement->execute();
$prodotto = $statement-fetch(PDO::FETCH_ASSOC);
while($prodotto){
$new_product["nome"] = $prodotto['nome']; //fetch product name from database
$new_product["sku"] = $prodotto['sku']; //fetch product sku from database
if(isset($_SESSION["products"])){ //if session var already exist
if(isset($_SESSION["products"][$new_product['sku']])) //check item exist in products array
{
unset($_SESSION["products"][$new_product['sku']]); //unset old item
}
}
$_SESSION["products"][$new_product['sku']] = $new_product; //update products with new item array
}
$total_items = count($_SESSION["products"]); //count total items
die(json_encode(array('items'=>$total_items))); //output json
}
################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ //if we have session variable
$cart_box = '<ul class="cart-products-loaded">';
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
//set variables to use them in HTML content below
$product_name = $product["nome"];
/*$product_price = $product["product_price"];
*/$product_code = $product["sku"];/*
$product_qty = $product["product_qty"];
$product_color = $product["product_color"];
$product_size = $product["product_size"];
*/
$cart_box .= "<li> $product_name ×</li>";
//$subtotal = ($product_price * $product_qty);
//$total = ($total + $subtotal);
}
$cart_box .= "</ul>";
//$cart_box .= '<div class="cart-products-total">Total : '.$currency.sprintf("%01.2f",$total).' <u>Check-out</u></div>';
die($cart_box); //exit and output content
}else{
die("Your Cart is empty"); //we have empty cart
}
}
################# remove item from shopping cart ################
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove
if(isset($_SESSION["products"][$product_code]))
{
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
die(json_encode(array('items'=>$total_items)));
}
Moving forward from our discussion in the comments, I will be posting a functional behavior of the code with a sample data from database since you wanted it to be dynamic.
As this was for learning purpose I've had used prepared statements with some msql_. (both in different files) Please note that msql_
is deprecated and I urge not to use it.
Before starting, I assume you have all the required files downloaded and saved in the correct path and used either method (filesystem/storing directly to database) for the images, I have however used the filesystem behavior. Now, there are three tables used from the database:
1) category table with columns as follow:
cat_id
cat_name
2) item table which has the columns as follow:
item_id
item_name
item_quantity
item_size
cat_id (FK from category table)
item_color
3) products_list table with following columns:
id (AI, PK)
product_name
product_desc
product_code
product_image
item_id (FK from item table)
product_price
product_discount
Now, Starting with the very first page.
index.php
<?php
session_start(); //start session
include("config.php"); //include config file
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$(".form-item").submit(function(e){
var form_data = $(this).serialize();
var button_content = $(this).find('button[type=submit]');
button_content.html('Adding...');
$.ajax({
url: "cart_process.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
$("#cart-info").html(data.items);
button_content.html('Add to Cart');
alert("Item added to Cart!");
if($(".shopping-cart-box").css("display") == "block"){
$(".cart-box").trigger( "click" );
}
})
e.preventDefault();
});
//Show Items in Cart
$( ".cart-box").click(function(e) {
e.preventDefault();
$(".shopping-cart-box").fadeIn();
$("#shopping-cart-results").html('<img src="images/ajax-loader.gif">');
$("#shopping-cart-results" ).load( "cart_process.php", {"load_cart":"1"});
});
//Close Cart
$( ".close-shopping-cart-box").click(function(e){
e.preventDefault();
$(".shopping-cart-box").fadeOut();
});
//Remove items from cart
$("#shopping-cart-results").on('click', 'a.remove-item', function(e) {
e.preventDefault();
var pcode = $(this).attr("data-code");
$(this).parent().fadeOut();
$.getJSON( "cart_process.php", {"remove_code":pcode} , function(data){
$("#cart-info").html(data.items);
$(".cart-box").trigger( "click" );
});
});
});
</script>
<?php
$que = "SELECT * FROM category";
$run = mysql_query($que);
$j = 0;
while($row = mysql_fetch_array($run))
{
$cat_idd[$j] = $row['cat_id'];
$cat_namee[$j] = $row['cat_name'];
$j++;
}
for($i = 0; $i < count($cat_idd); $i++)
{
$que2 = "SELECT * FROM item WHERE cat_id = '$cat_idd[$i]' ";
$result = mysql_query($que2);
$run = mysql_num_rows($result);
echo"<table>";
echo"<th id = 'hidden'></th>";
echo"<tr>";
echo"<td id = 'side' width = '110'>";
echo " "."<a href='index.php?id=$cat_idd[$i]' style = 'text-decoration: none;' >".$cat_namee[$i]." (".$run.")</a><br><br>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
require('config.php');
if(isset($_GET['id']))
{
$cat_id = $_GET['id'];
$que = "SELECT * FROM item WHERE cat_id = '$cat_id'";
$run = mysql_query($que);
?>
<form class="form-item">
<a href="#" class="cart-box" id="cart-info" title="View Cart">
<?php
if(isset($_SESSION["products"])){
echo count($_SESSION["products"]);
}else{
echo 0;
}
?>
</a>
<div class="shopping-cart-box">
<a href="#" class="close-shopping-cart-box" >Close</a>
<h3>Your Shopping Cart</h3>
<div id="shopping-cart-results">
</div>
</div>
<?php
while($row = mysql_fetch_array($run))
{
$i_id = $row['item_id'];
$i_name = $row['item_name'];
$i_quantity = $row['item_quantity'];
$i_size = $row['item_size'];
$i_color = $row['item_color'];
?>
<?php
$query3 = "SELECT product_name, product_price, product_desc, product_code, product_image, product_discount FROM products_list WHERE item_id = '$i_id' ";
$run3 = mysql_query($query3);
while($row3 = mysql_fetch_array($run3)) {
?>
<ul class="products-wrp">
<li>
<form class="form-item">
<h4><?php echo $row3['product_name']; ?></h4>
<div><img src="images/<?php echo $row3['product_image']; ?>"height = "150" width = "180"></div>
<?php echo "Availabe Quantity: " . $i_quantity . "<br>"; ?>
<?php
if($row3['product_discount'] == 0)
{
echo "Rs. " . $row3['product_price'];
}
else
{
echo "NOW ". $row3['product_discount'] . "% OFF!";
echo '<div>Rs. <span style = "text-decoration: line-through;">'.$row3['product_price'].'</span></div>';
$discount = ((($row3['product_discount'])/100) * $row3['product_price']);
$f_price = ($row3['product_price'] - $discount);
echo "Rs. ". $f_price . ".00" ;
}
?>
<div class="item-box">
<div>
Color :
<?php
$arr = $row["item_color"];
$exp = explode("," , $arr);
echo "<select name='product_color'>";
foreach($exp as $key=>$val) {
echo "<option value='" . $val . "'>" . $val . "</option>";
}
echo "</select>";
?>
<!-- <select name="product_color">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Orange">Orange</option>
</select>
-->
</div>
<div>
Qty :
<input type = "number" name = "product_qty" min = "1" max = "<?php echo $i_quantity; ?>"
value = "1" title = "Please Enter the Numbers Below Available Quantity Only.">
<!--
<select name="product_qty">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
-->
<div>
Size :
<?php
$arr = $row["item_size"];
$exp = explode("," , $arr);
echo "<select name='product_size'>";
foreach($exp as $key=>$val) {
echo "<option value='" . $val . "'>" . $val . "</option>";
}
echo "</select>";
?>
<input name="product_code" type="hidden" value="<?php echo $row3['product_code']; ?>">
<button type="submit">Add to Cart</button>
</div>
</form>
</li>
</ul>
</div>
<?php } } }?>
</body>
</html>
Now the very first thing as you click on "Add to Cart" happens is the ajax request to cart_process.php with a json value expected to be returned.
cart_process.php
<?php
session_start();
$db_username = 'root';
$db_password = '';
$db_name = 'yourdbnamehere';
$db_host = 'localhost';
$currency = 'Rs. ';
$shipping_cost = 500;
$taxes = array(
'VAT' => 12,
'Service Tax' => 5,
'Other Tax' => 10
);
$mysqli_conn = new mysqli($db_host, $db_username, $db_password,$db_name);
if ($mysqli_conn->connect_error) {
die('Error : ('. $mysqli_conn->connect_errno .') '. $mysqli_conn->connect_error);
// add products to session
if(isset($_POST["product_code"]))
{
foreach($_POST as $key => $value){
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
$statement = $mysqli_conn->prepare("SELECT product_name, product_price, product_discount FROM products_list WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $product_price, $product_discount);
while($statement->fetch()){
$new_product["product_name"] = $product_name;
$new_product["product_price"] = $product_price;
$new_product["product_discount"] = $product_discount;
if($product_discount == 0)
{
$product_price = $product_price;
}
else
{
$discount = (($product_discount/100) * $product_price);
$product_price = $product_price - $discount;
}
if(isset($_SESSION["products"])){
if(isset($_SESSION["products"][$new_product['product_code']]))
{
unset($_SESSION["products"][$new_product['product_code']]);
}
$_SESSION["products"][$new_product['product_code']] = $new_product;
}
$total_items = count($_SESSION["products"]);
die(json_encode(array('items'=>$total_items)));
}
// list products in cart
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
$cart_box = '<ul class="cart-products-loaded">';
$total = 0;
foreach($_SESSION["products"] as $product){
$product_name = $product["product_name"];
$product_price = $product["product_price"];
$product_code = $product["product_code"];
$product_qty = $product["product_qty"];
$product_color = $product["product_color"];
$product_size = $product["product_size"];
$product_discount = $product["product_discount"];
if($product_discount == 0)
{
$product_price = $product_price;
}
else
{
$discount = (($product_discount/100) * $product_price);
$product_price = $product_price - $discount;
}
$cart_box .= "<li> $product_name (Qty : $product_qty | $product_color | $product_size ) — $currency ".sprintf("%01.2f", ($product_price * $product_qty)). " ×</li>";
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$cart_box .= "</ul>";
$cart_box .= '<div class="cart-products-total">Total : '.$currency.sprintf("%01.2f",$total).' <u>Check-out</u></div>';
die($cart_box);
}else{
die("Your Cart is empty");
}
}
// remove item from shopping cart
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING);
if(isset($_SESSION["products"][$product_code]))
{
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
die(json_encode(array('items'=>$total_items)));
}
Now comes the part when you click on "Check-out" in your add-to-cart box. It takes you to another page (the last one in our case) where you can see all the products that you have bought.
view_cart.php
<?php
session_start();
include("config.inc.php"); //one written above in cart_process.php
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Review Your Cart Before Buying</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<body>
<?php
if(isset($_COOKIE['user']))
{
$last = $_COOKIE['user'];
echo 'SignOut';
echo "Logged in: ". $last . "<br><br>";
echo '<h3 style="text-align:center">Review Your Cart Before Buying</h3>';
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
$total = 0;
$list_tax = '';
$cart_box = '<ul class="view-cart">';
foreach($_SESSION["products"] as $product){
$product_name = $product["product_name"];
$product_qty = $product["product_qty"];
$product_price = $product["product_price"];
$product_code = $product["product_code"];
$product_color = $product["product_color"];
$product_size = $product["product_size"];
$product_discount = $product["product_discount"];
if($product_discount == 0)
{
$product_price = $product_price;
}
else
{
$discount = (($product_discount/100) * $product_price);
$product_price = $product_price - $discount;
}
$item_price = sprintf("%01.2f",($product_price * $product_qty)); // price x qty = total item price
$cart_box .= "<li> $product_code – $product_name (Qty : $product_qty | $product_color | $product_size) <span> $currency$item_price </span></li>";
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$grand_total = $total + $shipping_cost;
foreach($taxes as $key => $value){
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount;
}
foreach($tax_item as $key => $value){
$list_tax .= $key. ' '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
$cart_box .= "<li class=\"view-cart-total\">$shipping_cost $list_tax <hr>Payable Amount : $currency ".sprintf("%01.2f", $grand_total)."</li>";
$cart_box .= "</ul>";
echo $cart_box;
echo 'Confirm Purchase';
}else{
echo "Your Cart is empty";
}
}
else
if(!isset($_COOKIE['user']))
{
echo "You must be logged in to purchase!<br>";
echo 'Login';
}
?>
</body>
</html>
I have run and checked all the processing before posting this here, So it should help you understand the exact behavior and the way to move along.
Cheers.

how to get cart values in codeigniter for paypal payment gateway

I am stuck on integrating paypal payment gateway on codeigniter
I am using the current library
https://github.com/romaldyminaya/ci_paypal
As the library contains only static values of the items , but i need to get the items that are coming from my cart, how can i get them to the $this->paypal->add('T-shirt',2.99,6);
my controller function:
public function do_purchase(){
$config['business'] = 'babar.seller#gmail.com';
$config['cpp_header_image'] = ''; //Image header url [750 pixels wide by 90 pixels high]
$config['return'] = 'http://localhost/final-project/index.php/mysite/modify_payment';
$config['cancel_return'] = 'http://final-project/mysite/canceled.php';
$config['notify_url'] = 'process_payment.php'; //IPN Post
$config['production'] = FALSE; //Its false by default and will use sandbox
$config["invoice"] = random_string('numeric',8); //The invoice id
$this->load->library('paypal',$config);
#$this->paypal->add(<name>,<price>,<quantity>[Default 1],<code>[Optional]);
$this->paypal->add('T-shirt',2.99,6); //First item
$this->paypal->add('Pants',40); //Second item
$this->paypal->add('Blowse',10,10,'B-199-26'); //Third item with code
$this->paypal->pay(); //Proccess the payment
}
public function modify_payment(){
$received_data = print_r($this->input->post(),TRUE);
echo "<pre>".$received_data."<pre>";
$this->load->view('mysite/modify_payment',$received_data);
}
public function cart()
{
$cart = $this->cart->contents();
//print_r($cart);
//die;
//$data['user_id']=$this->mainmodel->get_user_i($user_id);
$this->load->view('mysite/cart');
$this->load->view('mysite/include/footer');
}
cart view :
<?php $i = 1; ?>
<?php foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden($i.'[rowid]', $items['rowid']); ?>
<tr>
<td> <input name="qty[<?php echo $items['rowid'];?>]" id="qty" type="text" value="<?php echo $items['qty']?>" class="input" />
</td>
<td>
<?php echo $items['name']; ?>
<?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>
<p>
<?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br />
<?php endforeach; ?>
</p>
<?php endif; ?>
function add($item_name = '',$item_amount = NULL,$item_qty = NULL,$item_number = NULL){
$this->config['item_name_'.$this->item] = $item_name;
$this->config['amount_'.$this->item] = $item_amount;
$this->config['quantity_'.$this->item] = $item_qty;
$this->config['item_number_'.$this->item] = $item_number;
$this->item++;
}
What i did is had a paypal library class that handled the addition and just simply hard coded inn some products

first product not added in session

Hi Iam creating a simple php shopping cart application in which the items are shown initially and when the user clicks add to cart it is added the cart.The problem is except first product everything is added to the cart.The first product alone showing erreor on adding.
Could anyone help me to fix this problem soon
here is my code
my chooseproduct.php
<div class="products">
<?php
include "config.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']);
$query3 = $mysqli->query("SELECT * FROM `catalouge` where subcat_id='$subcat_id'");
if ($query3) {
while($obj = $query3->fetch_object())
{
echo '<div class="product">';
echo '<form method="post" action="cart_update3.php">';
echo '<div class="product-thumb"></div>';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-desc">'.$obj->description.'</div>';
echo '<div class="product-info">';
echo 'Price '.$currency.$obj->product_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>';
}
}
?>
<div class="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<ol>';
foreach ($_SESSION["products"] as $cart_itm)
{
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<h3>'.$cart_itm["name"].'</h3>';
echo '<div class="p-code">P code : '.$cart_itm["code"].'</div>';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div class="p-price">Price :'.$currency.$cart_itm["price"].'</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}
echo '</ol>';
echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> Check-out!</span>';
echo '<span class="empty-cart">Empty Cart</span>';
}else{
echo 'Your Cart is empty';
}
?>
</div>
</div>
cart_update3.php
<?php
session_start();
include_once("config.php");
//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')
{
$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
//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>');
}
//MySqli query - get details of item from db using product code
$results = $mysqli->query("SELECT product_name,product_price FROM catalouge 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->product_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);
}
//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);
}
?>
Hi the page is not showing any errors. but the first product fetched from the database is not added to the cart.except the first one all are adding

PHP and SQL Shopping Cart is Not Adding Products to Shopping Cart

I am trying to make a simple MSSQL and PHP shopping cart for my website. The page index.php correctly retrieves the products from my MSSQL products table and displays them. For each product displayed there is an Add to Cart button. The button should use $_SESSION to store the added product into the shopping cart via the cart_update.php page. The products added to the shopping cart should be displayed at the bottom of the index.php page. Currently, when the Add to Cart button is hit, no products are added to the shopping cart. I am unsure why this is happening.
Here is my index.php page code:
<?php
session_start();
include_once("config.php");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<div class="products">
<?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']);
$query = "SELECT * FROM products ORDER BY id ASC";
$results = mssql_query($query, $mysqli);
if ($results) {
//output results from database
while($obj = mssql_fetch_object($results))
{
echo '<div class="product">';
echo '<form method="post" action="cart_update.php">';
echo '<div class="product-thumb"><img src="images/'.$obj->product_img_name.'"></div>';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-desc">'.$obj->product_desc.'</div>';
echo '<div class="product-info">Price '.$currency.$obj->price.' <button class="add_to_cart">Add To Cart</button></div>';
echo '</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>';
}
}
?>
</div>
<div class="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<ol>';
foreach ($_SESSION["products"] as $cart_itm)
{
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<h3>'.$cart_itm["name"].'</h3>';
echo '<div class="p-code">P code : '.$cart_itm["code"].'</div>';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div class="p-price">Price :'.$currency.$cart_itm["price"].'</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}
echo '</ol>';
echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> Check-out!</span>';
echo '<span class="empty-cart">Empty Cart</span>';
}else{
echo 'Your Cart is empty';
}
?>
</div>
</body>
</html>
And here is my cart_update.php page code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?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')
{
$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
//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>');
}
$query = "SELECT product_name,price FROM products WHERE product_code='$product_code' LIMIT 1";
//MySqli query - get details of item from db using product code
$results = mssql_query($query, $mysqli);
$obj = mssql_fetch_object($results);
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);
}
//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);
}
?>
</body>
</html>
Thank you for any help. All help is greatly appreciated.
To add products to the shopping cart I had to change the query in the cart_update.php page where
$query = "SELECT product_name,price FROM products WHERE product_code='$product_code LIMIT 1'";
to
$query = "SELECT TOP 1 product_name,price FROM products WHERE product_code='$product_code'";
This is because LIMIT does not work in SQL Server, and the equivalent is TOP.

Categories