php shopping cart display error - php

First of all, i am sorry if this question has been asked before.I am working on a shopping cart. My current code will only show 1 item in the cart. It means that when i click add to cart on #product1 it will show me #product1 detail in the cart. However when i click add to cart for #product2, it will override the information of #product1.
Here is my code for product:
<div >
<image src="ip5s.jpg">
<p><font color="blue">&nbsp&nbspIphone 5S</font></p>
<p><font color="red">&nbsp&nbspRM1999</font></p>
<p><form name="addcart" method="post" action="processcart.php">
<input type="submit" name="addtocart" value="Add to cart">
<input type="hidden" name="product_id" value="1234" />
<input type="hidden" name="quantity" value="1" />
</form>
</p>
</div>
Here is the code for process.php:
<?php
session_start();
include_once("config.php");
$pid=$_POST['product_id'];
$_SESSION['product'] = array($pid);
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
Here is the code for cart.php:
<?php
if(!isset($_SESSION['cart']))
echo "<p>Your shopping cart is empty!</p>";
else{
$tblname="products";
require_once("dbcon.php");
$proids = array();
foreach($_SESSION['product'] as $id)
{
$proids[] = $id;
}
$proids = implode(',', $proids);
$query = "SELECT * from $tblname where product_id in ('$proids') ";
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
echo "<tr><td>" . $row[$i]['product_name'] . "</td><td>" . $row[$i]['product_price'] . "</td></tr>" ;
}
echo "</table>";
mysql_free_result($result);
mysql_close();
}

Add session_start() to the beginning of cart.php to resume the session.
Also, in order to add multiple product IDs to the $_SESSION['product'] variable, which is probably what you'll be doing, you'll have to change
$_SESSION['product'] = array($pid);
to
$_SESSION['product'][] = $pid;
Which inserts $pid to the end of $_SESSION['product'] array.

USE array_push() .make an array with card Ids and display them using forloop
<?php
session_start();
include_once("config.php");
$pid = $_POST['product_id'];
$_SESSION['product'] = array();
$_SESSION['product'] = array_push($_SESSION['product'], $pid);
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
Try
<?php
session_start();
if(isset($_SESSION['quantity']))
$_SESSION['quantity']=$_SESSION['quantity']+1;
else
$_SESSION['quantity']=1;
echo "Cart=". $_SESSION['quantity'];
?>

As you seem to be really stuck on this:
process_cart.php
<?php
session_start();
include_once("config.php");
// test & generate cart if needed
if(! isset($_SESSION['cart']))
{
$_SESSION['cart'] = array("products"=>array());
}
// add current product
// ! note: you need to add data validation to this to avoid SQL injects
$_SESSION['products'][$_POST['product_id']] = $_POST['quantity'];
// Show you have done something
sleep(2);
echo "Add to cart successful";
header("refresh:1;url=cart.php");
exit();
?>
databaseConnection.php
<?php
define("DB_HOST", "localhost");
define("DB_NAME", "onlinestore");
define("DB_USER", "root");
define("DB_PASSWORD", "");
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME);
?>
cart.php:
<?php
session_start();
if (!isset($_SESSION['cart']))
{
// No items yet added to the cart
echo "<p>Your shopping cart is empty!</p>";
}
else
{
// set table
$tblname = "products";
// get connection
require_once('DatabaseConnection.php');
// create a list with product ID's
$prodids = array();
// For each product in the cart
foreach($_SESSION['cart']['products'] as $id => $qntity)
{
// add id to the array
$prodids[] = $id;
}
// combine into a string
$prodids = implode(',', $prodids);
$query = "SELECT * from $tblname where product_id in ($prodids) ";
// (The query should really be mysqli)
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr><td>" . $row['product_name'] . "</td><td>" . $row['product_price'] . "</td></tr>". $_SESSION['cart']['products'][$row['product_id']];
}
echo "</table>";
mysql_free_result($result);
mysql_close();
?>

Related

Declaring Variable Runs Variable

I am trying to create a functioning search field using ProductID, then using this to display the row in the product table where the ProductID exists. The problem I am having is that if I have the code as follows: The submit button below executes the $deleteprod and $deltesale code which all it should (from my understanding) is submit the ProductID variable.
<form action="delete.php" method="post">
<input value="" placeholder="Product ID" name="ProductID" type="text"/> <br>
<input type="submit" onclick="" value="Search"/
</form>
<?php
$ProductID = $_POST['ProductID'];
$db = mysql_connect("localhost:3307", "root", "usbw");
$deleteprod = mysql_query("DELETE FROM gameshop.product WHERE (product.ProductID = '$ProductID')");
$deletesale = mysql_query("DELETE FROM gameshop.sale WHERE (sale.ProductID = '$ProductID')");
$deletebutton = "<button onclick=\"$deletesale; $deleteprod; location.href='database.php'\" style='width:200px; background-color:red;'>Delete Row</button>";
mysql_select_db("gameshop",$db);
$result = mysql_query("SELECT product.*, sale.Price
FROM gameshop.product, gameshop.sale
WHERE (product.ProductID = '$ProductID' AND sale.ProductID = '$ProductID')",$db);
if (!$result){
print mysql_rror();
}
elseif ($myrow = mysql_fetch_array($result)){
echo "<table style='text-align:center;' border=1>\n";
echo "<tr><td>Product ID</td><td>Product Name</td>", "<td>Publisher</td><td>Developer</td>", "<td>Release Date</td><td>Stock</td>", "<td>Console</td> <td>Rank</td><td>Price</td><td>Delete?</td></tr>\n";
do{
printf("<tr><td>%4d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%1d</td><td>%s</td><td>%1d</td><td>%2d</td><td>%s</td></tr>\n", // %s are syntax (string)
$myrow["ProductID"], $myrow["ProductName"], $myrow["Publisher"], $myrow["Developer"], $myrow["ReleaseDate"], $myrow["Stock"], $myrow["Console"], $myrow["Rank"], $myrow["Price"], $deletebutton);
}
while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
}
mysql_close($db);
?>
If I were to move the $db = MySQL_connect("localhost:3307", "root", "usbw"); to below the $delete variables, this problem does not occur and it creates the single row table. However when attempting to click on the $deletebutton, the code does not execute and no row is deleted.
What am I doing wrong?
the problem is, when you click the button you call JavaScript, not PHP.
I think you could solve it making another PHP page with your deletesale and deleteprod which takes Product_ID with post.
so this file would have a php script like this:
$ProductID = $_POST['ProductID'];
$db = mysql_connect("localhost:3307", "root", "usbw");
mysql_select_db("gameshop",$db);
$result = mysql_query("SELECT product.*, sale.Price
FROM gameshop.product, gameshop.sale
WHERE (product.ProductID = '$ProductID' AND sale.ProductID = '$ProductID')",$db);
if (!$result){
print mysql_error();
}
elseif ($myrow = mysql_fetch_array($result)){
echo "<table style='text-align:center;' border=1>\n";
echo "<tr><td>Product ID</td><td>Product Name</td>", "<td>Publisher</td> <td>Developer</td>", "<td>Release Date</td><td>Stock</td>", "<td>Console</td> <td>Rank</td><td>Price</td><td>Delete?</td></tr>\n";
do{
printf("<tr><td>%4d</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%1d</td><td>%s</td><td>%1d</td><td>%2d</td><td>",$myrow["ProductID"], $myrow["ProductName"], $myrow["Publisher"], $myrow["Developer"], $myrow["ReleaseDate"], $myrow["Stock"], $myrow["Console"], $myrow["Rank"], $myrow["Price"]);
printf "<form method=\"post\" action=\"delete_page.php\"><input type=\"text\" style=\"display:none\" name=\"ProductID\" value=\"$ProductID\"/><input type=\"submit\" value=\"delete product\"/></form>"
printf "</td></tr>"
}
while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
}
mysql_close($db);
and then you would have delete_page.php with
$ProductID = $_POST['ProductID'];
$db = mysql_connect("localhost:3307", "root", "usbw");
mysql_select_db("gameshop",$db);
mysql_query("DELETE FROM gameshop.product WHERE (product.ProductID = '$ProductID')");
mysql_query("DELETE FROM gameshop.sale WHERE (sale.ProductID = '$ProductID')");
mysql_close($db);
then you can add a link back to the main page.
Be sure to check for typos :)

My Sessions Keeps Sending a Fixed Value while it's supposed to be changeable

Well i got this script
while($row = $result->fetch_assoc()) {
$_SESSION["sup"] = $row['id'];
if ($hi < $row['buytime']) {
} else {
echo " <form action='Action1.php' method='get'>
Thanks for buying from our shop , if the item with id <input type='submit' value='" . $row['id'] ."' class='btn-link'/> </form>";
echo "<form action='Action.php' method='post'>
is a bad tool , you can report by clicking on the following button <input type='submit' value='Report Item' />
</form>";
}
}
The only problem is hat in line $_SESSION["sup"] = $row['id'];
Keeps sending a fixed value which it's 144 while the $row['id']; is not a fixed value , i'm really lost lol
If session is a bad idea , how can i send ID to action.php without inserting the ID in a hidden input ?
Update the two pages
First PAge
<?php
$conn = mysqli_connect("localhost", "localhost", "localhost", "localhost");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$buyer = $_SESSION['username'];
$sql_shells = "SELECT buytime,id,situation,buyer FROM shells WHERE situation = 'sold' AND buyer = '$buyer' ";
$dt = new DateTime();
$dt->modify('+172799 seconds');
$hi = $dt->format('Y-m-d H:i:s');
$_SESSION["sup"] = [];
$result = $conn->query($sql_shells);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION["sup"][] = $row['id'];
$_SESSION["sup"] = implode(',', $session['sup']); // use this var
if ($hi < $row['buytime']) {
}else{
echo " <form action='view_item.php' method='get'>
Thanks for buying from our shop , if the item with id <input type='submit' value='" . $row['id'] ."' class='btn-link'/> </form>";
echo "<form action='reportinsert.php' method='post'>
is a bad tool , you can report by clicking on the following button <input type='submit' value='Report Item' />
</form>";
}
}
}else {
}
?>
Second page
<?php
session_start();
if (isset($_SESSION['username'])) {
$link = mysqli_connect("localhost", "localhost", "localhost", "localhost");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$trn_date = date("Y-m-d H:i:s");
$seller = $_SESSION['username'];
$id = $_POST['whatever'];
$id = explode(',', $id); // You now have an array of IDs.
$sql = "INSERT INTO reports (reporter,stats,trn_date,itemid) VALUES ('$seller','Opened','$trn_date','$id')";
if(mysqli_query($link, $sql)){
echo $id;
echo $seller;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
} else
{
header("location:/quickshops/login.php");
}
?>
now it gives me Array in insert
Remove inside $row '' from $row['id'].
You will always get the last row's value, the reason is, you set the session in each iteration so whenever you plan to use it out of the loop, you will get the value of last iteration.
In case you want to set the array within the session, that's how you can do that:
$idsArray= array();
while($row = $result->fetch_assoc()) {
$idsArray[] = $row['id'];
}
$_SESSION["ids"] = $idsArray;
You are rewriting the value every time you go through the loop:
// loop through results
while($row = $result->fetch_assoc()) {
// overwrite session variable with the last id
$_SESSION["sup"] = $row['id'];
So if you have 10 results, the session var will be the id of the 10th row.
Without more detail on what you are trying to achieve with your result set, we can't really help much more than that. Maybe update your question with more details if this isn't enough to solvce your problem?
Update Ok so you need ALL Id's
You could make the session var an array, and when it's time to post the ID's, implode() them with a comma. Then in the receiving script, explode on a comma to get all the ids.
$_SESSION["sup"] = [];
while($row = $result->fetch_assoc()) {
$_SESSION["sup"][] = $row['id'];
// etc
}
$_SESSION["sup"] = implode(',', $session['sup']); // use this var
And in the other script
$ids = $_POST['whatever'];
$ids = explode(',', $ids); // You now have an array of IDs.
Incidentally, since you are using a session variable, you probably don't even need to post it, and just access the session in the other script, but then I've no idea what your code is doing

save order cart session to database

I was wondering if anyone can help me save the shopping cart to a database? ive looked all online but havent found anything.
im trying to save an ordering form (for a mock restaurant) to the db after the user adds the items to the cart and proceeds to the pay function which already directs them to paypal screen. So basically, im trying to save the dishes the user selects and the price/qty to the database,address along with an order id.
In the database i have a table called dishes (Id,name,Description,Price and Quantity).
Many Thanks
below is the php session code.
<?php
session_start();
$page = 'ordering.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 dishes 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) ;
}
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 dishes(){
$get = mysql_query('SELECT id, name, description, price FROM dishes WHERE quantity > 0 ORDER BY id DESC');
if (mysql_num_rows($get)==0) {
echo "There are no dishes to display!";
}
else {
while ($get_row = mysql_fetch_assoc($get)) {
echo '<p>'.$get_row['name'].'<br />'.$get_row['description'].'<br />€'.number_format($get_row['price'], 2).' Add</p>';
}
}
}
function cart() {
$total = 0;
foreach($_SESSION as $name => $value) {
if ($value>0) {
if (substr ($name, 0, 5)=='cart_'){
$id = substr($name, 5, strlen ($name)-5);
$get = mysql_query('SELECT id, name, price FROM dishes WHERE id='.mysql_real_escape_string((int)$id)) ;
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo $get_row['name'].' x '.$value.' # €'.number_format($get_row['price'], 2). ' = €'.number_format($sub, 2).' [-] [+] [Delete]<br />';
}
}
$total += $sub;
}
}
if ($total == 0) {
echo "no items.";
}
else {
echo 'Total: €'.number_format($total, 2).'</p>';
?>
<html>
<p>
<form action='viewcart.php' method='POST'>
<input type='submit' name='view' value='Confirm'>
</p>
<?php
}
}
?>
This is the html file to display the dishes and cart.
<div class="callout">
<aside class="sidebar">
<br />
<fieldset>
<?php cart(); ?>
</fieldset>
</div>
<br />
<?php dishes (); ?>
</body>
<?php include 'footer.html'; ?>
</html>
im trying to save it but im getting a id per item and i want a id per order and also i wanted the total price but its coming back empty
here is my code for inserting into database
function orders() {
foreach($_SESSION as $name => $value) {
if ($value !=0) {
if (substr ($name, 0, 5)=='cart_'){
//-5 so it = to the id number
$id = substr($name, 5, strlen ($name)-5);
$get = mysql_query('SELECT id, name, price FROM dishes WHERE id='.mysql_real_escape_string((int)$id));
while ($Get_row = mysql_fetch_assoc($get)) {
echo '<input type="text" name="item_name_'.$num.'" value="'.$Get_row['name'].'">';
echo '<input type="text" name="amount_'.$num.'" value="'.$Get_row['price'].'">';
echo '<input type="text" name="quantity_'.$num.'"value="'.$value.'">';
echo '<input type="text" name="total_'.$num.'"value="'.$total.'">';
if(mysql_query("INSERT INTO orders (name,quantity,price) VALUES ('$name','$value','$price')"))
echo"successfully inserted";
else
echo "failed";
}
}
}
}
}
You need an order table and an order details table, when customers place an order, you
insert an new order with customer information and new orderid ,amount paid,....
Insert every cart item, quantity,price to the details table, with the order id
Clear session content.

Sessions and variables not persisting over multiple pages

The sessions between multiple pages on my site is not persisting. This it the session code I have at the start of each page:
<?php
#session_start();
echo session_id();
?>
I then add the variables to the session:
$_SESSION["CustomerID"]= $IDCustomer;
$_SESSION["PaymentID"]= $IDPayment;
var dumping this directly afterwards shows the correct variable. however, when doing the exact same on the next page, the variables are NULL. The only thing I have done between var dumping the variables on the first page, and var dumping them on the second page is clicking the hyperlink to switch the pages.
This is the code in full for each page:
<?php
require_once("php/init.php");
echo session_id();
$Cat = $_GET['Type'];
//create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
//show the connection string
$connStr = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source= \www\DMG Games Website\DMG Database.accdb";
$conn->open($connStr); //Open the connection to the database
//Read customer + payment from $Get
//Store in session variables
$IDCustomer = $_GET['CustomersDropdown'];
$IDPayment = $_GET['PaymentsDropdown'];
$_SESSION["CustomerID"]= $IDCustomer;
$_SESSION["PaymentID"]= $IDPayment;
//create the Products query
$query = "SELECT * FROM [Product Details]";
if (isset($Cat)) {
$query = "SELECT * FROM [Product Details] Where [Product Type] ='" . $Cat . "'";
}
//execute query
$rs = $conn->execute($query);
//count the number of columns
$num_columns = $rs->Fields->Count();
echo "There are " . $num_columns . " columns." . "<br>";
for ($i=0; $i < $num_columns; $i++) {
$fld[$i] = $rs->Fields($i);
}
//show the information in a table
echo "<table>";
echo "<tr>";
echo "<th> Product ID </th>";
echo "<th> Product Name </th>";
echo "<th> Product Description </th>";
echo "<th> Price </th>";
echo "<th> Quantity In Stock </th>";
echo "<th> Product Type </th>";
echo "<th> Image </th>";
echo "<th> Click to Buy </th>";
echo "</tr>";
while (!$rs->EOF) //carry on looping while there are records to be obtained
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $fld[$i]->value . "</td>";
}
echo "</tr>";
$rs->MoveNext(); //move on to the next record
}
echo "</table>";
//close the connection
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
$Customer = $_SESSION["CustomerID"];
var_dump($Customer);
$Payment = $_SESSION["PaymentID"];
var_dump($Payment)
?>
This is the code for the second page:
//create an instance of the ADO connection object
$conn = new COM ("ADODB.Connection")
or die("Cannot start ADO");
//show the connection string
$connStr = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source= \www\DMG Games Website\DMG Database.accdb";
$conn->open($connStr); //Open the connection to the database
// Get the url variables
$Pid = $_GET['newPid'];
// Read the quantity from the address
$Quantity = $_GET['newQuantity'];
//Create a query for retreiving the product image
$queryGetImage = "SELECT [Image] FROM [Product Details] Where [Product ID]=" . $Pid;
//execute the query
$rs = $conn->execute($queryGetImage);
echo "<h2> Add product to basket </h2>";
echo "</br></br>";
echo $rs->Fields("Image");
echo "</br></br>";
//declare the form
?>
<FORM NAME ="QuantityForm" METHOD ="get" ACTION = "">
Product ID:</br> <INPUT TYPE = "TEXT" NAME ="newPid" VALUE = "<?php echo $Pid;?>">
</br></br>
Quantity:</br> <INPUT TYPE = "TEXT" NAME ="newQuantity">
</br></br>
<input type="submit" />
</form>
<?php
//Create the AddToBasket query
if (isset($Quantity)) {
// Add the product and the quantity to the basket table
$AddtoBasketQuery = "INSERT INTO Basket([Product ID], [Quantity])
VALUES ('$Pid', '$Quantity')";
//execute the query
$conn->execute($AddtoBasketQuery);
//close the connection
$conn->Close();
$conn = null;
echo "</br> Your product has succesfully been added to your basket.";
}
?>
I don't see
session_start();
on your second script, you need to put it at the top of each script which wants to use session variables
You need to add session_start(); at start in second script. To access the Session variables this is required to start session before doing anything.

The object stored into a PHP session gets the wrong value stored

I have created a shopping cart object that works. But when I try to save the object into the session the wrong content of that object is stored. The value that is being saved is the value after the object is cleared from the shopping cart, the empty one.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Testing the Shopping Cart</title>
</head>
<body>
<?php # cart.php
// This script uses the ShoppingCart and Item classes.
//error_reporting(0);
// Create the cart:
session_start();
try {
require('ShoppingCart.php');
require('userMenu.php');
$cart = new ShoppingCart();
// Create some items:
require('Item.php');
require ('Connect.php');
$conn=Connect::doConnect();
$query = "SELECT product_id, product_name, product_price from product";
$result = mysqli_query($conn, $query);
$i=0;
$w = array();
$new_cart;
if ($result->num_rows > 0) {
// output data of each row
echo '<table border='."1".'><form action="cart.php" method="post"><tr><td>';
echo '<b>'."Id produs".'</td><td><b>'."Denumire".'</td><td><b>'."Pret".'</td><td>'."Numar de bucati solicitate".'</td></tr><tr>';
while($row = $result->fetch_assoc()) {
echo '<td>'.$row["product_id"].'</td><td>'. $row["product_name"].'</td><td>'. $row["product_price"]. '</td><td>
<input type="input" value="0" name="quantity[]"><input type="hidden" value="'.$row["product_id"].'" name="item_adjust[]"></td>';
echo '</tr>';
$i++;
$w[$i]=new Item($row["product_id"], $row["product_name"],$row["product_price"]);
$cart->addItem($w[$i]);
//$cart->deleteItem($w[$i]);
}
echo '</td></tr><tr><td colspan="3"><input type="submit" value="Adauga in cosul de cumparaturi" name="adjQ"></td></tr></table>';
//foreach ()
} else {
echo "0 results";
}
$conn->close();
if($_POST["adjQ"]){
echo "In stoc avem ".$i." tipuri de produse";
// Update some quantities:
$cart_items_new = array_combine($_POST['item_adjust'],$_POST['quantity']);
foreach ($cart_items_new as $product_id=>$quantity){
//$item=new Item($product_id,Item->);
//Item $it;
//->updateItem($item->getId($product_id), $qty);
//$cart->updateItem(getId($product_id), $quantity);
$conn=Connect::doConnect();
$query1 = "SELECT product_id, product_name, product_price from product where
product_id='$product_id'";
$result1 = mysqli_query($conn, $query1);
$row1=mysqli_fetch_array($result1);
if($quantity>0){
$cart->updateItem($w[$product_id], $quantity);
echo $product_id.$quantity."+".$row1["product_name"];
}
else{
$cart->deleteItem($w[$product_id]);
}
}
// Show the cart contents:
echo '<h2>Continutul cosului de cumparaturi (' . count($cart) . ' tipuri de produse)</h2>';
echo "The user is " . $_SESSION["user"] . ".<br>";
echo "User type is " . $_SESSION["user_type"] . ".";
$new_cart = unserialize(serialize($cart));
if (!$cart->isEmpty()) {
foreach ($cart as $arr) {
// Get the item object:
$item = $arr['item'];
// Print the item:
printf('<p><strong>%s</strong>: %d # $%0.2f bucata.<p>', $item->getName(), $arr['qty'], $item->getPrice());
} // End of foreach loop!
} // End of IF.
}
echo '</td></tr><tr><td colspan="2"><input type="submit" value="Salveaza" name="session"></td><td></td></tr></form></table>';
if ($_POST['session'])
{
echo "You entered the number ";
$serialize_cart=serialize($new_cart);
$_SESSION["cart"]=$serialize_cart;
}
}
catch (Exception $e) {
}
?>
</body>
</html>
What I am doing wrong when I push the second submit button.
Hey I've had a go at this
I can't test it as I dont have the additional files and cart object but it should be close to error free
I've got a Session variable 'cart' if present we grab it unserialize and were done then can edit the values and save it back out so on
If not present i.e. first hit or cart was deleted we build a new cart from the database (This isnt ideal just for testing as presently your adding every item from the database to the cart?)
If the post or get value of adjQ is present we modify some of the values of the cart object and save it back out to the session variable
If the post or get value of showCart is present we output the current cart
To make this work you might have to tweak your Shopping_Cart Object to support the variables being called and the getCount function and the getAllRows function
I've removed the additional storage of an array of the items from the cart (w) not sure what thats for since you have the data stored in the object dont need to replicate it
All the request variables should be sanitized to prevent injection attacks n so on
I've added a hidden field to trigger the showCart request
Anyway hope this helps
<?php
session_start();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Testing the Shopping Cart</title>
</head>
<body>
<?php # cart.php
// This script uses the ShoppingCart and Item classes.
//error_reporting(0);
// Create the cart:
require('ShoppingCart.php');
require('userMenu.php');
$rowCount = 0;
if(isset($_SESSION['cart']))
{
echo "We have a stored cart in a Session variable, retrieving data ...";
$cart = unserialize($_SESSION["cart"]);
$rowCount = $cart->getCount();
}
else
{
$cart = new ShoppingCart();
// Create some items:
require('Item.php');
require ('Connect.php');
$conn=Connect::doConnect();
$query = "SELECT product_id, product_name, product_price from product";
$result = mysqli_query($conn, $query);
$rowCount = $result->num_rows;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$cart->addItem(new Item($row["product_id"], $row["product_name"],$row["product_price"]));
}
}
$conn->close();
}
if(isset($_REQUEST['adjQ']))
{
echo "In stoc avem ".$rowCount." tipuri de produse";
// Update some quantities:
$cart_items_new = array_combine($_POST['item_adjust'], $_POST['quantity']);
foreach ($cart_items_new as $product_id=>$quantity) {
if($quantity > 0) {
$cart->updateItem($product_id, $quantity);
$conn=Connect::doConnect();
$query1 = "SELECT product_id, product_name, product_price from product where product_id='$product_id'";
$result1 = mysqli_query($conn, $query1);
$row1 = mysqli_fetch_array($result1);
echo $product_id." ".$quantity." + ".$row1["product_name"];
}
else {
$cart->deleteItem($product_id);
}
}
// Show the cart contents:
echo '<h2>Continutul cosului de cumparaturi (' . $rowCount . ' tipuri de produse)</h2>
The user is ' . $_SESSION["user"] . '.<br>
User type is ' . $_SESSION["user_type"] . '.';
if (!$cart->isEmpty()) {
foreach ($cart as $arr) {
// Get the item object:
$item = $arr['item'];
// Print the item:
printf('<p><strong>%s</strong>: %d # $%0.2f bucata.<p>', $arr['item']->getName(), $arr['item']->getQuantity(), $arr['item']->getPrice());
} // End of foreach loop!
echo "Saving card to Session variable";
//New_cart is only set in adjQ request prehaps this code should be there?
$_SESSION["cart"] = serialize($cart);
} // End of IF.
}
if(isset($_REQUEST['showCart']))
{
if ($cart->getCount() > 0) {
// output data of each row
echo '<table border='."1".'><form action="cart.php" method="post">';
echo '<tr><td><b>'."Id produs".'</td><td><b>'."Denumire".'</td><td><b>'."Pret".'</td><td>'."Numar de bucati solicitate".'</td></tr>';
foreach ($cart->getAllRows() as $row) {
echo '
<tr>
<td>'. $row->getProductId() . '</td>
<td>'. $row->getName() . '</td>
<td>'. $row->getPrice() . '</td>
<td><input type="input" value="0" name="quantity[]"><input type="hidden" value="' . $row->getProductId() . '" name="item_adjust[]"/><input type="hidden" value="showCart" name="showCart"/></td>
</tr>';
}
echo '<tr><td colspan="3"><input type="submit" value="Adauga in cosul de cumparaturi" name="adjQ"></td></tr></table>';
} else {
echo "Cart is empty";
}
}
?>
</body>
</html>

Categories