Shopping cart using PHP - php

I am trying to make a shopping cart.I can add books to the cart and empty whole cart.But I cant remove individual cart items.I could add one item to the cart and remove it using remove item hyperlink.But after adding multiple items,I cant remove items using hyperlink. What should I do?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> </title>
<link rel="stylesheet" type="text/css" href="header.css" />
</head>
<body>
<div id="header">
<?php include './menu.php';?>
</div>
<div id="navigator">
</div>
<div id="section">
<?PHP
$name=$_SESSION['userName'];
$email=$_SESSION['myEmail'];
require("connection.php");
?><h2>
Welcome <?PHP echo($name); ?>,</h2>
<?PHP require("menu2.php"); ?><hr>
<?PHP
require("connection.php");
$Query=("select * from tb_book");
$result=mysql_query($Query);
?>
<?php
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$result = mysql_query("SELECT * FROM tb_book WHERE bookID='" . $_GET["bookID"] . "'");
$productByCode=mysql_fetch_array($result);
$itemArray = array($productByCode["bookID"]=>array('bName'=>$productByCode["bName"], 'bookID'=>$productByCode["bookID"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode["price"]));
//$itemArray = array($productByCode[0]["bookID"]=>array('bName'=>$productByCode[0]["bName"], 'bookID'=>$productByCode[0]["bookID"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode["bookID"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode["bookID"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["bookID"] == $k)
unset($_SESSION["cart_item"][$k]);
//if(empty($_SESSION["cart_item"]))
// unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
?>
<table border="1" width="100%" height="100%">
<tr>
<td width="70%">
<div id="product-grid">
<div class="txt-heading">Products</div>
<?php
$product = mysql_query("SELECT * FROM tb_book ORDER BY bName ASC");
while($row=mysql_fetch_array($product)) {
?>
<div class="product-item">
<form method="post" action="buyBook.php?action=add&bookID=<?php echo $row["bookID"]; ?>">
<div><img src="./books/<?PHP echo($row['image']); ?>" height="100" width="100" /></div>
<div><?php echo $row["bName"]; ?></div>
<div class="product-price"><?php echo "INR ".$row["price"]; ?></div>
<div><input type="text" name="quantity" value="1" size="2" />
<input type="submit" value="Add to cart" class="btnAddAction" /></div>
</form>
</div>
<?php
}
?>
</div>
</td>
<td width="30%" valign="top">
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" href="buyBook.php?action=empty">Empty Cart</a></div>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
<th></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><?php echo $item["bName"]; ?></td>
<td><?php echo $item["quantity"]; ?></td>
<td align=right><?php echo "INR ".$item["price"]; ?></td>
<td>Remove Item</td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "INR ".$item_total; ?></td>
</tr>
</tbody>
</table>
<?php
}
?>
</div>
</table>
<br /><br /><center>
<form name="checkout" action="buyBook_action.php" method="post">
<input type="submit" value="PROCEED" />
</form>
</center>
</td>
</tr>
</table>
</div>
</body>
</html>

Answer:
if (!empty($_GET["bookID"])) {
foreach($_SESSION["cart_item"] as $subKey => $subArray){
if($subArray["bookID"] == $_GET["bookID"]){ /* CHECK IF THERE IS A BOOKID THAT HAS THE SAME $_GET["bookID"] */
unset($_SESSION["cart_item"][$subKey]);
}
} /* END OF FOREACH */
}
You store your array with sub-array of bName, bookID, quantity, and price in your session variable. The code I have provided will check the $_GET["bookID"] if it is in a sub-array of bookID. And if it does found one, it will remove that set of array.
[
{"bName":"Physics","bookID":"1","quantity":"1","price":"1100.00"},
{"bName":"Algebra","bookID":"2","quantity":"2","price":"1200.00"},
{"bName":"Calculus","bookID":"3","quantity":"3","price":"1300.00"}
]
Recommendation
Create an extra table. Lets name it cart_table
cart_id | userID | bookID |
---------+----------+----------+
1 | 1 | 1 |
2 | 1 | 2 |
3 | 1 | 3 |
userID column is the user's ID and bookID column is the book's ID that the user puts into the cart.
The advantage of this is even if the user logs-out, when this user returns, he/she will still be able to see the books that he/sher puts into his/her cart.

Related

Add to cart button redirecting to another page

Whenever I click on the add to cart button it just goes to another page instead of showing it in the table
<?php
require "includes/dbh.php";
if(isset($_post['add'])){
if(isset($_SESSION['shopping_cart'])){
This is how I get the data in the html
$item_array_id=array_column($_SESSION['shopping_Cart'],'item_id');
if(!in_array($_GET['id'],$item_array_id)){
$count=count($_SESSION['shopping_cart']);
$item_array=array(
'item_id' =>$_GET['id'],
'item_name'=>$_POST['hidden_name'],
'item_price'=>$_POST['hidden_price'],
'item_quantity'=>$_POST['quantity'],
);
$_SESSION['shopping_cart'][$count]=$item_array;
}else{
echo "<script> alert('item already added')</script>";
echo "window.location='displayitems.php'></script>";
}
}else{
$item_array=array(
'item_id' =>$_GET['id'],
'item_name'=>$_POST['hidden_name'],
'item_price'=>$_POST['hidden_price'],
'item_quantity'=>$_POST['quantity'],
);
$_SESSION['shopping_cart'][0]=$item_array;
}
}
if(isset($_get['action'])){
if($_get['action']=='delete'){
foreach($_SESSION['shopping_cart'] as $keys =>$values){
if($values['item_id']==$_get['id'])
{
unset($_SESSION['shopping_cart'][$keys]);
echo '<script>alert("item removed")</script>';
echo '<script>window.location="displayitems.php</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
<style>
.product{
border:1px solid
margin:-1px 19px 3px -1px;
padding: 10px;
text-align:center;
bacgkround-color:#efefef;
}
</style>
</head>
<body>
<?php
if(isset($_SESSION['userId'])){
echo '<div id="items" >';
include_once 'includes/dbh.php';
require 'includes/gallery-upload.in.php';
$sql="SELECT * FROM gallery ORDER BY orderitems DESC;";
$stmt=mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
echo "sql statement failed in displayitems.php";
}else{
mysqli_stmt_execute($stmt);
$result=mysqli_stmt_get_result($stmt);
while($row=mysqli_fetch_assoc($result))
{
?>
This is my form in adding to cart button
<div class="col-md-3">
<form method="POST" action="displayitems.php?action=add&id=<?php
echo $row["idGallery"]?>">
<div class="product">
<img src=images/<?php echo $row['imgFullNameGallery'] ?>
<br>
<h3><?php echo $row['nameitem']?></h3>
<h3><?php echo $row['price']?></h3>
<input type='number' name='quantity' value="1">
<input type='hidden' name='hidden_name' value="<?php echo
$row['nameitem']?>">
<input type='hidden' name='hidden_price' value="<?php
echo
$row['price']?>">
<button type='submit' name='add'>Add to cart</button>
</div>
</form>
</div>
<?php
}
}
}
?>
<div style="clear":both"></div>
<h3 class="title2">Shopping cart details</h3>
<div class="table table-bordered">
<table>
<tr>
<th width=40%>Item Name</th>
<th width=10%>Quantity</th>
<th width=20%>Price</th>
<th width=15%>Total</th>
<th width=5%>Action</th>
</tr>
<?php
if(!empty($_SESSION['shopping_cart'])){
$total=0;
foreach($_SESSION['shopping_cart']as $keys => $values){
?>
<tr>
<td><?php echo $values['item_name'];?></td>
<td><?php echo $values['item_quantity'];?></td>
<td>$<?php echo $values['item_price'];?></td>
<td><?php echo
number_format($values['item_quantity']*$values['item_price'],2);?></td>
<td>REMOVE</span></td>
</tr>
<?php
$total= $total+($values['item_quantity']*$values['item_price']);
}
?>
<tr>
<td coslpan="3" align="right">total</td>
<td align="right"><?php echo number_format($total,2);?></td>
</td></td>
<?php
}
?>
</table>
</div>
</body>
</html>
It doesn't show in the table and the url is just changing to http://localhost/Soft/displayitems.php?action=add&id=1 and the page is blank
because of you using form and the button type is submit so it's expecting a callback function. Regarding you don't have one and you want to display everything in the same page so you have instead to make the submit functionality to a link instead.
Change :
<button type='submit' name='add'>Add to cart</button>
to
<a type='submit' name='add'>Add to cart</a>
or
<input type="submit" value="Add to cart">
here is a mozilla ref

Only "Array" word is being inserted when trying to save php shopping cart session content, can not retrieve the contents of cart

I have a shopping cart in which the orders are being shown, i am using session to store the cart contents. Now what i want to do is to insert the cart contents into a database upon the press checkout button. But everytime any user checks out only the word "Array" is being inserted into the DB. What i have tried -
$sqlimp = implode(",", $_SESSION["cart"] );
and the n print_r the $sqlimp and it shows Array,Array,ArayArray,Array,Array (if there is 2 items). Below is my code -
index.php
<?php
session_start();
// print_r($_SESSION["user"]);
if(! isset($_SESSION["user"])){
header("Location: index.php");
}
require("connection.php");
if(isset($_GET['page'])){
$pages=array("products", "cart");
if(in_array($_GET['page'], $pages)) {
$_page=$_GET['page'];
}else{
$_page="products";
}
}else{
$_page="products";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <link rel="stylesheet" href="css/reset.css" /> -->
<link rel="stylesheet" href="styles.css" />
<title></title>
</head>
<body>
<h1> Welcome to our site! </h1>
Logout
<?php
// Echo session variables that were set on previous page
echo "Welcome " . $_SESSION["user"] . ".<br>";
?>
<div id="container">
<div id="main">
<?php require($_page.".php"); ?>
</div><!--end of main-->
<div id="sidebar">
<h1>Cart</h1>
<?php
if(isset($_SESSION['cart'])){
$sql="SELECT * FROM products WHERE id_product IN (";
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
// $sql1= "INSERT INTO cart (contents) VALUES ('" . $_SESSION["cart"]. "')";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
// $query1= mysql_query($sql1);
while($row=mysql_fetch_array($query)){
?>
<p><?php echo $row['name'] ?> x <?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?></p>
<?php
}
?>
<hr />
Go to cart
<?php
}else{
echo "<p>Your Cart is empty. Please add some products.</p>";
}
?>
</div><!--end of sidebar-->
</div><!--end container-->
</body>
</html>
products.php
<?php
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}else{
$sql_s="SELECT * FROM products
WHERE id_product={$id}";
$query_s=mysql_query($sql_s);
if(mysql_num_rows($query_s)!=0){
$row_s=mysql_fetch_array($query_s);
$_SESSION['cart'][$row_s['id_product']]=array(
"quantity" => 1,
"price" => $row_s['price']
);
}else{
$message="This product id it's invalid!";
}
}
}
?>
<h1>Product List</h1>
<?php
if(isset($message)){
echo "<h2>$message</h2>";
}
?>
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$sql="SELECT * FROM products ORDER BY name ASC";
$query=mysql_query($sql);
while ($row=mysql_fetch_array($query)) {
?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['price'] ?>$</td>
<td>Add to cart</td>
</tr>
<?php
}
?>
</table>
cart.php
<?php
if(isset($_POST['submit'])){
foreach($_POST['quantity'] as $key => $val) {
if($val==0) {
unset($_SESSION['cart'][$key]);
}else{
$_SESSION['cart'][$key]['quantity']=$val;
}
}
}
?>
<h1>View cart</h1>
Go back to the products page.
<form method="post" action="home.php?page=cart">
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Items Price</th>
</tr>
<?php
$sql="SELECT * FROM products WHERE id_product IN (";
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
$totalprice=0;
while($row=mysql_fetch_array($query)){
$subtotal=$_SESSION['cart'][$row['id_product']]['quantity']*$row['price'];
$totalprice+=$subtotal;
?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><input type="text" name="quantity[<?php echo $row['id_product'] ?>]" size="5" value="<?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?>" /></td>
<td><?php echo $row['price'] ?>$</td>
<td><?php echo $_SESSION['cart'][$row['id_product']]['quantity']*$row['price'] ?>$</td>
</tr>
<?php
}
?>
<tr>
<td colspan="4">Total Price: <?php echo $totalprice ?></td>
</tr>
</table>
<br />
<button type="submit" name="submit">Update Cart</button>
Checkout
</form>
<br />
<p>To remove an item set its quantity to 0. </p>
checkout.php
<?php
session_start();
include("connection.php");
$sql="SELECT * FROM products WHERE id_product IN (";
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
$sqlimp = implode(",",$_SESSION['cart'] );
print_r($sqlimp);
$sql1= "INSERT INTO cart (contents) VALUES ('" . $_SESSION["cart"]. "')";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
$query1= mysql_query($sql1);
// or die("Query to store cart failed");
?>
any help would be appreciated.
In your foreach loop in checkout.php you are trying to INSERT the $_SESSION['cart'] instead of your computed $sqlimp. So you need to change the line to:
$sql1= "INSERT INTO cart (contents) VALUES ('$sqlimp')";

Shopping cart is not working properly [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
My shopping cart is not completely working. The database connection is working and the products and their data show up in a table. However, I can't add anything to my cart. The shopping cart is consists of index.php, cart.php, products.php.
Index.php looks like this:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
require("includes/connection.php");
if(isset($_GET['page'])){
$pages=array("products", "cart");
if(in_array($_GET['page'], $pages)) {
$_page=$_GET['page'];
}else{
$_page="products";
}
}else{
$_page="products";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/style.css" />
<title>Shopping Cart</title>
</head>
<body>
<div id="container">
<div id="main">
<?php require($_page.".php"); ?>
</div><!--end of main-->
<div id="sidebar">
<h1>Cart</h1>
<?php
if(isset($_SESSION['cart'])){
$sql="SELECT * FROM products WHERE productCode IN (";
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY productName ASC";
$query=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($query)){
?>
<p><?php echo $row['productName'] ?> x <?php echo $_SESSION['cart'][$row['productCode']]['quantity'] ?></p>
<?php
}
?>
<hr />
Go to cart
<?php
}else{
echo "<p>Your Cart is empty. Please add some products.</p>";
}
?>
</div><!--end of sidebar-->
</div><!--end container-->
</body>
</html>
Cart.php looks like this:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
if(isset($_POST['submit'])){
foreach($_POST['quantity'] as $key => $val) {
if($val==0) {
unset($_SESSION['cart'][$key]);
}else{
$_SESSION['cart'][$key]['quantity']=$val;
}
}
}
?>
<h1>View cart</h1>
Go back to products page
<form method="post" action="index.php?page=cart">
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Items Price</th>
</tr>
<?php
$sql="SELECT * FROM products WHERE productCode IN (";
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY productName ASC";
$query=mysql_query($sql) or die(mysql_error());
$totalprice=0;
while($row=mysql_fetch_array($query)){
$subtotal=$_SESSION['cart'][$row['productCode']]['quantity']*$row['buyPrice'];
$totalprice+=$subtotal;
?>
<tr>
<td><?php echo $row['productName'] ?></td>
<td><input type="text" name="quantity[<?php echo $row['productCode'] ?>]" size="5" value="<?php echo $_SESSION['cart'][$row['productCode']]['quantity'] ?>" /></td>
<td><?php echo $row['buyPrice'] ?>$</td>
<td><?php echo $_SESSION['cart'][$row['productCode']]['quantity']*$row['buyPrice'] ?>$</td>
</tr>
<?php
}
?>
<tr>
<td>Total Price: <?php echo $totalprice ?></td>
</tr>
</table>
<br />
<button type="submit" name="submit">Update Cart</button>
</form>
<br />
<p>To remove an item set it's quantity to 0. </p>
And products.php looks like this:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}else{
$sql_s="SELECT * FROM products
WHERE productCode={$id}";
$query_s=mysql_query($sql_s) or die(mysql_error());
if(mysql_num_rows($query_s)!=0){
$row_s=mysql_fetch_array($query_s);
$_SESSION['cart'][$row_s['productCode']]=array(
"quantity" => 1,
"price" => $row_s['buyPrice']
);
}else{
$message="This product id it's invalid!";
}
}
}
?>
<h1>Product List</h1>
<?php
if(isset($message)){
echo "<h2>$message</h2>";
}
?>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$sql="SELECT * FROM products ORDER BY productName ASC";
$query=mysql_query($sql) or die(mysql_error());
while ($row=mysql_fetch_array($query)) {
?>
<tr>
<td><?php echo $row['productName'] ?></td>
<td><?php echo $row['productDescription'] ?></td>
<td><?php echo $row['buyPrice'] ?>$</td>
<td>Add to cart</td>
</tr>
<?php
}
?>
</table>
I turned error reporting on and I'm getting the following error:
Unknown column 'S10_1678' in 'where clause'
The table 'products' in my database looks like this:
http://i.stack.imgur.com/KrB8a.png
In my opinion everything in the code is correct, but what is going wrong here?
Please try adding quotes to your sql statement around $id - I understand it is a string (productCode) in your case, like this:
foreach($_SESSION['cart'] as $id => $value) {
$sql.="'".$id."',";
}

How can i display cart page in separate tab in php?

Here is my index.php:
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["code"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
?>
<HTML>
<HEAD>
<TITLE>Simple PHP Shopping Cart</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY>
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" href="index.php?action=empty">Empty Cart</a></div>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
<th><strong>Action</strong></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["code"]; ?></td>
<td><input type="number" value="<?php echo $item["quantity"]; ?>"></td>
<td align=right><?php echo "$".$item["price"]; ?></td>
<td>Remove Item</td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "$".$item_total; ?></td>
</tr>
</tbody>
</table>
<?php
}
?>
<div class="checkout"> Checkout</div>
</div>
<div id="product-grid">
<div class="txt-heading">Products</div>
<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="product-item">
<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
<div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
<div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
<div><input type="text" name="quantity" value="1" size="2" /><input type="submit" value="Add to cart" class="btnAddAction" /></div>
</form>
</div>
<?php
}
}
?>
</div>
</BODY>
</HTML>
Now page look like this; http://s1.postimg.org/7yyj0rh1b/Untitled_1_copy.png
I need to display another tab for displaying shopping cart.
May i know, how can i do this? Thanks in advance.
If I read your instructions correctly, and I am not 100% sure I am, I think you want to only display the cart on add. To do this I think I would break your page up into parts so that each portion has a task. then you can more easily separate out your cart from your all-products display. You can also more-easily use the cart on other parts of the site since it is a class:
class.ShoppingCart.php
<?php
class ShoppingCart
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
public function execute()
{
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
$this->AddToCart();
break;
case "remove":
$this->RemoveFromCart();
break;
case "empty":
$this->EmptyCart();
break;
}
}
}
public function AddToCart()
{
// I don't know if code is supposed to be numeric or not and I also
// don't know if you sanitize your input, but from just looking at this
// it looks dangerous (sql injection-prone)
if(!empty($_POST["quantity"]) && is_numeric($_GET["code"])) {
$productByCode = $this->db->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["code"] == $k)
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
}
public function RemoveFromCart()
{
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
}
public function EmptyCart()
{
unset($_SESSION["cart_item"]);
}
public function DisplayCart()
{
if(isset($_SESSION["cart_item"]) && !empty($_SESSION["cart_item"])) {
$item_total = 0; ?>
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" href="index.php?action=empty">Empty Cart</a></div>
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
<th><strong>Action</strong></th>
</tr><?php
foreach ($_SESSION["cart_item"] as $item) { ?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["code"]; ?></td>
<td><input type="number" value="<?php echo $item["quantity"]; ?>"></td>
<td align=right><?php echo "$".$item["price"]; ?></td>
<td>Remove Item</td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
} ?>
<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "$".$item_total; ?></td>
</tr>
</tbody>
</table>
<div class="checkout"> Checkout</div>
</div>
<?php }
}
} ?>
/includes/products/index.php
<?php
// Exit if the database is not set
// Stops direct access to this file
if(!isset($db_handle)) return; ?>
<div id="product-grid">
<div class="txt-heading">Products</div>
<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="product-item">
<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
<div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
<div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
<div><input type="text" name="quantity" value="1" size="2" /><input type="submit" value="Add to cart" class="btnAddAction" /></div>
</form>
</div>
<?php
}
}
?>
</div>
index.php
<?php
session_start();
require_once("dbcontroller.php");
// Include shopping cart class
require_once("class.ShoppingCart.php");
// Initiate db instance
$db_handle = new DBController();
// Initiate shopping cart engine
$ShoppingCart = new ShoppingCart($db_handle);
// Execute the engine portion that handles adding/removing/emptying
$ShoppingCart->execute(); ?><!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>Simple PHP Shopping Cart</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY>
<?php
// If adding to the cart, show the cart
if(isset($_GET['action']) && $_GET['action'] == 'add')
$ShoppingCart->DisplayCart();
// Only show product page if action add not available
else
include('includes/products/index.php'); ?>
</BODY>
</HTML>

Error insert data into table

I have follow an instruction on how to create a shopping cart, I want to make a modification so the shopping cart system can be use as a restaurant system for staff to record customer order, so the system do not need to record the customer details. I have error when i try to insert all the chosen data into table and it's echo sucess, but no data inserted into database. the error happens in cart.php.
Here is the error:
Notice: Undefined index: name in C:\xampp\htdocs\emakengku\cart.phpon line 7
Notice: Undefined index: quantity inC:\xampp\htdocs\emakengku\cart.php on line 8
Notice: Undefined index: price in C:\xampp\htdocs\emakengku\cart.phpon line 9
Here is the code:
index2.php
<?
session_start();
error_reporting(E_ALL);
require("connection.php");
if(isset($_GET['page'])){
$pages=array("products", "cart");
if(in_array($_GET['page'], $pages)) {
$_page=$_GET['page'];
}else{
$_page="products";
}
}else{
$_page="products";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<body>
</body>
</html>
<link rel="stylesheet" href="style2.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
});
</script>
</head>
<body>
<div id="container">
<div id="main">
<?php require($_page.".php"); ?>
</div>
<div id="sidebar">
<h1>Cart</h1>
<?php
if(isset($_SESSION['cart'])){
$sql="SELECT * FROM products WHERE id_product IN (";
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query)){
?>
<p><?php echo $row['name'] ?> x <?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?></p>
<?php }
?>
<hr />
Go to Cart
<?php
}else{
echo "<p>Your Cart is empty</p>";
}
?>
</div>
</div>
</body>
Products.php
<?php
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}else{
$sql_s="SELECT * FROM products
WHERE id_product={$id}";
$query_s=mysql_query($sql_s);
if(mysql_num_rows($query_s)!=0){
$row_s=mysql_fetch_array($query_s);
$_SESSION['cart'][$row_s['id_product']]=array(
"quantity" => 1,
"price" => $row_s['price']
);
}else{
$message="This product id it's invalid!";
}
}
}
?>
<h1>Product List</h1>
<?php
if(isset($message)){
echo "<h2>$message</h2>";
}
?>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$sql="SELECT * FROM products ORDER BY name ASC";
$query=mysql_query($sql);
while ($row=mysql_fetch_array($query)) {
?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['description'] ?></td>
<td>RM <?php echo $row['price'] ?></td>
<td>Add To Cart</td>
</tr>
<?php
}
?>
</table>
cart.php
<?php
error_reporting(E_ALL);
require("connection.php");
if(isset($_POST['submit2'])) {
$name=$_POST["name"];
$quantity=$_POST["quantity"];
$price=$_POST["price"];
$sql_insert = "INSERT INTO order (name, quantity, price)
values('$name', '$quantity', '$price')";
mysql_query($sql_insert);
echo "sucess!";
}
if(isset($_POST['submit'])){
foreach($_POST['quantity'] as $key => $val) {
if($val==0) {
unset($_SESSION['cart'][$key]);
}else{
$_SESSION['cart'][$key]['quantity']=$val;
}
}
}
?>
Go back to product page
<h1>View Cart</h1>
<form method="post" action"index2.php?page=cart">
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Item Price</th>
</tr>
<?php
$sql="SELECT * FROM products WHERE id_product IN (";
foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
$totalprice=0;
while($row=mysql_fetch_array($query)){
$subtotal=$_SESSION['cart'][$row['id_product']]['quantity']*$row['price'];
$totalprice+=$subtotal;
?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><input type="text" name="quantity[<?php echo $row['id_product'] ?>]" size="5" value="<?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?>"</td>
<td>RM <?php echo $row['price'] ?></td>
<td>RM <?php echo $_SESSION['cart'][$row['id_product']]['quantity']*$row['price'] ?></td>
</tr>
<?php
}
?>
<tr>
<td>Total Price: <?php echo $totalprice ?></td>
</tr>
</table>
<button type="submit" name="submit"> Update Cart</button>
<button type="submit" name="submit2"> Update Cart</button>
</form>
<br />
<p> To remove an item,set the quantity to 0</p>
Your form is broken, you're missing the name, quantity etc inputs you later try to use in the script ($_POST['name'] etc) - in file cart.php.
It's hard to find it, because the code is huge mess, but I didn't manage to find any inputs with those names.
Also, besides the obvious flaws like using deprecated mysql_* functions, you really should not mix logic and view this way. Doing database query in the middle of rendering a form is NOT GOOD.
If you used some MVC framework, it'd be much cleaner.

Categories