I am busy creating a shopping cart php project and i have successfully completed add,remove and update items to a shopping cart but the part i am stuck at is if a user clicks the "proceed to checkout" button i want whatever is in the shopping cart to decrease accordingly in the database. For Example if a person has in his shopping cart:
2 x product one
3 x product two
I want that to decrease in the amount i have on hand if the sale is completed. Could someone please help
Here is my shopping cart code below:
<?php
session_start();
#mysql_connect("localhost","root","") or die("Could not connect to database");
#mysql_select_db("bookstore") or die("Could not select database");
include("admin/php/myFunctions.php");
if(!empty($_GET['prodid'])){
$pid = $_GET['prodid'];
$wasFound = false;
$i = 0;
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$_SESSION["cart_array"]=array(0=>array("productID"=>$pid,"quantity"=>1));
}else{
foreach($_SESSION["cart_array"] as $each_product){
$i++;
while(list($key,$value)=each($each_product)){
if($key=="productID" && $value==$pid){
array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$pid,"quantity"=>$each_product ['quantity']+1)));
$wasFound=true;
}
}
}
if($wasFound==false){
array_push($_SESSION["cart_array"],array("productID"=>$pid,"quantity"=>1));
}
}
header("location:shoppingcart.php");
exit();
}
//-------------------------------------------------------------------------------------------------
$submit = $_POST['btnUpdate'];
if($submit == "Update"){
$x = 0;
foreach($_SESSION["cart_array"] as $each_product){
#$i++;
$quantity = $_POST['txtQuan'.$x];
$prodStock = $_POST['txtHoldQuan'.$x];
$prodAdjustId = $_POST['txtHoldProdId'.$x++];
if($quantity<1){ $quantity = 1; }
if($quantity>$prodStock){ $quantity = $prodStock; }
while(list($key,$value)=each($each_product)){
array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$prodAdjustId,"quantity"=>$quantity)));
}
}
}
//-------------------------------------------------------------------------------------------------
if(!empty($_GET['cid']) || isset($_GET['cid'])){
$removeKey = $_GET['cid'];
if(count($_SESSION["cart_array"])<=1){
unset($_SESSION["cart_array"]);
}else{
unset($_SESSION["cart_array"]["$removeKey"]);
sort($_SESSION["cart_array"]);
}
}
//-------------------------------------------------------------------------------------------------
$cartTitle = "";
$cartOutput = "";
$cartTotal = "";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartOutput="<h2 align='center'> Your shopping cart is empty </h2>";
}else{
$x = 0;
$cartTitle .= '<form name="shoppingcart_form" action="shoppingcart.php" method="post" /><table width="700px" cellspacing="0" cellpadding="5">
<tr bgcolor="#CCCCCC">
<th width="220" align="left">Image </th>
<th width="140" align="left">Name </th>
<th width="100" align="center">Quantity </th>
<th width="60" align="center">Stock </th>
<th width="60" align="right">Price </th>
<th width="60" align="right">Total </th>
<th width="90"> </th></tr>';
$i = 0;
foreach($_SESSION["cart_array"] as $each_product){
$product_id = $each_product['productID'];
$sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1");
while($row=mysql_fetch_array($sql)){
$prodNo = $row["prod_no"];
$prodID = $row["prod_id"];
$prodName = $row["prod_name"];
$prodPrice = $row["prod_price"];
$prodQuan = $row["prod_quan"];
}
$pricetotal=$prodPrice*$each_product['quantity'];
$cartTotal= number_format($pricetotal+$cartTotal,2);
$cartOutput .= '<tr><td><img style="border: 2px solid;" src="images/product/'.$prodNo.'.jpg" width="150" height="120" /></td>
<td>'.$prodName.'</td>
<td align="center"><input type="hidden" name="txtHoldProdId'.$i.'" value="'.$prodID.'" /><input name="txtQuan'.$i.'" type="text" value="'.$each_product['quantity'].'" style="width: 40px; text-align: center" /> </td>
<td align="center"><input type="hidden" name="txtHoldQuan'.$i.'" value="'.$prodQuan.'" /> '.$prodQuan .' pcs</td>
<td align="right">R '.$prodPrice.'</td>
<td align="right">R '.$pricetotal.'</td>
<td align="center"> <img src="images/remove_x.gif" alt="remove" /><br />Remove </td></tr>';
}
$_SESSION['checkoutCartTotal'] = $cartTotal;
$cartOutput .= '<tr>
<td colspan="3" align="right" height="40px">Have you modified your basket? Please click here to <input class="btn_upd" type="submit" name="btnUpdate" value="Update" /> </td>
<td align="right" style="background:#ccc; font-weight:bold"> Total: </td>
<td colspan="2" align="left" style="background:#ccc; font-weight:bold;">R '.$cartTotal.' </td>
<td style="background:#ccc; font-weight:bold"> </td>
</tr>
</table>
<div style="float:right; width: 215px; margin-top: 20px;">
<div class="checkout">Proceed to Checkout</div>
</div></form>';
}
?>
<!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">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Great Selling Book Store</title>
<link href="css/slider.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script language="javascript" type="text/javascript">
function clearText(field)
{
if (field.defaultValue == field.value) field.value = '';
else if (field.value == '') field.value = field.defaultValue;
}
</script>
</head>
<body id="subpage">
<div id="main_wrapper">
<div id="main_header">
<div id="site_title"><h1>Great Selling book Store</h1></div>
<div id="header_right">
<div id="main_search">
<form action="products.php" method="get" name="search_form">
<input type="text" value="Search" name="keyword" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field" />
<input type="submit" name="Search" value="" alt="Search" id="searchbutton" title="Search" class="sub_btn" />
</form>
</div>
</div> <!-- END -->
</div> <!-- END of header -->
<div id="main_menu" class="ddsmoothmenu">
<ul>
<li>Home</li>
<li>Books</li>
<li><a class="selected" href="shoppingcart.php">Cart</a></li>
<li>Checkout</li>
<li>About</li>
</ul>
<br style="clear: left" />
</div> <!-- end of menu -->
<div class="cleaner h20"></div>
<div id="main_top"></div>
<div id="main">
<div id="sidebar">
<h3>Categories</h3>
<ul class="sidebar_menu">
<li>Children</li>
<li>Horror</li>
<li>Thriller</li>
</ul>
</div> <!-- END of sidebar -->
<div id="content">
<?php echo $cartTitle; ?>
<?php echo $cartOutput; ?>
</div> <!-- end of content -->
<div class="cleaner"></div>
</div> <!-- END of main -->
<div id="main_footer">
<div class="cleaner h40"></div>
<center>
Copyright © 2048 DigitalNinja
</center>
</div> <!-- END of footer -->
</div>
<script type='text/javascript' src='js/logging.js'></script>
</body>
</html>
and here is a my table which i am using in my database:
CREATE TABLE IF NOT EXISTS `tblproduct` (
`prod_no` int(10) NOT NULL AUTO_INCREMENT,
`prod_id` int(15) NOT NULL,
`prod_name` varchar(100) NOT NULL,
`prod_descr` text NOT NULL,
`prod_cat` varchar(100) NOT NULL,
`prod_price` float NOT NULL,
`prod_quan` int(10) NOT NULL,
`date_added` datetime NOT NULL,
`ISBN` varchar(100) NOT NULL,
PRIMARY KEY (`prod_no`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `tblproduct` (`prod_no`, `prod_id`, `prod_name`, `prod_descr`, `prod_cat`, `prod_price`, `prod_quan`, `date_added`, `ISBN`) VALUES
(1, 1, 'Charlie and the chocolate factory', 'prod description', 'Children', 80, 100, '2016-11-01 08:25:36', '9785811243570'),
(2, 2, 'Frankenstein', 'Prod description', 'Horror', 120, 80, '2017-05-01 05:27:11', '9781608438037'),
(3, 3, 'The Girl on the Train', 'Prod Description', 'Thriller', 200, 90, '2017-01-18 04:22:22', '9784062932530');
After placing the order by the buyer you need to make an entry in your database:
UPDATE `tblproduct` SET prod_quan=prod_quan-$order_count WHERE prod_id=$product_id;
Where $order_count is the quantity ordered and $product_id - product ordered. Do this update for each product ordered.
working properly with mysql update books set TotalBooks = TotalBooks-1 where Id = ?
Assuming the order is stored in another table, and keeps a reference to the product, you should just be able to do something like this:
UPDATE tblproduct AS p
INNER JOIN tblorderproducts AS op ON p.product_no = op.product_no
SET p.prod_quan = p.prod_quan - op.prod_quan
WHERE op.order_id = [the order id]
;
Note: This might have some issues if the product can appear in the same order more than once.
Related
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
I don't get any errors but I can't update MySQL PHP. I want to change dropdown status from "sedang diproses" dropdown into "Berjaya or Tidak Berjaya". Also I can't change in the database "sedang diproses" into "Berjaya or Tidak Berjaya"
This is my Code Html
<?php
session_start();
include ('include/myFunction.php');
require('include/connect.php');
?>
<!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>Untitled Document</title>
</head>
<link href="css/myStyle.css" rel="stylesheet" type="text/css" />
<link href="css/myStyle1.css" rel="stylesheet" type="text/css" />
<!-- Button to open the modal login form -->
<link href="css/myStyle3.css" rel="stylesheet" type="text/css" />
<body>
<div align="right">
<a href="logout.php" ><img src="img/logout.png" width="63" height="46" /></a>
</div>
<div class="header" align="left"><img src="img/gmbar.PNG" width="223" height="126" /><!-- end .header --><!-- end .header --></div>
<div class="content" style="font:Verdana, Geneva, sans-serif">
<div class="content" style="font:Verdana, Geneva, sans-serif">
<div class="topnav" id="myTopnav" style="font-family:Verdana, Geneva, sans-serif">Kembali
</div>
<p> </p>
<?php if($_SESSION['namaadmin'] ==null)
{
header('location:index.php');
}
else
{
?>
<form action="prosesstatus.php" method="post">
<table width="1002" height="87" border="0" align="center" bgcolor="#CCCCFF">
<tr bgcolor="#00CCFF">
<td width="30"><strong>Bil</strong></td>
<td width="298"><strong>Nama</strong></td>
<td width="176"><strong>Nama Kursus</strong></td>
<td width="150"><strong>Tarikh Daftar</strong></td>
<td width="150"><strong>Status</strong></td>
<td width="168"><strong>Kemaskini Status</strong></td>
<td width="131"><strong>Pilihan</strong></td>
</tr>
<?php
$namakursus = '';
if( isset( $_GET['namakursus'])) {
$namakursus = $_GET['namakursus'];
}
$sql1 = "Select * from pemohonan INNER JOIN kursus ON pemohonan.idkursus = kursus.idkursus
INNER JOIN pemohon ON pemohonan.idPemohon = pemohon.idPemohon WHERE kursus.namakursus = '$namakursus' ";
$result1=mysqli_query($dbc,$sql1) or die (mysqli_error());
$i=1;
while($row1 = mysqli_fetch_assoc($result1))
{
?>
<tr>
<td><strong><?php echo $i; ?><input name="idkursus" type="hidden" size="50" value="<?php echo $row1['idkursus'];?>"/><input name="idPemohonan" type="hidden" size="50" value="<?php echo $row1['idPemohonan'];?>"/></strong></td>
<td><strong><?php echo $row1['nama']; ?></strong><input name="id" type="hidden" size="50" value="<?php echo $row1['idPemohon'];?>"/></strong></td>
<td><strong><?php echo $row1['namakursus']; ?></strong></td>
<td><strong><?php echo $row1['tarikhpemohon']; ?></strong></td>
<td><strong><?php echo $row1['status']; ?></strong></td>
<td><select name="status" value="<?php echo $row1['status']; ?>">
<option value="sila pilih">-Sila Pilih-</option>
<option value="Berjaya">Berjaya</option>
<option value="Tidak Berjaya">Tidak Berjaya</option>
</select></td>
<td><input name="btnKemaskini" type="submit" value="Kemaskini" /></td>
</tr>
<?php
$i++;
}
mysqli_close($dbc);
}
?>
</table></form>
<p> </p>
<p> </p>
<div class="footer" style="font-family:Arial, Helvetica, sans-serif">
<?php footertext(); ?>
</div>
</body>
</html>
This is Image
This Is My Image DB
This is my Code Php
<?php
require ('include/connect.php');
$idPemohonan = '';
$idPemohon = '';
$idkursus = '';
if (isset($_GET['idPemohon'],$_GET['idkursus'],$_GET['idPemohonan']))
{
$idPemohon = $_GET['idPemohon'];
$idkursus = $_GET['idkursus'];
$idPemohonan = $_GET['idPemohonan'];
}
$tarikhharini=date('y-m-d');
$status=$_POST['status'];
$sql1 = "UPDATE pemohonan SET idPemohonan ='$idPemohonan' , idPemohon ='$idPemohon' , idkursus ='$idkursus' , tarikhpemohon ='$tarikhharini' , status='$status'
where idPemohonan = '$idPemohonan' and idPemohon = '$idPemohon'";
$result1 = mysqli_query($dbc,$sql1) or die (mysqli_error());
$num_row1 = mysqli_affected_rows($dbc);
echo "<script language=\"JavaScript\">\n";
echo "alert('Status Pemohonan Telah Dihantar!');\n";
echo "window.location='senaraipemohon.php'";
echo "</script>";
mysqli_close($dbc);
?>
Your code is not working because you haven't sent in
<form action="prosesstatus.php" method="post">
Parameters:
$idPemohon = $_GET['idPemohon'];
$idkursus = $_GET['idkursus'];
$idPemohonan =
$_GET['idPemohonan'];
If you want use $_GET link should look like:
prosesstatus.php?idPemohon=value&idkursus=value&idPemohonan=value
Or you should add these parameters in
Input type hidden and change in php to $_POST
I agree with others than you should use MVC for example some kind of framework (Laravel, CodeIgniter)
Or separate as much as possible php and html because your code looks unprofessional.
Your MySQL queries are vulnerable to SQL injection and most likely file
include/connect.php
is not outside public folder which is not good practice to do.
I have a shopping cart that displays the different products the customer has selected to purchase. I need to INSERT each product selected as a single row with the same customer_id in the 'order_details' table.
Screenshot
code
<?php
session_start();
#mysql_connect("localhost","root","") or die("Could not connect to database");
#mysql_select_db("bookstore") or die("Could not select database");
$connection = mysqli_connect('localhost', 'root', '', 'bookstore');
include("admin/php/myFunctions.php");
$customer = $_SESSION['id_login'];
$order = $_SESSION['id_login'];
if(!empty($_GET['prodid'])){
$pid = $_GET['prodid'];
$wasFound = false;
$i = 0;
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$_SESSION["cart_array"]=array(0=>array("productID"=>$pid,"quantity"=>1));
}else{
foreach($_SESSION["cart_array"] as $each_product){
$i++;
while(list($key,$value)=each($each_product)){
if($key=="productID" && $value==$pid){
array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$pid,"quantity"=>$each_product ['quantity']+1)));
$wasFound=true;
}
}
}
if($wasFound==false){
array_push($_SESSION["cart_array"],array("productID"=>$pid,"quantity"=>1));
}
}
header("location:shoppingcart.php");
exit();
}
//-------------------------------------------------------------------------------------------------
#$submit = $_POST['btnUpdate'];
if($submit == "Update"){
$x = 0;
//echo $_POST['txtQuan2'];
//echo $_POST['txtHoldProdId0'];
foreach($_SESSION["cart_array"] as $each_product){
$i++;
$quantity = $_POST['txtQuan'.$x];
$prodStock = $_POST['txtHoldQuan'.$x];
$prodAdjustId = $_POST['txtHoldProdId'.$x++];
if($quantity<1){ $quantity = 1; }
if($quantity>$prodStock){ $quantity = $prodStock; }
while(list($key,$value)=each($each_product)){
array_splice($_SESSION["cart_array"],$i-1,1,array(array("productID"=>$prodAdjustId,"quantity"=>$quantity)));
}
}
}
//-------------------------------------------------------------------------------------------------
if(!empty($_GET['cid']) || isset($_GET['cid'])){
$removeKey = $_GET['cid'];
if(count($_SESSION["cart_array"])<=1){
unset($_SESSION["cart_array"]);
}else{
unset($_SESSION["cart_array"]["$removeKey"]);
sort($_SESSION["cart_array"]);
}
}
//-------------------------------------------------------------------------------------------------
$cartTitle = "";
$cartOutput = "";
$cartTotal = "";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartOutput="<h2 align='center'> Your shopping cart is empty </h2>";
}else{
$x = 0;
$cartTitle .= '<form name="shoppingcart_form" action="shoppingcart.php" method="post" /><table width="700px" cellspacing="0" cellpadding="5">
<tr bgcolor="#CCCCCC">
<th width="220" align="left">Image </th>
<th width="140" align="left">Name </th>
<th width="100" align="center">Quantity </th>
<th width="60" align="center">Stock </th>
<th width="60" align="right">Price </th>
<th width="60" align="right">Total </th>
<th width="90"> </th></tr>';
#Values in here need to go into database "order_details" table
$i = 0;
foreach($_SESSION["cart_array"] as $each_product){
$product_id = $each_product['productID'];
$sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1");
while($row=mysql_fetch_array($sql)){
$prodNo = $row["prod_no"];
$prodID = $row["prod_id"];
$prodName = $row["prod_name"];
$prodPrice = $row["prod_price"];
$prodQuan = $row["prod_quan"];
}
$pricetotal=$prodPrice*$each_product['quantity'];
$cartTotal= number_format($pricetotal+$cartTotal,2);
$cartOutput .= '<tr><td><img style="border: 2px solid;" src="images/product/'.$prodNo.'.jpg" width="150" height="120" /></td>
<td>'.$prodName.'</td>
<td align="center"><input type="hidden" name="txtHoldProdId'.$i.'" value="'.$prodID.'" /><input name="txtQuan'.$i.'" type="text" value="'.$each_product['quantity'].'" style="width: 40px; text-align: center" /> </td>
<td align="center"><input type="hidden" name="txtHoldQuan'.$i.'" value="'.$prodQuan.'" /> '.$prodQuan .' pcs</td>
<td align="right">R '.$prodPrice.'</td>
<td align="right">R '.$pricetotal.'</td>
<td align="center"> <img src="images/remove_x.gif" alt="remove" /><br />Remove </td></tr>';
}
$_SESSION['checkoutCartTotal'] = $cartTotal;
$cartOutput .= '<tr>
<td colspan="3" align="right" height="40px">Have you modified your basket? Please click here to <input class="btn_upd" type="submit" name="btnUpdate" value="Update" /> </td>
<td align="right" style="background:#ccc; font-weight:bold"> Total: </td>
<td colspan="2" align="left" style="background:#ccc; font-weight:bold;">R '.$cartTotal.' </td>
<td style="background:#ccc; font-weight:bold"> </td>
</tr>
</table>
<div style="float:right; width: 215px; margin-top: 20px;">
</form>
</div></form>';
}
//---------------------------------------------------
$cTotal = $_SESSION['checkoutCartTotal'];
#$cName = $_POST['cardName'];
#$cNumber = $_POST['cardNum'];
#$cAdress = $_POST['cusAddress'];
#$cCity = $_POST['cusCity'];
#$cEmail = $_POST['cusEmail'];
#$cPhone = $_POST['cusPhone'];
foreach($_SESSION["cart_array"] as $each_product){
$product_id = $each_product['productID'];
$sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1");
while($row=mysql_fetch_array($sql)){
$ProdID = $row["prod_id"];
$prodPrice = $row["prod_price"];
$ProdQuan = $row["prod_quan"];
}
$sqlinsert2 = ("INSERT INTO order_details (`order_id`, `prod_id`, `cus_id`, `quantity`, `price_per_unit`) VALUES ('$order', '$ProdID', '$customer', '$ProdQuan', '$prodPrice')");
}
$sqlinsert = "INSERT INTO tbl_order (`total_price`, `credit_card_number`, `fname`, `email`, `address`, `phone`, `city`,`date_ordered`) VALUES ('$cTotal','$cNumber', '$cName', '$cEmail', '$cAdress', '$cPhone', '$cCity',now())";
if (!mysqli_query($connection, $sqlinsert)) {
die(mysqli_error($connection));
}
$newrecord = "Thank you for making your purchase!";
?>
<!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">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Great Selling Book Store</title>
<link href="css/slider.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/ddsmoothmenu.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script language="javascript" type="text/javascript">
function clearText(field)
{
if (field.defaultValue == field.value) field.value = '';
else if (field.value == '') field.value = field.defaultValue;
}
</script>
</head>
<body id="subpage">
<div id="main_wrapper">
<div id="main_header">
<div id="site_title"><h1>Great Selling book Store</h1></div>
<div id="header_right">
<div id="main_search">
<form action="products.php" method="get" name="search_form">
<input type="text" value="Search" name="keyword" onfocus="clearText(this)" onblur="clearText(this)" class="txt_field" />
<input type="submit" name="Search" value="" alt="Search" id="searchbutton" title="Search" class="sub_btn" />
</form>
</div>
</div> <!-- END -->
</div> <!-- END of header -->
<div id="main_menu" class="ddsmoothmenu">
<ul>
<li>Home</li>
<li>Books</li>
<li><a class="selected" href="shoppingcart.php">Cart</a></li>
<li>About</li>
</ul>
<br style="clear: left" />
</div> <!-- end of menu -->
<div class="cleaner h20"></div>
<div id="main_top"></div>
<div id="main">
<div id="sidebar">
<h3>Categories</h3>
<ul class="sidebar_menu">
<li>Children</li>
<li>Horror</li>
<li>Thriller</li>
</ul>
</div> <!-- END of sidebar -->
<div id="content">
<?php echo $cartTitle; ?>
<?php echo $cartOutput; ?>
</div> <!-- end of content -->
<div class="cleaner">
<form method ="post" action="shoppingcart.php">
<input type="hidden" name="submitted" value= "true" />
<fieldset>
<legend>Customer Checkout</legend>
<label>Enter your name as it is on the credit card: <input type="text" name="cardName"></label>
<label>Card Number: <input type="text" name="cardNum"></label>
<label>Adress: <input type="text" name="cusAddress"></label>
<label>City: <input type="text" name="cusCity"></label>
<label>Email: <input type="text" name="cusEmail"></label>
<label>Please, specify your reachable phone number. YOU MAY BE GIVEN A CALL TO VERIFY AND COMPLETE THE ORDER: <input type="text" name="cusPhone"></label>
</fieldset>
<div class="cleaner h50"></div>
<td> <input type="submit" class="more" value="Checkout!"></td>
</form>
</div>
</div> <!-- END of main -->
<?php
echo #$newrecord;
?>
<div id="main_footer">
<div class="cleaner h40"></div>
<center>
Copyright © 2048 DigitalNinja
</center>
</div> <!-- END of footer -->
</div>
<script type='text/javascript' src='js/logging.js'></script>
</body>
</html>
Below example for multiple inserts in a single query and its faster,
INSERT INTO example
(example_id, name, value, other_value)
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
Your Code with multiple insert option:
foreach($_SESSION["cart_array"] as $each_product){
$product_id = $each_product['productID'];
$sql=mysql_query("select * from tblproduct where prod_id='$product_id' limit 1");
while($row=mysql_fetch_array($sql)){
$Prods .= '('.$order.
','.$row["prod_id"].
','. $order.
','.$row["prod_quan"].
','.$row["prod_price"].
'),';//if text: ',"'.$row["prod_quan"].'"),';
}
$Prods = rtrim($Prods, ',');// this is to remove last comma from multiple inserts
$sqlinsert2 = ("INSERT INTO order_details (`order_id`, `prod_id`, `cus_id`, `quantity`, `price_per_unit`) VALUES $Prods");
mysql_query($sqlinsert2);
}
NOTE: you are not running mysql_query of insert, so it's not inserting data into the database.
WARNING: You should use mysqli with parameterized queries and you have created a severe SQL injection bug
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.
I have some HTML/PHP code in Dreamweaver and for the life of me I cannot figure out the cause of this error. The error reads, "There is a syntax error on line 318. Code hinting may not work until you fix this error." Could someone help? And yes, I know I have terrible commenting practice and variable nomenclature. The code can also be found here
<?php
require $_SERVER['DOCUMENT_ROOT'].'/resources/feeds.php';
require $_SERVER['DOCUMENT_ROOT'].'/resources/mysql.php';
session_start();
if(empty($_SESSION['username']) || $_SESSION['login'] != 'true'){ header("location:/"); }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Design by Free CSS Templates
http://www.freecsstemplates.org
Released for free under a Creative Commons Attribution 2.5 License
Name : Vegetables
Description: A two-column, fixed-width design with dark color scheme.
Version : 1.0
Released : 20110416
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="icon" type="/image/png" href="/resources/favicon.png">
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>My Website • Edit Information</title>
<link href="/style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="header">
<div id="logo">
<h1>My Website</h1>
This is the best website ever
<p> </p>
</div>
</div>
<!-- end #header -->
<div id="wrapper">
<div id="menu">
<ul>
<li class="current_page_item">Home</li>
<li>Events</li>
<li>Forums</li>
<li>About</li>
<li>Minutes</li>
<li>Documents</li>
<li>Contact Us</li>
</ul>
</div>
<!-- end #menu -->
</div>
<div id="page">
<div id="content">
<div class="post">
<h2 class="title">Edit Information</h2>
<div style="clear: both;"><form action="/admin"><input type="submit" value='Back'/></form></div>
<div style="clear: both;"></div>
<div class="entry">
<SCRIPT language="javascript">
function add() {
x++;
var foo = document.getElementById('my_div');
foo.innerHTML = foo.innerHTML +"<input type='text' name='tg"+x+"' placeholder='name'><br />";
}
function addch() {
y++;
var foo = document.getElementById('my_other_div');
foo.innerHTML = foo.innerHTML +"<input type='text' name='ch"+y+"' placeholder='name'><br />";
}
function addws() {
z++;
var foo = document.getElementById('my_other_other_div');
foo.innerHTML = foo.innerHTML +"<input type='text' name='ws"+z+"' placeholder='workshop name and leaders' style='width: 98%;'><br />";
}
function detect(form) {
if(form.checked) {
window.backUpHtml = document.getElementById('con_div').innerHTML;
document.getElementById('con_div').innerHTML = '';
} else {
document.getElementById('con_div').innerHTML = window.backUpHtml;
window.backUpHtml = '';
}
}
</SCRIPT>
<form name="form1" method="post" action="./"><font color="#FFFFFF">
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#00000" style="max-width: 560px;">
<tr>
<td width="10%">Name</td>
<td width="90%"><?php echo "<input name='name' type='text' value='".stripslashes($_POST['name'])."' required='required'/>"; ?><input type="checkbox" onclick="detect(this)" name="isyac" id="isyac" value="yes" <?php if(isset($_POST['isyac'])) { echo "checked='checked'";} ?> /><label for="isyac">YAC Meeting</label></td>
</tr>
<tr>
<td width="10%" style="vertical-align:top;">Description</td>
<td width="90%"><?php echo '<textarea name="desc" rows="5" cols="60" style="resize: vertical;" required="required">'.stripslashes($_POST["desc"]).'</textarea>'; ?></td>
</tr>
<tbody id="con_div">
<!-- START OF CON DIV -->
<tr>
<td width="10%" style="vertical-align:top;">Touchgroup Leaders</td>
<td width="90%">
<?php
$blah = 1;
while(isset($_POST['tg'.$blah])) {
echo '<input type="text" name="tg'.$blah.'" value="'.stripslashes($_POST["tg".$blah]).'" /><br />';
$blah++;
}
$hoo = $blah - 1;
echo "<script language='javascript'> var x = ".$hoo."; </script>";
?>
<div id="my_div"></div>
<input type="button" value="Add" onClick="add()">
</td>
</tr>
<tr>
<td width="10%" style="vertical-align:top;">Chaplains</td>
<td width="90%">
<?php
$blah = 1;
while(isset($_POST['ch'.$blah])) {
echo '<input type="text" name="ch'.$blah.'" value="'.stripslashes($_POST["ch".$blah]).'" /><br />';
$blah++;
}
$hoo = $blah - 1;
echo "<script language='javascript'> var y = ".$hoo."; </script>";
?>
<div id="my_other_div"></div>
<input type="button" value="Add" onClick="addch()">
</td>
</tr>
<tr>
<td width="10%" style="vertical-align:top;">Workshops</td>
<td width="90%">
<?php
$blah = 1;
while(isset($_POST['ws'.$blah])) {
echo '<input type="text" name="ws'.$blah.'" value="'.stripslashes($_POST["ws".$blah]).'" style="width: 98%;"/><br />';
$blah++;
}
$hoo = $blah - 1;
echo "<script language='javascript'> var z = ".$hoo."; </script>";
?>
<div id="my_other_other_div"></div>
<input type="button" value="Add" onClick="addws()">
</td>
</tr>
</tbody>
<!-- END OF CON DIV -->
<tr>
<td width="10%" style="vertical-align:top;">Registration Links</td>
<td width="90%">
<?php echo '<input type="text" name="YouthLink" value="'.stripslashes($_POST['YouthLink']).'"/> Youth Link<br />
<input type="text" name="AdultLink" value="'.stripslashes($_POST['AdultLink']).'"/> Adult Link'; ?>
</td>
</tr>
<tr>
<td width="10%" style="vertical-align:top;">Start Date</td>
<td width="90%">
<select name='startmonth'>
<?php $idk = array("January","February","March","April","May","June","July","August","September","October","November","December");
foreach ($idk as $bob):
if($bob = $_POST['startmonth']) {
echo '<option value="'.$bob.'" selected="selected">'.$bob.'</option>';
} else {
echo '<option value="'.$bob.'">'.$bob.'</option>';
}
endforeach;
?>
</select>
<select name="startday">
<?php
$x = 1;
while($x <= 31) {
if((int)$_POST['startday'] == $x) {
echo "<option value='".$x."' selected='selected'>".$x."</option>";
} else {
echo "<option value='".$x."'>".$x."</option>";
}
$x++;
}
?>
</select>
<select name="startyear">
<?php $date = getdate();
for($x = 0;$x < 3;$x++) {
$y = (int)$date['year']+$x;
if($y == $_POST['startyear']) {
echo "<option value='".$y."' selected='selected'>".$y."</option>";
} else {
echo "<option value='".$y."'>".$y."</option>";
}
}
?>
</select>
</td>
</tr>
<tr>
<td width="10%" style="vertical-align:top;">End Date</td>
<td width="90%">
<select name='endmonth'>
<?php $idk = array("January","February","March","April","May","June","July","August","September","October","November","December");
foreach ($idk as $bob):
if($bob = $_POST['endmonth']) {
echo '<option value="'.$bob.'" selected="selected">'.$bob.'</option>';
} else {
echo '<option value="'.$bob.'">'.$bob.'</option>';
}
endforeach;
?>
</select>
<select name="endday">
<?php
$x = 1;
while($x <= 31) {
if((int)$_POST['endday'] < $x) {
echo "<option value='".$x."'>".$x."</option>";
} else if((int)$_POST['endday'] == $x) {
echo "<option value='".$x."' selected='selected'>".$x."</option>";
} else if((int)$_POST['endday'] > $x) {
echo "<option value='".$x."'>".$x."</option>";
}
$x++;
}
?>
</select>
<select name="endyear">
<?php $date = getdate();
for($x = 0;$x < 3;$x++) {
$y = (int)$date['year']+$x;
if($y == $_POST['endyear']) {
echo "<option value='".$y."' selected='selected'>".$y."</option>";
} else {
echo "<option value='".$y."'>".$y."</option>";
}
}
?>
</select>
</td>
</tr>
<tr>
<td width="10%" style="vertical-align:top;">Location</td>
<td width="90%">
<?php echo '<input type="text" name="location" value="'.stripslashes($_POST['location']).'" required="required"/>'; ?>
</td>
</tr>
<tr>
<td width="90%"></td>
<td width="10%">
<input type="hidden" name="blah" value="blah"/>
<input type="submit" name="woohoo" value="Save" align="right"/>
</td>
</table>
</form>
<?php if(isset($_POST['isyac'])) {
echo "<script language='javascript'>window.backUpHtml = document.getElementById('con_div').innerHTML;
document.getElementById('con_div').innerHTML = '';</script>"; ?>
}
</div>
</div>
<div style="clear: both;"> </div>
</div>
<!-- end #content -->
<div id="sidebar">
<?php include($_SERVER['DOCUMENT_ROOT'].'/resources/side.php'); ?>
</div>
<!-- end #sidebar -->
<div style="clear: both;"> </div>
</div>
<!-- end #page -->
<div id="footer-menu">
<ul>
<li class="current_page_item">Home</li>
<li>Events</li>
<li>Forums</li>
<li>About</li>
<li>Minutes</li>
<li>Documents</li>
<li>Contact Us</li>
</ul>
</div>
<div id="footer">
<p>Copyright © <?php $date = getdate(); echo $date['year']; ?> My Website. All rights reserved.</p>
</div>
<!-- end #footer -->
</body>
</html>
Your problem comes from this bit of code:
<?php if(isset($_POST['isyac'])) {
echo "<script language='javascript'>window.backUpHtml = document.getElementById('con_div').innerHTML;
document.getElementById('con_div').innerHTML = '';</script>"; ?>
}
the closing brace } needs to be inside the php tags (before the ?>)
I just glanced over your code and I would say this is probably it:
</form>
<?php if(isset($_POST['isyac'])) {
echo "<script language='javascript'>window.backUpHtml = document.getElementById('con_div').innerHTML;
document.getElementById('con_div').innerHTML = '';</script>"; ?>
}
</div>
Your end curly should be inside the ?>
</form>
<?php if(isset($_POST['isyac'])) {
echo "<script language='javascript'>window.backUpHtml = document.getElementById('con_div').innerHTML;
document.getElementById('con_div').innerHTML = '';</script>";
}
?>
</div>