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.
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'];
}
}
}
I am having issues with my PHP code. I am trying to insert data into a mysql database with Session variables info. The connection to the SQL table is fine. Whenever i submit the form it displays none of the session variables. The code is quite lengthy. Any help would be highly appreciated.
View Cart Page
<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION["cart_products"])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$currency.$product_price.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}
$grand_total = $total + $shipping_cost; //grand total including shipping cost
foreach($taxes as $key => $value){ //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; //add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value){ //List all taxes
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : R <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
<tr><td colspan="5">Add More Items<button type="submit">Update</button></td></tr>
</tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>
</form>
</form>
The cart update Page
<?php
session_start();
include_once("config.php");
//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
foreach($_POST as $key => $value){ //add all post vars to new_product array
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
//remove unecessary vars
unset($new_product['type']);
unset($new_product['return_url']);
//we need to get product name and price from database.
$statement = $mysqli->prepare("SELECT product_name, price FROM products WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $price);
while($statement->fetch()){
//fetch product name, price from db and add to new_product array
$new_product["product_name"] = $product_name;
$new_product["product_price"] = $price;
if(isset($_SESSION["cart_products"])){ //if session var already exist
if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
}
}
$_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
//update item quantity in product session
if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
foreach($_POST["product_qty"] as $key => $value){
if(is_numeric($value)){
$_SESSION["cart_products"][$key]["product_qty"] = $value;
}
}
}
//remove an item from product session
if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
foreach($_POST["remove_code"] as $key){
unset($_SESSION["cart_products"][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);
?>
The page im having issues with, Insert Variables.php
<?
$product_name = $_SESSION["product_name"];
$product_qty = $_SESSION["product_qty"];
$product_price = $_SESSION["product_price"];
$hostname="Localhost";
$username="ABCD";
$password="";
$dbname="Abc";
$usertable="Shop";
$link = mysqli_connect($hostname,$username,$password,$dbname);
if(isset($_POST['submit'])){
$product_name = $_SESSION["product_name"];
$product_qty = $_SESSION["product_qty"];
$product_price = $_SESSION["product_price"];
}
if($link === false) {
die("Error: Could not connect.".mysqli_connect_error());
}
$sql = "INSERT INTO $usertable (Qty, product,productID) VALUES ('{$_SESSION['product_qty']}', '{$_SESSION['product_name']}', '{$_SESSION['cart_products']}')";
if (mysqli_query($link, $sql)){
echo "<h1> Succes </h1>";
} else {
echo "Error: could not execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
I guess the problem is at the very beginning of the Variables.php
You have:
$product_name = $_SESSION["product_name"];
$product_qty = $_SESSION["product_qty"];
$product_price = $_SESSION["product_price"];
But instead, it should be:
$product_name = $_SESSION["cart_products"][$key]["product_name"];
$product_qty = $_SESSION["cart_products"][$key]["product_qty"];
$product_price = $_SESSION["cart_products"][$key]["product_price"];
Where $key is the product_code
Then use the varibales
$sql = "INSERT INTO $usertable (Qty, product, productID) VALUES ('$product_qty', '$product_name', '$key'";
Help me guys to make page loader while the page is loading. I'm doing some paypal payment system. As I watch some pages, when the page is directing to paypal page, they put some loader(ajax loader) while the page is processing to redirect to "Paypal gateway". I'm also planning to put some Ajax loader in my other page while they're loading. So please help me guys. Here is my code.
<?php
$current_url = base64_encode($url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_POST['checkoutnow'])){
header('Location: checkout_now1.php');
}
if(isset($_SESSION["products"])){
$total = 0;
echo '<ol>';
echo '<form action="paypal-express-checkout/process.php" method="POST">';
$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 '</ol>';
echo '<strong>Total: '.$currency.$total.'</strong><br />';
echo '<center>
<div id="check_out">
<button>Check Out with US</button><br />OR<br />
<div class="paypal-button"><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckoutsm.gif"></div>
</center>
</div>';
echo '</form>';
}else{
echo 'Your Cart is Empty<br />Go to Home And Order';
}
?>
To do so, you can use javascript method "setInterval()" to put a time between two process or more. I didn't get where is you condition to put this delay, but I link you my code and hope it helps :
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
<title> title-page </title>
</head>
<body>
<script type = "text/javascript">
function loading() {
var miliSecTime = 1000; // 1 sec time between each process for example
document.getElementById("waitDiv").InnerHtml = "<img src = 'wait.gif' />";
var timer = setInterval(function () {
// BEGIN : Your process
// END : Your process
// Condition to abort the process
// Likely when you want to stop
// the waiting view
if (leftLoading_condition) {
clearInterval(timer);
document.getElementById("waitDiv").innerHTML = ""; // Hidding the wait view
}
},
miliSecTime
);
}
</script>
<!-- This is where you want to show you wait gif -->
<div id = "waitDiv">
</div>
<input type = "button" onClick = "loading()" />
</body>
</html>
The "setInterval()" function takes two parameters : the first is you function, the second is the delay you want to put between each tick. So you make a proces into the function method, and the trick is to put a left tick event condition, with the call of the method "clearInterval" which will stop the tick.
So here is the work of this code :
The function "loading" is called by clicking on the button. The method launch the process which is included in the "function () {}" code. Before launching this process, we show the wait gif, which can be a loading gif or whatever. Then, the process run in loop until the left tick condition (the if() call). If we have reach the end of the process, the timer is aborted by clearing the interval parameters (by calling "clearInterval()" method).
<?php
session_start();
include_once("../config.php");
include_once("paypal.class.php");
$paypalmode = ($PayPalMode=='sandbox') ? '.sandbox' : '';
if($_POST) //Post Data received from product list page.
{
//Other important variables like tax, shipping cost
$TotalTaxAmount = 2.58; //Sum of tax for all items in this order.
$HandalingCost = 2.00; //Handling cost for this order.
$InsuranceCost = 1.00; //shipping insurance cost for this order.
$ShippinDiscount = -3.00; //Shipping discount for this order. Specify this as negative number.
$ShippinCost = 3.00; //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
//we need 4 variables from product page Item Name, Item Price, Item Number and Item Quantity.
//Please Note : People can manipulate hidden field amounts in form,
//In practical world you must fetch actual price from database using item id.
//eg : $ItemPrice = $mysqli->query("SELECT item_price FROM products WHERE id = Product_Number");
$paypal_data ='';
$ItemTotalPrice = 0;
foreach($_POST['item_name'] as $key=>$itmname)
{
$product_code = filter_var($_POST['item_code'][$key], FILTER_SANITIZE_STRING);
$results = $mysqli->query("SELECT product_name, product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
$obj = $results->fetch_object();
$paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$key.'='.urlencode($obj->product_name);
$paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$key.'='.urlencode($_POST['item_code'][$key]);
$paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$key.'='.urlencode($obj->price);
$paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($_POST['item_qty'][$key]);
// item price X quantity
$subtotal = ($obj->price*$_POST['item_qty'][$key]);
//total price
$ItemTotalPrice = $ItemTotalPrice + $subtotal;
//create items for session
$paypal_product['items'][] = array('itm_name'=>$obj->product_name,
'itm_price'=>$obj->price,
'itm_code'=>$_POST['item_code'][$key],
'itm_qty'=>$_POST['item_qty'][$key]
);
}
//Grand total including all tax, insurance, shipping cost and discount
$GrandTotal = ($ItemTotalPrice + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount);
$paypal_product['assets'] = array('tax_total'=>$TotalTaxAmount,
'handaling_cost'=>$HandalingCost,
'insurance_cost'=>$InsuranceCost,
'shippin_discount'=>$ShippinDiscount,
'shippin_cost'=>$ShippinCost,
'grand_total'=>$GrandTotal);
//create session array for later use
$_SESSION["paypal_products"] = $paypal_product;
//Parameters for SetExpressCheckout, which will be sent to PayPal
$padata = '&METHOD=SetExpressCheckout'.
'&RETURNURL='.urlencode($PayPalReturnURL ).
'&CANCELURL='.urlencode($PayPalCancelURL).
'&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE").
$paypal_data.
'&NOSHIPPING=0'. //set 1 to hide buyer's shipping address, in-case products that does not require shipping
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
'&PAYMENTREQUEST_0_TAXAMT='.urlencode($TotalTaxAmount).
'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($ShippinCost).
'&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($HandalingCost).
'&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($ShippinDiscount).
'&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($InsuranceCost).
'&PAYMENTREQUEST_0_AMT='.urlencode($GrandTotal).
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode).
'&LOCALECODE=GB'. //PayPal pages to match the language on your website.
'&LOGOIMG='. //site logo
'&CARTBORDERCOLOR=FFFFFF'. //border color of cart
'&ALLOWNOTE=1';
//We need to execute the "SetExpressCheckOut" method to obtain paypal token
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
//Respond according to message we receive from Paypal
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
//Redirect user to PayPal store with Token received.
$paypalurl ='https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$httpParsedResponseAr["TOKEN"].'';
header('Location: '.$paypalurl);
}
else
{
//Show error message
echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}
//Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
if(isset($_GET["token"]) && isset($_GET["PayerID"]))
{
//we will be using these two variables to execute the "DoExpressCheckoutPayment"
//Note: we haven't received any payment yet.
$token = $_GET["token"];
$payer_id = $_GET["PayerID"];
//get session variables
$paypal_product = $_SESSION["paypal_products"];
$paypal_data = '';
$ItemTotalPrice = 0;
foreach($paypal_product['items'] as $key=>$p_item)
{
$paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($p_item['itm_qty']);
$paypal_data .= '&L_PAYMENTREQUEST_0_AMT'.$key.'='.urlencode($p_item['itm_price']);
$paypal_data .= '&L_PAYMENTREQUEST_0_NAME'.$key.'='.urlencode($p_item['itm_name']);
$paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER'.$key.'='.urlencode($p_item['itm_code']);
// item price X quantity
$subtotal = ($p_item['itm_price']*$p_item['itm_qty']);
//total price
$ItemTotalPrice = ($ItemTotalPrice + $subtotal);
}
$padata = '&TOKEN='.urlencode($token).
'&PAYERID='.urlencode($payer_id).
'&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE").
$paypal_data.
'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
'&PAYMENTREQUEST_0_TAXAMT='.urlencode($paypal_product['assets']['tax_total']).
'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($paypal_product['assets']['shippin_cost']).
'&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($paypal_product['assets']['handaling_cost']).
'&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($paypal_product['assets']['shippin_discount']).
'&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($paypal_product['assets']['insurance_cost']).
'&PAYMENTREQUEST_0_AMT='.urlencode($paypal_product['assets']['grand_total']).
'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode);
//We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
//Check if everything went ok..
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
echo '<h2>Success</h2>';
echo 'Your Transaction ID : '.urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
/*
//Sometimes Payment are kept pending even when transaction is complete.
//hence we need to notify user about it and ask him manually approve the transiction
*/
if('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"])
{
echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
}
elseif('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"])
{
echo '<div style="color:red">Transaction Complete, but payment is still pending! '.
'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
}
// we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
// GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
$padata = '&TOKEN='.urlencode($token);
$paypal= new MyPayPal();
$httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
{
echo '<br /><b>Stuff to store in database :</b><br />';
echo '<pre>';
/*
#### SAVE BUYER INFORMATION IN DATABASE ###
//see (http://www.sanwebe.com/2013/03/basic-php-mysqli-usage) for mysqli usage
//use urldecode() to decode url encoded strings.
$buyerName = urldecode($httpParsedResponseAr["FIRSTNAME"]).' '.urldecode($httpParsedResponseAr["LASTNAME"]);
$buyerEmail = urldecode($httpParsedResponseAr["EMAIL"]);
//Open a new connection to the MySQL server
$mysqli = new mysqli('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$insert_row = $mysqli->query("INSERT INTO BuyerTable
(BuyerName,BuyerEmail,TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$buyerName','$buyerEmail','$transactionID','$ItemName',$ItemNumber, $ItemTotalPrice,$ItemQTY)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
*/
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
} else {
echo '<div style="color:red"><b>GetTransactionDetails failed:</b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}else{
echo '<div style="color:red"><b>Error : </b>'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]).'</div>';
echo '<pre>';
print_r($httpParsedResponseAr);
echo '</pre>';
}
}
?>
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.
I am writing a script to place an order which will be added to a cart, I am storing the selected values for the cart as a session. Each new selection (addition to the cart) is added to a new session which is incremented by one each time.
ie.
$_SESSION['cart'][1]
$_SESSION['cart'][2]
$_SESSION['cart'][3]
I am receiving the below error and am stumped.
Warning: Cannot use a scalar value as an array in C:\wamp\www\php\cart\carting\order.php on line 37 -(This is the line $_SESSION['cart'][$p] = $cartstring;)
<?PHP
session_start();
$productlist = $_POST['products']; //Form post
if (isset($productlist)) {
if (!isset($_SESSION['cart'])) {
$p = 0;
$_SESSION['cart'][$p];
print $_SESSION['cart'][$p];
}
elseif (isset($_SESSION['cart'])) {
$p = count($_SESSION['cart']);
$p++;
$product = explode('-', $productlist[1][0]);
$productname = $product[0];
$productprice = $product[1];
$productqty = $productlist[1][1];
$itemsubtotal = ($productprice * $productqty);
$cartstring = "productid-$productname-$productprice-$productqty-$itemsubtotal";
$_SESSION['cart'][$p] = $cartstring; //THIS IS LINE 37
}
}
$product1 = "Bread";
$price1 = 12;
$product2 = "Butter";
$price2 = 2;
print '<form action="order.php" method="post">';
print '<input type="checkbox" name="products[1][]" value="'.$product1." "."-"." ".$price1.'" />';echo $product1;
print '<input type="text" name="products[1][]" value="" />QTY';print '<br>';
print '<br>';print '<br>';
print '
<input type="submit" name="formSubmit" value="Submit" />
</form>';
?>