https://kopy.io/6Ud9J https://kopy.io/7tFRb
In first code I have view_cart.php but it doesn't show me the values.
Viewcart.php
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>pret</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION['prodcos'])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION['prodcos'] as $cart_itm)
{
var_dump($cart_itm);
//set variables to use in content below
$titlu = $cart_itm['titlu'];
$cantitate = $cart_itm['cantitate'];
$pret = $cart_itm['pret'];
$id = $cart_itm['id'];
$subtotal = ($pret * $cantitate); //calculate pret x Qty
var_dump($titlu);
var_dump($pret);
var_dump($titlu);
echo '<tr>';
echo '<td><input type="text" size="2" maxlength="2" name="cantitate['.$id.']" value="'.$cantitate.'" /></td>';
echo '<td>'.$titlu.'</td>';
echo '<td>'.$pret.$currency.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$id.'" /></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 : <?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>
update_cart.php
<?php
session_start();
include_once("includes/config.php");
//add product to session or create new one
if(isset($_POST['type']) && $_POST['type']=='add' && $_POST['cantitate']>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']);
$id = $_POST['id'];
$sth = $db->prepare("SELECT titlu, pret FROM produse WHERE id = :id");
$sth->bindParam(':id', $id);
$sth->execute();
// $statement = $db->query('SELECT titlu, pret FROM produse WHERE id="$id"');
while($sth->fetch(PDO::FETCH_ASSOC)){
//fetch product name, pret from db and add to new_product array
$new_product['titlu'] = $titlu;
$new_product['pret'] = $pret;
if(isset($_SESSION['prodcos'])){ //if session var already exist
if(isset($_SESSION['prodcos'][$new_product['id']])) //check item exist in products array
{
unset($_SESSION['prodcos'][$new_product['id']]); //unset old array item
}
}
$_SESSION['prodcos'][$new_product['id']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST['cantitate']) || isset($_POST['remove_code']))
{
//update item quantity in product session
if(isset($_POST['cantitate']) && is_array($_POST['cantitate'])){
foreach($_POST['cantitate'] as $key => $value){
if(is_numeric($value)){
$_SESSION['prodcos'][$key]['cantitate'] = $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['prodcos'][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST['return_url']))?urldecode($_POST['return_url']):''; //return url
header('Location:'.$return_url);
?>
When I ADD the product, in shopping cart, it doesn't show the details..
Related
I try to send an email with phpmailer after "Place Order".
The problem is that I cannot list the shopping cart as an email (product, quantity, price of each product and total price).
echo var_dump($_SESSION['cart']);
echo var_dump($_SESSION['qty_array']);
This shows me that everything seems to work.
cart.php:
<tr>
<?php
$total = 0;
if(!empty($_SESSION['cart'])){
include 'config.php';
$index = 0;
if(!isset($_SESSION['qty_array'])){
$_SESSION['qty_array'] = array_fill(0, count($_SESSION['cart']), 1);
}
$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
?>
</tr>
<tr>
<td>
<img src="<?= $row['photo'] ?>" width="150px"><br />
<?= $row['name'] ?>
</td>
<input type="hidden" name="indexes[]" value="<?php echo $index; ?>">
<td>
<?php echo $_SESSION['qty_array'][$index]; ?>
</td>
<td>
<b><i class="fas fa-dollar-sign"></i> <?php echo number_format($_SESSION['qty_array'][$index]*$row['price'], 2); ?></b>
</td>
<?php $total += $_SESSION['qty_array'][$index]*$row['price']; ?>
</tr>
<?php
$index ++;
}
}
?>
phpmailer.php:
echo var_dump($_SESSION['cart']);
echo var_dump($_SESSION['qty_array']);
foreach($_SESSION['cart'] as $key => $product) {
$name = $product['name'];
$price = $product['price'];
$qty = $product['qty'];
$tprice = $product['totalPrice'];
}
$mail->Body = nl2br("$name\r\n$\r\n$qty\r\n$tprice");
This is not working at all. I tried a few things, and most of what worked was just the listing of the last product on the shopping cart list. But only the ID.
Edit:
I have tried another way, but still only the last item is listed.
phpmailer.php:
$total = 0;
if(!empty($_SESSION['cart'])){
include 'config.php';
$index = 0;
if(!isset($_SESSION['qty_array'])){
$_SESSION['qty_array'] = array_fill(0, count($_SESSION['cart']), 1);
}
$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$service = $row['name'];
$qty = $_SESSION['qty_array'][$index];
$qtyPrice = number_format($row['price'], 2);
$qtyTotalprice = number_format($_SESSION['qty_array'][$index]*$row['price'], 2);
$total += $_SESSION['qty_array'][$index]*$row['price'];
$mail->Body = nl2br("$service: ($qty) x ($$qtyPrice) = $$qtyTotalprice \r\n \r\nTOTAL: $ <u>$total</u>");
$index ++;
}
}
I found a solution:
phpmailer.php
...
$mail->Body = nl2br("Hi {$_POST['name']} \r\n");
/// List Cart Item(s) Start
$total = 0;
if(!empty($_SESSION['cart'])){
include 'config.php';
$index = 0;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array_fill(0, count($_SESSION['cart']), 1);
}
$sql = "SELECT * FROM products WHERE id IN (".implode(',',$_SESSION['cart']).")";
$query = $conn->query($sql);
while($row = $query->fetch_assoc()){
$index;
$service = $row['name'];
$qty = $_SESSION['cart'][$index];
$qtyPrice = $row['price'];
$qtyTotalprice = number_format($_SESSION['cart'][$index]*$row['price'], 2);
$total += $_SESSION['cart'][$index]*$row['price'];
$mail->Body .= nl2br("$service: ($qty) x ($$qtyPrice) = $$qtyTotalprice \r\n");
$index ++;
}
}
$mail->Body .= nl2br(" \r\nTOTAL: $ <u>$total</u>");
/// Cart Item(s) End
$mail->Body .= nl2br("Kind regards \r\n");
...
I'm trying to loop all rows of a table name cart but the foreach is only displaying the last row entered and always ignore the previous ones. Say I have 5 products in the cart_table well only product_id[5] will be displayed. If user adds a sixth item, only product_id[6] will now be displayed. The $item_count will also always equal 1 as if there is only one item when there are multiple. To my understanding in the foreach($items as $item) $items is not seen as an array even with multiple items. when I var_dump($items); it shows array(1) { [0]=>...
add_cart.php
<?php
ob_start();
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/core/init.php';
$product_id = isset($_POST['product_id'])? sanitize($_POST['product_id']):'';
$size = isset($_POST['size'])? sanitize($_POST['size']):'';
$available = isset($_POST['available'])? sanitize($_POST['available']):'';
$quantity = isset($_POST['quantity'])? sanitize($_POST['quantity']):'';
$item = array();
$item[] = array(
'id' => $product_id,
'size' => $size,
'quantity' => $quantity,
'available' => $available
);
$domain =($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$query = $db->query("SELECT * FROM product WHERE id = '{$product_id}'");
$product = mysqli_fetch_assoc($query);
$_SESSION['success_flash'] = $product['prod_name']. ' was added to your cart.';
//check if the cart cookie exists
if (is_array($cart_id != ' ')) {
$cartQ = $db->query("SELECT * FROM cart WHERE id = '{$cart_id}'");
$cart = mysqli_fetch_assoc($cartQ);
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach($previous_items as $pitem){
if ($item[0]['id'] == $pitem['id'] && $item[0]['size'] == $pitem['size']) {
$pitem['quantity'] = $pitem['quantity'] + $item[0]['quantity'];
if ($pitem['quantity'] > $available) {
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if ($item_match != 1) {
$new_items = array_merge($item,$previous_items);
}
$items_json = json_encode($new_items);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = '{cart_id}'");
setcookie(CART_COOKIE,'',1,"/",$domain,false);
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}else{
// add to databse and set cookie
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}')");
$cart_id = $db->insert_id;
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
?>
cart.php
<?php
require_once 'core/init.php';
//include 'includes/headerpartial.php';
if($cart_id != ' ') {
$cartQ = $db->query("SELECT * FROM cart WHERE id ='{$cart_id}' ");
$result = mysqli_fetch_assoc($cartQ);
$items = json_decode($result['items'], true);
$i = 1;
$sub_total = 0;
$item_count = 0;
}
?>
<?php if($cart_id == ' '): ?>
<div class="bg-danger">
<p class='text-center text-danger'>Your cart is empty.</p>
</div>
<?php else: ?>
<?php
foreach ($items as $item) {
var_export($items);
$product_id = $item['id'];
$productQuery = $db->query("SELECT * FROM product WHERE id ='{$product_id}' ");
$product = mysqli_fetch_assoc($productQuery);
$sArray = explode(',', $product['sizes']);
/* foreach ($sArray as $sizeString) {
$s = explode(':', $sizeString);
if($s[0] == $item['size']) {
$available = $s[1];
}
}*/
?>
<tr class="p">
<td class="image"><img src="<?= $product['image_1']; ?>"/></td>
<td class="name"><?= $product['prod_name']; ?></td>
<td class="price"><?= money($product['price']); ?></td>
<td class="quantity"><?= $item['quantity']; ?></td>
<td class="pricesubtotal"><?= money($item['quantity'] * $product['price']); ?></td>
<td class="remove">
<div>×</div>
</td>
</tr>
<?php
$i ++;
$item_count += $item['quantity'];
$sub_total += ($product['price'] * $item['quantity']);
}
$tax = TAXRATE * $sub_total;
$tax = number_format($tax, 2);
$grand_total = $tax + $sub_total;
<?php endif;?>
Here is one of the problems. You told me that your id is an auto increment int, so I would like to propose this answer. The problem is in your sql command.
UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = {cart_id}
Be sure to put that command in quotes. Also, I highly recommend preparing the JSON with this command:
$itemJson = addslashes($itemJson);
then, you can run the command. Another possibility would be to use the prepare method from mysqli. Here is a link to some examples:
w3schools.com
if you have any further questions, feel free to update your question, but be sure to #McStuffins in the comments.
I am making a shopping cart system, and my session is being displayed with a foreach() function. Inside this function, i have a variable called $item_price. I would like all the $item_price's to be added up so that I end up with the grand total.
How could this be done? I have no clue to how this problem should be solved :/
This is my foreach() code:
foreach($session_cart as $cart_items) {
$fetch_info = mysql_query("SELECT * FROM `shop_items` WHERE item_id = '$cart_items'");
while($shop_items = mysql_fetch_array($fetch_info)) {
$item_id = $shop_items['item_id'];
$item_name = $shop_items['item_name'];
$item_quantity = count(array_keys($session_quantity, $item_id));
$item_price = $shop_items['item_price'] * $item_quantity; }
$cartOutput .= '<h2>'.$item_name.'</h2>';
$cartOutput .= '<a> Quantity: '.$item_quantity.'</a><br>';
$cartOutput .= '<a> Price: '.number_format((float)$item_price, 2, '.', '').' USD</a><br>';
$cartOutput .= '<a> ID: '.$item_id.'</a><br><br>';
}
Use updated code:
$total = 0;
foreach($session_cart as $cart_items) {
$fetch_info = mysql_query("SELECT * FROM `shop_items` WHERE item_id = '$cart_items'");
// while($shop_items = mysql_fetch_array($fetch_info)) { //<- No need of loop here as only one will be returned everytime
$shop_items = mysql_fetch_assoc($fetch_info); //<- use this instead
$item_id = $shop_items['item_id'];
$item_name = $shop_items['item_name'];
$item_quantity = count(array_keys($session_quantity, $item_id));
$item_price = $shop_items['item_price'] * $item_quantity;
//} //<- Closing while loop removed
$cartOutput .= '<h2>'.$item_name.'</h2>';
$cartOutput .= '<a> Quantity: '.$item_quantity.'</a><br>';
$cartOutput .= '<a> Price: '.number_format((float)$item_price, 2, '.', '').' USD</a><br>';
$cartOutput .= '<a> ID: '.$item_id.'</a><br><br>';
$total+=$item_price; //<- Sums up for grand total
}
echo $total; //<- shows grand total
$total = 0;
foreach($array as $row)
{
$total += $row['item_price'];
//the rest of your code in foreach
}
echo $total;
I'm just learning how to use this StackOverflow, so please bear with me. If you need anything further I can provide it. I can click the checkmark on your answer if you can help me.
My code is working, but there is a small glitch. Currently, I have $i=0 and my code deletes the $i from the form. The problem is that with, for example, when $i=2 is deleted, $i=3 becomes $i=2, and I can no longer delete that item from my cart, because it is now the same $i that was deleted.
Here is my code:
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
header("location: cart.php");
} else {
unset($_SESSION["cart_array"]["$key_to_remove"]);
//sort($_SESSION["cart_array"]);
}
}
And here is my output loop:
$cartoutput = "";
$cartTotal="";
$totalwithtaxdisplay = 0;
$servicechargedisplay =0;
$grandtotaldisplay = 0;
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartoutput = "<div align='center'><font style='font-weight: bold; font-size: 20pt;'>Your order is currently empty.</font></div>";
}else{
$i=0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$result = mysqli_query($con,"SELECT * FROM menuitem WHERE id='$item_id' LIMIT 1");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));// Displays the error that mysql will generate if syntax is not correct.
exit();
}
//echo mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result)) {
//item id is $each_item['item_id']; being pulled in from form on other page PID.
$id = $row['id'];
$product_name = $row["name"];
$price = $row["price"];
$description = $row['description'];
}
$tax = .065;
$service = .18;
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
$totalwithtax = round($cartTotal + ($cartTotal * $tax), 2); //Order Items + Tax
$totalwithtaxdisplay = number_format($totalwithtax, 2, '.', ''); //displays the decimals correctly
$servicecharge = round($totalwithtax * $service, 2); //service charge
$servicechargedisplay = number_format($servicecharge, 2, '.', ''); //displays the decimals correctly
$grandtotal = round($totalwithtax + ($totalwithtax * $service), 2); //service charge
$grandtotaldisplay = number_format($grandtotal, 2, '.', ''); //displays the decimals correctly
$cartoutput .= " <tr><td width='20%'> Order Item $i </td>
<td width='40%'> " . $product_name . "</td>
<td width='20%'> $" . $price . ".00</td>";
$cartoutput .=" <td width='20%'><form action='cart.php' method='post'>
<input name='deleteBtn" . $item_id . "'type='submit' value='Remove This Item' />
<input name='index_to_remove' type='hidden' value='" . $i . "' />
</form></td></tr>";
$i++;
}
}
I echo out the $cartouput at a later time. You can see in the code above the second $cartouput is the form i'm using. It hold the value $i, but when that value is deleted, it doesn't let me delete the item that has updated into the new $i.
Instead of setting index_to_remove to $i, you should set it to $item_id and in your session variable. That way, you no longer need $i.
Also, this line leaves you with an SQL injection vulnerability: $item_id = $each_item['item_id'];. You should, at minimum, escape it using mysqli_real_escape_string().
My problem is I am having a cart_array which store the product added into my cart. when I press submit and process through the first block of php, if there's sufficient data, it should go to the unset($_SESSION['cart_array']); part and destroy the cart_array, however, it does not do so, the item added still show up in my cart.php. I tried session_destroy also no luck. Thing to note is that it does echo out $success which means the code should pass through that part but why it didn't unset my cart_array?
<?php
if ($_POST['cartOutput']) {
$customer_name = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_name']);
$tel_num = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['tel_num']);
$customer_address = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_address']);
$customer_messages = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_messages']);
$error_status = false;
if (empty($customer_name)){
$error_customer_name ='<h4>Please Fill Your Name</h4>';
$error_status = true;
}
if (empty($tel_num)){
$error_tel_num='<h4>Please Fill Your Contact Number</h4>';
$error_status = true;
}
if (empty($customer_address)){
$error_customer_address='<h4>Please Fill Your Address</h4>';
$error_status = true;
}
if(!$error_status) {
include "storescripts/connect_to_mysqli.php";
$sql= 'INSERT INTO orders (customer_name,tel_num,customer_address,product_name, price, quantity, date_added,customer_messages) VALUES(?,?,?,?,?,?,NOW(),?)';
$stmt = $myConnection->prepare($sql);
$countArray = count($_POST["item_name"]);
for ($i = 0; $i < $countArray; $i++) {
$stmt->bind_param('sssssss', $customer_name,$tel_num,$customer_address, $_POST['item_name'][$i], $_POST['amount'][$i], $_POST['quantity'][$i],$customer_messages);
$stmt->execute();
}
;
$to_address="someone#gmail.com";
$subject="Online Store Order Submission";
$cartTotal=$_POST['cartTotal'];
$message="Input from online order form.\n\n";
$message .="Name: ".$customer_name."\n";
$message .="Tel: ".$tel_num."\n";
$message .="Address: ".$customer_address."\n";
$message .="Messages: ".$customer_messages."\n";
$message .="Total:".$cartTotal."\n";
mail($to_address, $subject, $message);
$success= 'ORDER SUMITTED SUCCESSFULLY! Thank you and WELCOME to shop again!';
unset($_SESSION["cart_array"]);
}
}
?>
another thing to note is when I make the form action posted to another file let's say order.php and put the above code in it, it UNSET the session, of cause i change the POST to ISSET and put exit() after the unset thou, when i try to put exit() in my cart.php it just go blank if it submitted succesffully.
any help would be appreciated
The below are all the PHP BLOCK above HTML tag for the reference.
<?php
if ($_POST['cartOutput']) {
$customer_name = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_name']);
$tel_num = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['tel_num']);
$customer_address = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_address']);
$customer_messages = preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $_POST['customer_messages']);
$error_status = false;
if (empty($customer_name)){
$error_customer_name ='<h4>Please Fill Your Name</h4>';
$error_status = true;
}
if (empty($tel_num)){
$error_tel_num='<h4>Please Fill Your Contact Number</h4>';
$error_status = true;
}
if (empty($customer_address)){
$error_customer_address='<h4>Please Fill Your Address</h4>';
$error_status = true;
}
if(!$error_status) {
include "storescripts/connect_to_mysqli.php";
$sql= 'INSERT INTO orders (customer_name,tel_num,customer_address,product_name, price, quantity, date_added,customer_messages) VALUES(?,?,?,?,?,?,NOW(),?)';
$stmt = $myConnection->prepare($sql);
$countArray = count($_POST["item_name"]);
for ($i = 0; $i < $countArray; $i++) {
$stmt->bind_param('sssssss', $customer_name,$tel_num,$customer_address, $_POST['item_name'][$i], $_POST['amount'][$i], $_POST['quantity'][$i],$customer_messages);
$stmt->execute();
}
;
$to_address="someone#gmail.com";
$subject="Online Store Order Submission";
$cartTotal=$_POST['cartTotal'];
$message="Input from online order form.\n\n";
$message .="Name: ".$customer_name."\n";
$message .="Tel: ".$tel_num."\n";
$message .="Address: ".$customer_address."\n";
$message .="Messages: ".$customer_messages."\n";
$message .="Total:".$cartTotal."\n";
mail($to_address, $subject, $message);
$success= 'ORDER SUMITTED SUCCESSFULLY! Thank you and WELCOME to shop again!';
unset($_SESSION["cart_array"]);
}
}
?>
<?php
session_start();
/* Created by Adam Khoury # www.developphp.com */
// Connect to the MySQL database
include "storescripts/connect_to_mysqli.php";
// Query the module data for display ---------------------------------------------------------------------------------------------------------------
$sqlCommand = "SELECT modulebody FROM modules WHERE showing='1' AND name='footer' LIMIT 1";
$query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$footer = $row["modulebody"];
}
mysqli_free_result($query);
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
// Query the module data for display ---------------------------------------------------------------------------------------------------------------
$sqlCommand = "SELECT modulebody FROM modules WHERE showing='1' AND name='custom1' LIMIT 1";
$query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$custom1 = $row["modulebody"];
}
mysqli_free_result($query);
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
// Build Main Navigation menu and gather page data here -----------------------------------------------------------------------------
$sqlCommand = "SELECT id, linklabel FROM pages WHERE showing='1' ORDER BY id DESC";
$query = mysqli_query($myConnection, $sqlCommand) or die(mysqli_error());
$menuDisplay = '';
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$linklabel = $row["linklabel"];
$menuDisplay .= '<a href="index.php?pid=' . $pid . '">' .
$linklabel . '</a><br />';
}
mysqli_free_result($query);
//---------------------------------------------------------------------------------------------------------------------------------------------------------------
//mysqli_close($myConnection);
// This file is www.developphp.com curriculum material
// Written by Adam Khoury January 01, 2011
// http://www.youtube.com/view_play_list?p=442E340A42191003
// Script Error Reporting
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 1 (if user attempts to add something to the cart from the product page)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $pid) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["cart_array"], $i - 1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
}
header("location: cart.php");
exit();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 2 (if user chooses to empty their shopping cart)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_GET['cmd']) && $_GET['cmd'] === 'emptycart') {
unset($_SESSION["cart_array"]);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 3 (if user chooses to adjust item quantity)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
// execute some code
$item_to_adjust = $_POST['item_to_adjust'];
$quantity = $_POST['quantity'];
$quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers
if ($quantity >= 100) {
$quantity = 99;
}
if ($quantity < 1) {
$quantity = 1;
}
if (empty($quantity)) {
$quantity = 1;
}
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $item_to_adjust) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["cart_array"], $i - 1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
} // close if condition
} // close while loop
} // close foreach loop
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 4 (if user wants to remove an item from cart)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] !== '') {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]) <= 1) {
unset($_SESSION["cart_array"]);
} else {
unset($_SESSION["cart_array"][$key_to_remove]);
sort($_SESSION["cart_array"]);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Section 5 (render the cart for the user to view on the page)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$cartOutput = "";
$cartTotal = "";
$pp_checkout_btn = '';
$product_id_array = '';
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
$cartOutput = "<h3 align='center'>Your shopping cart is empty</h3>";
} else {
// Start PayPal Checkout Button
$pp_checkout_btn .= '<form action=" " method="post">
<input type="hidden" name="cartOutput" value = "$cartOutput">';
// Start the For Each loop
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$sqlCommand = "SELECT * FROM products WHERE id='$item_id' LIMIT 1";
$sql = mysqli_query($myConnection, $sqlCommand);
while ($row = mysqli_fetch_array($sql)) {
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
}
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
setlocale(LC_MONETARY, "ms_MY");
$pricetotal = money_format("%10.2n", $pricetotal);
// Dynamic Checkout Btn Assembly
$pp_checkout_btn .= '<input type="hidden" name="item_name[]" value="' . $product_name . '">
<input type="hidden" name="amount[]" value="' . $price . '">
<input type="hidden" name="quantity[]" value="' . $each_item['quantity'] . '"> ';
// Create the product array variable
$product_id_array .= "$item_id-" . $each_item['quantity'] . ",";
// Dynamic table row assembly
$cartOutput .= "<tr>";
$cartOutput .= '<td><center>' . $product_name . '<br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name . '" width="40" height="52" border="0" /></center></td>';
$cartOutput .= '<td>' . $details . '</td>';
$cartOutput .= '<td><center>RM' . $price . '</center></td>';
$cartOutput .= '<td><center><form action="cart.php" method="post">
<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
<input name="adjustBtn' . $item_id . '" type="submit" value="change" />
<input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
</form></center></td>';
//$cartOutput .= '<td><center>' . $each_item['quantity'] . '</center></td>';
$cartOutput .= '<td><center>' . $pricetotal . '</center></td>';
$cartOutput .= '<td><center><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></center></td>';
$cartOutput .= '</tr>';
$i++;
}
setlocale(LC_MONETARY, "ms_MY");
$cartTotal = money_format("%10.2n", $cartTotal);
$cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : " . $cartTotal . " MYR</div>";
// Finish the Paypal Checkout Btn
$pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '">
<div id="table">
Name: <input type="text" name="customer_name">
<br/>
Tel: <input type="text" name="tel_num">
<br/>
Address: <input type="text" name="customer_address">
<br/>
Messages: <textarea name="customer_messages">
</textarea>
<input type="hidden" name="cartTotal" value="' . $cartTotal . '">
<input type="submit" value="Submit">
</div>
</form>';
}
?>
If you want to manipulate the session as in unset($_SESSION["cart_array"]); you have to have a session to manipulate.
So if you add a session_start(); at the top of the first piece of code, it will probably unset correctly
As in :-
<?php
session_start();
if ($_POST['cartOutput']) {
....