first product not added in session - php

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

Related

Send SESSION GET information in POST contact form together with the POST fields

On the website i'm currently working on I made a list (cart idea) where customers can put products on. It works with GET method + a session, the code for the making of the session is as follows:
`<?php session_start();
require("dbconnect.php");
?>
<?php
if(!isset($_SESSION['cart'])) {
$cart = array();
$_SESSION['cart'] = $cart;
}
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(in_array($id, $_SESSION['cart'])){
if (($key = array_search($id, $_SESSION['cart'] !== false))){
unset($_SESSION['cart'][$key]);
}
}
else {
array_push($_SESSION['cart'],$id);
}
}
if(isset($_GET['action']) && $_GET['action']=="delete"){
$id = intval($_GET['id']);
if (in_array($id, $_SESSION['cart'])){
$key = array_search($id, $_SESSION['cart']);
unset($_SESSION['cart'][$key]);
}
}
?>
Nothing special, just a regular cart in a session with an array where I put all the unique product codes to remember what is on the list. Now when customers go to the page where they could send the list of product they also can select how many of each product they want. They have to fill in a number and when they are done they click on the button 'calculate (berekenen in my language)' and they get the subtotal price of all the products, the VAT and the total price. However, I want it this way that the customer can fill in their personal information plus the list plus the amounts to be send in an e-mail. I made selfmade PHP forms myself earlier but now i'm getting stuck. I use GET for the order list but I always use a POST form for my contactforms. How can I manage to make one button that sends the list plus the amounts plus the input of the contact form fields to me? At this moment I tried it as follows (and many more ways, but it all failed so far).
<main>
<div class="main-center">
<div class="offerte-container">
<form action="" method="get" value="offertelijst">
<ul class="offerte-list">
<?php
$per_page = 9;
$args = array(
'post_type'=> 'wpcproduct',
'order' => 'ASC',
'orderby' => 'menu_order',
'posts_per_page' => $per_page
);
$products = new WP_Query($args);
?>
<?php
while($products->have_posts()): $products->the_post();
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
echo '<li class="wpc-product-item">';
echo 'Verwijder ';
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
echo '<div class="item-title"> ' .$title. ' </div>';
echo '<div class="item-take"> <img width="25px" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/pijltje.png" /> </div>';
echo '<div class="item-nr"> '.$product_id. '</div>';
if((isset($_GET["amount$id"]) && $_GET["amount$id"] == 1) || $_GET["amount$id"] == "" ){
if (is_numeric($price) && (floor($price) == $price)) {
echo '<div class="item-price"> €' .number_format ($price , 0 , "," , "." ). ',- </div>';
}
else {
echo '<div class="item-price"> €' .$price. '</div>';
}
echo '</li>';
}
else if(isset($_GET["amount$id"]) && floatval($_GET["amount$id"]) > 1){
changeFormat($price);
$priceTotal = number_format($price * floatval($_GET["amount$id"]), 2);
if (is_numeric($priceTotal) && (floor($priceTotal) == $priceTotal)) {
echo '<div class="item-price"> €' .$priceTotal . ',- </div>';
}
else {
echo '<div class="item-price"> €' .$priceTotal . '</div>';
}
echo '</li>';
}}
endwhile;
?>
</ul>
<input type="submit" value="Bereken"> </input>
</form>
<div class="totalprice">
<?php
(float)$total = 0;
while($products->have_posts()): $products->the_post(); {
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
if (is_numeric($price) && (floor($price) == $price)) {
$price = number_format($price, 2);
}
else {
$price = str_replace(',', '.', $price);
}
$total += (floatval($price) * floatval($_GET["amount$id"]));
}}
endwhile;
(String)$total;
number_format($total, 2);
$totalDecimal = str_replace('.', ',', $total);
echo 'Subtotaal: €' .$totalDecimal. '<br />';
echo 'BTW: €' . str_replace('.',',', number_format($total * 0.21,2)). '<br />';
echo 'Totaal: €' . str_replace('.',',', number_format($total * 1.21,2));
function changeFormat($var) {
if(is_numeric($var) && (floor($var) == $var)){
return number_format($var, 0) + ',-';
}
else {
if (is_numeric($var)) {
return number_format($var, 2, ',', '.');
}
else if (is_string ($var)){
return str_replace(',', '.', $var);
}
else {
echo "What the hell is dit voor een formaat?";
}
}}
?>
</div>
</div>
</div>
</main>
The calculate function and the orderlist are all working fine and i'm able to make a standard POST form as a contactform but I can't manage to get this done. I want the button 'send' to send the list plus the given amounts per product and the filled in contact forms.
The URL for this project is: http://www.bgc-testomgeving.nl/sem
Underneath the http://www.bgc-testomgeving.nl/sem/offertelijst/ page should be the contact form but every time I try to build this I demolish my perfect order list.
First of all change your form method to post.
<form action="" method="post" value="offertelijst">
Then you have to create inputs for each item in your form element. I see this you have only Amount input in your form:
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
Create input for each element, since user doesnt need to see those inputs you can create them as hidden element, here is one example for item title:
echo '<input type="hidden" name="title['.$id.']" value="' .$title. '"</input>';
Put this below this line
echo '<div class="item-title"> ' .$title. ' </div>';
After you created all inputs, also create second button near of this one:
<input type="submit" name="action" value="Bereken">
<input type="submit" name="action" value="Send">
So When the user click Bereken, you will do your calculation things, but if it is Send button, you will mail it to your self. here is Example code:
<?php
// if send button clicked
if($_POST["action"]=="Send")
{
/// mail to your self all element
mail("you#www.com","New Order",implode("-",$_POST));
}
?>
<main>
<div class="main-center">
<div class="offerte-container">
<form action="" method="post" value="offertelijst">
<ul class="offerte-list">
<?php
$per_page = 9;
$args = array(
'post_type'=> 'wpcproduct',
'order' => 'ASC',
'orderby' => 'menu_order',
'posts_per_page' => $per_page
);
$products = new WP_Query($args);
?>
<?php
while($products->have_posts()): $products->the_post();
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
echo '<li class="wpc-product-item">';
echo 'Verwijder ';
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
echo '<div class="item-title"> ' .$title. ' </div>';
// i added below input for example
echo '<input type="hidden" name="title['.$id.']" value="' .$title. '"</input>';
echo '<div class="item-take"> <img width="25px" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/pijltje.png" /> </div>';
echo '<div class="item-nr"> '.$product_id. '</div>';
if((isset($_GET["amount$id"]) && $_GET["amount$id"] == 1) || $_GET["amount$id"] == "" ){
if (is_numeric($price) && (floor($price) == $price)) {
echo '<div class="item-price"> €' .number_format ($price , 0 , "," , "." ). ',- </div>';
}
else {
echo '<div class="item-price"> €' .$price. '</div>';
}
echo '</li>';
}
else if(isset($_GET["amount$id"]) && floatval($_GET["amount$id"]) > 1){
changeFormat($price);
$priceTotal = number_format($price * floatval($_GET["amount$id"]), 2);
if (is_numeric($priceTotal) && (floor($priceTotal) == $priceTotal)) {
echo '<div class="item-price"> €' .$priceTotal . ',- </div>';
}
else {
echo '<div class="item-price"> €' .$priceTotal . '</div>';
}
echo '</li>';
}}
endwhile;
?>
</ul>
<input type="submit" name="action" value="Bereken">
<input type="submit" name="action" value="Send">
</form>
<div class="totalprice">
<?php
// is bereken button clickied
if($_POST["action"]=="Bereken") {
(float)$total = 0;
while($products->have_posts()): $products->the_post(); {
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
if (is_numeric($price) && (floor($price) == $price)) {
$price = number_format($price, 2);
}
else {
$price = str_replace(',', '.', $price);
}
$total += (floatval($price) * floatval($_GET["amount$id"]));
}}
endwhile;
(String)$total;
number_format($total, 2);
$totalDecimal = str_replace('.', ',', $total);
echo 'Subtotaal: €' .$totalDecimal. '<br />';
echo 'BTW: €' . str_replace('.',',', number_format($total * 0.21,2)). '<br />';
echo 'Totaal: €' . str_replace('.',',', number_format($total * 1.21,2));
}
function changeFormat($var) {
if(is_numeric($var) && (floor($var) == $var)){
return number_format($var, 0) + ',-';
}
else {
if (is_numeric($var)) {
return number_format($var, 2, ',', '.');
}
else if (is_string ($var)){
return str_replace(',', '.', $var);
}
else {
echo "What the hell is dit voor een formaat?";
}
}}
?>
</div>
</div>
</div>
</main>

Show Cart Session Item

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
}
?>

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.

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.

Shopping Cart's `View Cart Items` Page is not Paginating Properly

I have a PHP page that retrieves the arrays in my $_SESSION['products'] session. Each array in that session is a product added by the user to their "shopping cart" via the catalogue.php page. Currently my session has eleven arrays meaning I have added eleven products to the cart. I am now trying to display the arrays on my view_cart.php page, and paginate them by ten. Basically I would like the page to show the first ten arrays then to display the eleventh array on view_cart.php?Page=2. Right now, the code displays all eleven arrays on the page at once, and displays three error messages before each array. I have posted the errors below.
Warning: mssql_query() [function.mssql-query]: message: Incorrect
syntax near 'OFFSET'. (severity 15) in
D:\Hosting\4502990\html\partscatalogue\view_cart4.php on line 63
Warning: mssql_query() [function.mssql-query]: message: Invalid usage
of the option NEXT in the FETCH statement. (severity 15) in
D:\Hosting\4502990\html\partscatalogue\view_cart4.php on line 63
Warning: mssql_query() [function.mssql-query]: Query failed in
D:\Hosting\4502990\html\partscatalogue\view_cart4.php on line 63
Warning: mssql_fetch_object(): supplied argument is not a valid MS
SQL-result resource in
D:\Hosting\4502990\html\partscatalogue\view_cart4.php on line 64
Here is my full PHP page code for the view_cart.php page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
session_start();
include_once("config.php");
$cart_items = 0;
foreach ($_SESSION['products'] as $cart_itm)
{
$cart_items ++;
}
$Number_of_Arrays = $cart_items;
echo "Number of Arrays: ".$Number_of_Arrays."";
$Per_Page = 10; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Number_of_Arrays<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Number_of_Arrays % $Per_Page)==0)
{
$Num_Pages =($Number_of_Arrays/$Per_Page) ;
}
else
{
$Num_Pages =($Number_of_Arrays/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$Page_End = $Per_Page * $Page;
IF ($Page_End > $Number_of_Arrays)
{
$Page_End = $Number_of_Arrays;
}
?>
<?php
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="PAYMENT-GATEWAY">';
echo '<ul>';
$cart_items = 0;
$i = 0;
foreach ($_SESSION['products'] as $cart_itm)
{
$product_code = $cart_itm["code"];
$queryy = "SELECT TOP 1 product_name,product_desc, price FROM products ORDER BY id OFFSET (($Page - 1) * $Per_Page) FETCH NEXT $Per_Page ONLY";
$results = mssql_query($queryy, $mysqli);
$obj = mssql_fetch_object($results);
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>';
echo 'Checkout';
}
?>
</body>
</html>
Here is my config.php page's complete code:
<?php
$mysqli = mssql_connect('dag','gfa','dca');
$objConnectee = mssql_select_db('gba',$mysqli );
?>
Thank you for any help. All help is appreciated.

Categories