SESSION Cart adding 2 + or -2 problem - php

So i edited my own shop but im having some issues with it, for example it add 2 instead of 1 or it removes 2 instead of 1,
you can see how it looks on www.neobotmx.org/test/tienda.php <<< not opwn for the public yet >> thats why its on a test folder
The shop code :
<?php
$product_id = $_GET[id]; //the product id from the URL
$action = $_GET[action]; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" align=\"center\" padding=\"3\" width=\"70%\">";
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\"><strong>Producto</strong></td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\"><strong>Cantidad</strong></td>";
echo "<td align=\"center\"><strong>Costo</strong></td>";
echo "</tr>";//format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT name, description, price FROM products WHERE id = %d;",
$product_id);
$result = mysql_query($sql);
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysql_num_rows($result) > 0) {
list($name, $description, $price) = mysql_fetch_row($result);
$line_cost = $price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\"><strong>$name</strong></td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\"><strong>$quantity </strong>Borrar</td>";
echo "<td align=\"center\"><strong>$line_cost</strong></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\"><strong>Total</strong></td>";
echo "<td align=\"right\"><strong>$total</strong></td>";
echo "</tr>";
echo "</table>";
}else{
//otherwise tell the user they have no items in their cart
echo "No tiene articulos en compra.";
}
//function to check if a product exists
function productExists($product_id) {
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;",
$product_id);
return mysql_num_rows(mysql_query($sql)) > 0;
}
?>
</p>
<p><strong>Seguir Comprando</strong></p>
<?php
and now the display of the books / items / whatever you want.
<?php
define('MAX_REC_PER_PAGE', 1);
$sql = "SELECT id, name, description, price FROM products;";
$rs = mysql_query("SELECT COUNT(*) FROM products") or die("Imposible Realizar Operacion");
list($total) = mysql_fetch_row($rs);
$total_pages = ceil($total / MAX_REC_PER_PAGE);
$page = intval(#$_GET["page"]);
if (0 == $page){
$page = 1;
}
$start = MAX_REC_PER_PAGE * ($page - 1);
$max = MAX_REC_PER_PAGE;
$rs = mysql_query("SELECT id, name, description, price FROM products ORDER BY id
ASC LIMIT $start, $max") or die("Imposible Realizar Operacion");
?>
<table width="100%" height="404" border="0" cellpadding="12">
<?php
while (list($id, $name, $description, $price) = mysql_fetch_row($rs)) {
?>
<tr>
<td height="46" align="left" valign="middle"><p><strong> Producto :
<?= htmlspecialchars($name) ?>
</strong>
</p></td>
</tr>
<tr>
<td height="172" align="left" valign="middle"><p><strong>Descripcion :</strong></p>
<p>
<strong>
<?= htmlspecialchars($description) ?>
</strong></p></td>
</tr>
<tr>
<td height="67" align="left" valign="middle"><p><strong>Precio :
<?= htmlspecialchars($price) ?> </strong>
</p></td>
</tr>
<tr>
<td height="109" align="center" valign="middle"><strong><? echo "Comprar" ?> </strong></td>
</tr>
<?php
}
?>
</table>
<table border="0" cellpadding="5" align="center">
<tr>
<td><strong>Pagina : </strong></td>
<?php
for ($i = 1; $i <= $total_pages; $i++) {
$txt = $i;
if ($page != $i)
$txt = "$txt";
?>
<td align="center"><?= $txt ?></td>
<?php
}
?>
</table>
I have no idea where's the error on it...
Ty for the help :)
Obiusly you have to :
<?php session_start();?>
include your database
etc

You have in the style:
body {
background-image: url();
}
which is causing the browser to request the page again, which adds it to the cart again.
Instead of rendering the cart page, Once the code has modified the cart it should send a redirect to the cart page.

Related

Dynamic add to cart

I have add to cart already but I don't want to reload the page when I click Add to Cart Button so I can still choose other products even its not reloading the page.
Index.php
<?php
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}else{
$sql_p="SELECT * FROM products WHERE product_id={$id}";
$query_p=mysqli_query($con, $sql_p);
if(mysqli_num_rows($query_p)!=0){
$row_p=mysqli_fetch_array($query_p);
$_SESSION['cart'][$row_p['product_id']]=array("quantity" => 1, "price" => $row_p['product_price']);
}else{
$message="Product ID is invalid";
}
}
}
?>
product.php
<?php
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}else{
$sql_p="SELECT * FROM products WHERE product_id={$id}";
$query_p=mysqli_query($con, $sql_p);
if(mysqli_num_rows($query_p)!=0){
$row_p=mysqli_fetch_array($query_p);
$_SESSION['cart'][$row_p['product_id']]=array("quantity" => 1, "price" => $row_p['product_price']);
}else{
$message="Product ID is invalid";
}
}
}
?>
<h1>Products</h1>
<?php
if(isset($message)){
echo "<h2>$message</h2>";
}
?>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Items Price</th>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM products WHERE product_category= 'Chicken' ORDER BY product_name ASC");
while($row=mysqli_fetch_assoc($query)){
?>
<tr>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo $row['product_description']; ?></td>
<td><?php echo "$" . $row['product_price']; ?></td>
<td>Add to Cart</td>
</tr>
<?php
}
?>
</table>
Cart.php
<?php
if(isset($_POST['submit'])){
if(!empty($_SESSION['cart'])){
foreach($_POST['quantity'] as $key => $val){
if($val==0){
unset($_SESSION['cart'][$key]);
}else{
$_SESSION['cart'][$key]['quantity']=$val;
}
}
}
}
?>
<h1>View Cart || Products</h1>
<form method="post" action="index.php?page=cart">
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Subtotal</th>
</tr>
<?php
$sql = "SELECT * FROM products WHERE product_id IN(";
foreach($_SESSION['cart'] as $id => $value){
$sql .=$id. ",";
}
$sql=substr($sql,0,-1) . ") ORDER BY product_id ASC";
$query = mysqli_query($con, $sql);
$totalprice=0;
if(!empty($query)){
while($row = mysqli_fetch_array($query)){
$subtotal= $_SESSION['cart'][$row['product_id']]['quantity']*$row['product_price'];
$totalprice += $subtotal;
?>
<tr>
<td><?php echo $row['product_name']; ?></td>
<td><input type="text" name="quantity[<?php echo $row['product_id']; ?>]" size="6" value="<?php echo $_SESSION['cart'][$row['product_id']]['quantity']; ?>"> </td>
<td><?php echo "$" .$row['product_price']; ?></td>
<td><?php echo "$" .$_SESSION['cart'][$row['product_id']]['quantity']*$row['product_price']. ".00"; ?></td>
</tr>
<?php
}
}else{
?>
<tr><td colspan="4"><?php echo "<i>Add product to your cart."; ?></td></tr>
<?php
}
?>
<tr>
<td colspan="3">Total Price: <h1><?php echo "$" ."$totalprice". ".00"; ?></h1><td>
</tr>
</table>
<br/><button type="submit" name="submit">Update Cart</button>
</form>
<br/><p>To remove an item, set quantity to 0.</p>
//how to solve this please all kind guys can direct change code, my error is undifined offset value of product_id
<?php
include('dataconn.php');
$result=mysql_query("select * from product");
while($row=mysql_fetch_assoc($result))
{
echo "<p>$row[Product_Name]</p>";
echo "<p>$row[Product_Quantity]</p>";
echo "<p>Add To Cart</p>";
}
?>
logout
/*--add to cart page--*/
<?php
/* ----------- ADD TO CART PAGE ----------------*/
include("dataconn.php");
$product_id = isset($_GET['pid']) ? $_GET['pid'] : null;
$action = isset($_GET['action']) ? $_GET['action'] : null; //the action
$quantity=isset($_GET['qty']) ? $_GET['qty'] : null;
?>
<html>
<head>
<title>View Cart</title>
</head>
<body>
<?php
$customer_id=$_SESSION['customer_id'];
$result=mysql_query("select * from product");
$row=mysql_fetch_assoc($result);
switch($action)
{
//decide what to do
case "add":
$_SESSION['cart'][$product_id]++;
break;
case "remove":
$_SESSION['cart'][$product_id] = 0;
unset($_SESSION['cart'][$product_id]);
header("Location: payment.php");//if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
header("Location: payment.php");
break;
}
//------- for checkout ---------
if(isset($_SESSION['cart']) && $_SESSION['cart']) {
$total = 0;
echo "<form name='cart' method='POST' action=''>";
echo "<table border=\"1\" padding=\"3\" width=\"100%\" class=\"data-container\">";
echo "<td colspan=\"4\" align=\"right\"><img src=\"image/delete.png\"/></td>";
foreach($_SESSION['cart'] as $product_id => $quantity)
{
$sql = sprintf("SELECT * FROM product WHERE Product_ID = %d;", $product_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$itemsInfo = mysql_fetch_assoc($result);
$cost = $itemsInfo["Product_Price"] * $quantity;
$total = $total + $cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">".$itemsInfo["Product_Name"]."</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity </td>";
echo "<td align=\"center\">RM $cost</td>";
echo "<td align=\"center\"><img src=\"image/remove.png\"/></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" ></td>";
echo "<td align=\"center\">Total</td>";
echo "<td colspan=\"2\" align=\"center\">RM $total</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
?>
<br>
<div>
<span style="margin-left: 88%"><input type="submit" name="shopping_more" class="custom-button" value="Back To Shopping"/></span>
</div>
</html>

Table pagination not going to a different page when selected

I added pagination to a table a I created a while back and I have not ever been able to get it to work correctly since.
The table limit works, but that's it. If I select "First, Last or the page number" it just reloads the page, but the new page does not display.
If I set the page limit to a low number like 5 and select 'Last Page', when the page loads it shows =1 like it doesn't know there are other pages.
<?php
$con = mysqli_connect("localhost","root","","bfb");
$per_page=20;
if(isset($_POST["page"])) {
$page = $_POST["page"];
}
else {
$page = 1;
}
//Page will start from 0 and multiply per page
$start_from = ($page-1)*$per_page;
//Selecting the data from the table but with limit
$query = "SELECT * FROM orders LIMIT $start_from, $per_page";
$result = mysqli_query($con, $query);
?>
<table class="tableproduct">
<tr>
<th class="thproduct">Order ID</th>
<th class="thproduct">Customer Name</th>
<th class="thproduct">Product</th>
<th class="thproduct">Total Price</th>
<th class="thproduct"></th>
<th class="thproduct"></th>
</tr>
<?php
if( $result ){
while($row = mysqli_fetch_assoc($result)) :
?>
<form method="POST" action="orderhistory.php">
<tr>
<td class="tdproduct"><?php echo $row['order_id']; ?> </td>
<td class="tdproduct"><?php echo $row['customer_name']; ?> </td>
<td class="tdproduct"><?php echo $row['product_name']; ?> </td>
<td class="tdproduct"><?php echo $row['total_price']; ?> </td>
<td class="tdproduct"><a href='editorderhistory.php?id=<?php echo $row['id']; ?>'>EDIT</a></td>
<input type="hidden" name="product_id" value="<? echo $row['id']; ?>"/>
<td class="tdproduct"><input name="delete" type="submit" value="DELETE "/></td>
</tr>
</form>
<?php
endwhile;
}
?>
</table>
<?php
//Count the total records
if ($result != false) {
$total_records = mysqli_num_rows($result);
if ($total_records == 0) {
echo 'No results founds.';
}
}
//Using ceil function to divide the total records on per page
$total_pages = ceil($total_records /$per_page);
?>
<span class="spandarkblue">
<?php
//Going to first page
echo "<center><a href='orderhistory.php?page=1'>".'First Page'."</a> ";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='orderhistory.php?page=".$i."'>".$i."</a> ";
};
// Going to last page
echo "<a href='orderhistory.php?page=$total_pages'>".'Last Page'."</a></center>";
?>
Any ideas?
Found below issues in you code.
1) You are trying to get page value from URL using POST, where as you need to GET method to fetch values from URl. Using POST is returning null value, so $page value is always set to 1
So use $_GET["page"] instead of $_POST["page"]
2) You are preparing pagination by considering row count of the query which you are executing. But as you have added limits , your $total_records is always equals to $per_page value or less, resulting in only one page number.
Use the following code for generate pazination
$query1 = "SELECT count(*) as totalRecords FROM orders";
$result1 = mysqli_query($con, $query1);
if ($result1) {
$row1 = mysqli_fetch_assoc($result1);
$total_records = $row1['totalRecords'];
if ($total_records == 0) {
echo 'No results founds.';
}
}
Instead of below code
if ($result != false) {
$total_records = mysqli_num_rows($result);
if ($total_records == 0) {
echo 'No results founds.';
}
}
Hope it helps you.
You need to fetch all the data to know the total of your records, then you show only the desired data whithin a for() loop, so remove LIMIT $start, $per_page from your query, in this node you will always have 20 or less results
In your while() save the data in arrays like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
$ordID[$index] = $row["order_id"];
// The rest of your data...
$index++; // Increment the index
}
Then you chan show only the desired data:
for($i = (($page-1)*$perPage); $i < min(($page*$perPage), $total); $i++) {
echo $orderID[$i];
// And so on...
}
The min() function returns the lowest value between two vars, in this way in the last page, if you have 17 products instead of 20 you will not have errors.

Manipulating individual products in MySQL table

I am working on a small orders cart and currently I have implemented MySQL to display products from a database. I want these products to have their own images and to be organised into 3 separate tables for starters, mains and desserts.
Currently I have one table for all items and I am unsure how to add an image next to a selected product.
Shown here:
Here is my code:
<?php
session_start();
$page = 'index.php';
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('cart') or die(mysql_error());
if (isset($_GET['add'])) {
$quantity = mysql_query('SELECT id, quantity FROM products WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while ($quantity_row = mysql_fetch_assoc($quantity)) {
if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]) {
$_SESSION['cart_' . (int)$_GET['add']] +='1';
header('Location: ' . $page);
}
}
header('Location: ' . $page);
}
if (isset($_GET['remove'])) {
$_SESSION['cart_'.(int)$_GET['remove']]--;
header ('Location: ' . $page);
}
if (isset($_GET['delete'])) {
$_SESSION['cart_' . (int)$_GET['delete']]='0';
header ('Location: ' . $page);
}
function products() {
$get = mysql_query('SELECT id, name, description, price FROM products WHERE quantity > 0 ORDER BY id ASC');
if (mysql_num_rows($get) == 0) {
echo "There are no products to display.";
}
else {
echo "<center>\n";
echo " <table border=2 width=40% cellspacing=5 cellpadding=10 bgcolor=cyan cols=2>\n";
echo " <tr>\n";
echo " <th>View</th>\n";
echo " <th>Dish</th>\n";
echo " <th>Description</th>\n";
echo " <th>Item Price</th>\n";
echo " </tr>\n";
while ($get_row = mysql_fetch_assoc($get)) {
?>
<tr>
<td> <a href="ice.png"</a> </td>
<td> <?echo '<p>'.$get_row['name']?> </td>
<td> <?echo $get_row['description']?> </td>
<td> <?echo '&pound'.number_format($get_row['price'],2).'<br><br> Add</p>';?> </td>
</tr>
<?
}
echo "</table>\n";
echo "</center>\n";
}
}
You can add a field to a table with a type of product.
So you will be able to perform 3 separate queries with the condition.
For Example
SELECT
id,
name,
description,
price
FROM
products
WHERE
quantity > 0
AND type LIKE 'desert'
ORDER BY id ASC
and so on

php issues adding product to shopping cart

I'm having issues adding products to my shopping cart. In order to read it easier I'm only posing the php code. I'm not worried about security issues at this point, just looking to correct the issue with the product not showing up in the cart on the page view_cart.php . Can anyone see what I'm missing here? Also, the session is started on another page prior to them reaching this point.
<?php # add_cart.php
// This page adds beers to the shopping cart.
if (isset($_GET['beer_id'])) { // Check for a beer ID.
$beer_id = $_GET['beer_id'];
// Check if the cart already contains one of these beers;
// If so, increment the quantity:
if (isset($_SESSION['cart'][$beer_id])) {
echo '<p> same beer </p>';
$_SESSION['cart'][$beer_id]['quantity']++; // Add another.
// Display a message:
echo '<p> This brew was already in your cart so we added another to your shopping cart. </p>';
} else { // New product to the cart.
require ('mysqli_connect.php'); // Connect to the database.
$q = "SELECT price FROM beer WHERE beer_id='" . $beer_id . "'";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid beer_ID.
// Fetch the information.
list($price) = mysqli_fetch_array ($r, MYSQLI_NUM);
// Add to the cart:
$_SESSION['cart'] = array('quantity' => 1, 'price' => $price);
echo $_SESSION['cart'][$beer_id][$r];
// Display a message:
echo '<p>' . $beer_id . 'has been added to your shopping cart.<br/>Go to Cart or Keep Shopping</p>';
} else { // Not a valid beer_ID.
echo '<div align="center">This page has been accessed in error!</div>';
}
mysqli_close($dbc);
}
}// End of isset conditional.
else { // No beer_ID.
echo '<div align="center">This page has been accessed in error!</div>';
}
?>
The page below is called from add_cart.php
<?php
# view_cart.php
// Check if the form has been submitted (to update the cart):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Change any quantities:
foreach ($_POST['quantity'] as $k => $v) {
$beer_id = (int) $k;
$qty = (int) $v;
if ( $qty == 0 ) { // Delete.
unset ($_SESSION['cart'][$beer_id]);
} elseif ( $qty > 0 ) { // Change quantity.
$_SESSION['cart'][$beer_id]['quantity'] = $qty;
}
} // End of FOREACH.
} // End of SUBMITTED IF.
// Display the cart if it's not empty...
if (!empty($_SESSION['cart'])) {
// Retrieve information for beers in cart:
require ('mysqli_connect.php'); // Connect to the database.
$q = "SELECT beer_id, name, price FROM beer WHERE beer_id ='".$beer_id."'";
/*foreach ($_SESSION['cart'] as $beer_id => $value) {
$q .= $beer_id . ',';
}*/
$q = substr($q, 0, -1) . ') ORDER BY beer_id ASC';
$r = mysqli_query ($dbc, $q);
// Create a form and a table:
echo '<form action="view_cart.php" method="post">
<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
<td align="left" width="30%"><b>ID</b></td>
<td align="left" width="30%"><b>Name</b></td>
<td align="right" width="10%"><b>Price</b></td>
<td align="center" width="10%"><b>Qty</b></td>
<td align="right" width="10%"><b>Total Price</b></td>
</tr>
';
// Print each item...
$total = 0; // Total cost of the order.
while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {
// Calculate the total and sub-totals.
$subtotal = $_SESSION['cart'][$row['beer_id']]['quantity'] * $_SESSION['cart'][$row['beer_id']]['price'];
$total += $subtotal;
// Print the row:
echo "\t<tr>
<td align=\"left\">{$row['name']}</td>
<td align=\"right\">\${$_SESSION['cart'][$row['beer_id']]['price']}</td>
<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['beer_id']}]\" value=\"{$_SESSION['cart'][$row['beer_id']]['quantity']}\" /></td>
<td align=\"right\">$" . number_format ($subtotal, 2) . "</td>
</tr>\n";
} // End of the WHILE loop.
mysqli_close($dbc); // Close the db connection.
// Print the total, close the table, and the form:
echo '<tr>
<td colspan="4" align="right"><b>Total:</b></td>
<td align="right">$' . number_format ($total, 2) . '</td>
</tr>
</table>
<div align="center"><input type="submit" name="submit" value="Update My Cart" /></div>
</form><p align="center">Enter a quantity of 0 to remove an item.
<br /><br />Checkout</p>';
} else {
echo '<form action="view_cart.php" method="post">
<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
<td align="left" width="10%"><b>ID</b></td>
<td align="left" width="30%"><b>Name</b></td>
<td align="right" width="30%"><b>Price</b></td>
<td align="center" width="10%"><b>Qty</b></td>
<td align="right" width="10%"><b>Total Price</b></td>
</tr></table>
';
echo '<p>Your cart is currently empty.</p>';
}
?>

PHP MySQL Shopping Cart - Adding items to session

I am practicing with PHP, and as a result, I ended up creating a dummy online store. I managed to implement most of the online functionality, but I am struggling with the shopping cart.
Once the user logs in and enters the product area of the site, I want the user to be able to add items to a cart. I have been following a phpAcademy YouTube tutorial. I've managed to display all the products with an add button/hyperlink to link each product to a processing page called cart.php. Each button's link matches their associated product ID.
When I test this and click "add", the ID of the product does not appear on the cart.php page.
user_man_boxing_gloves.php:
<?php
session_start();
include('connect_mysql.php');
$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';
$get = mysql_query("SELECT product_id, product_image, product_name, product_des, product_price, product_type FROM products WHERE product_type='ManGloves' AND product_qua > 0 ORDER BY product_id DESC");
if(mysql_num_rows($get) == 0)
{
echo "There are no Products to display";
}
else
{
?>
<?php
while($get_row = mysql_fetch_assoc($get))
{
?>
<table id='display'>
<tr><td><?php echo "<img src=$get_row[$product_image] class='grow'>" ?></td></tr>
<tr>
<th></th>
<th><strong>Avalible</strong></th>
<th><strong>Price</strong></th>
<th><strong>Description</strong></th>
</tr>
<tr>
<td width='290px'><?php echo "$get_row[$product_name]" ?></td>
<td width='290px'><?php echo "$get_row[$product_qua]" ?></td>
<td width='290px'><?php echo "$get_row[$product_price]" ?></td>
<td width='290px'><?php echo "$get_row[$product_des]" ?></td>
</tr>
<tr>
<td><?php echo 'Add'; ?></td>
</tr>
</table>
<?php
}
}
?>
cart.php:
<?php
if(isset($_GET['add'])){
$_SESSION['cart_'.$_GET['add']]+='1';
}
echo $_SESSION['cart_'];
?>
I want to display the product ID to see if my code works, and I want to do further processing after verifying that it works.
Looking at the screenshot, it appears that the add button correctly shows the product ID.
It looks like the issue in cart.php deals with the following snippet:
if(isset($_GET['add'])){
$_SESSION['cart_'.$_GET['add']]+='1';
}
Working this out, this would mean that with an ID of 1, you could see the following in your session array:
$_SESSION['cart_1'] = 1;
$_SESSION['cart_2'] = 4;
What you probably want, for the display, is to store an array into cart. That is,
if(isset($_SESSION['cart']))
{
$arr = unserialize($_SESSION['cart']);
}
else
{
$arr = array();
}
if(isset($_GET['add'])){
$arr[$_GET['add']] += 1;
}
$_SESSION['cart'] = serialize($arr);
var_dump(unserialize($_SESSION['cart']));

Categories