Error insert data into table - php

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.

Related

Delete row data from one table using check box and insert the deleted row data in another table

/*I have two table , 1st table name is bazar and 2nd table name is bazarduepayment having same columne name : sl,date,item,paid,due,remark. 'sl' is auto increment . Delete function is working perfectly . Someone please help me how to insert deleted row data in 2nd table 'bazarduepayment' Here below is code detail i wrote */
<?php
session_start();
include_once("rwdbconnection.php");
error_reporting(0);
if(isset($_POST['save']))
{
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++)
{
$del_id = $checkbox[$i];
mysqli_query($conn,"DELETE FROM bazar WHERE sl='".$del_id."'");
$message = "Data deleted successfully !";
}
}
$result = mysqli_query($conn,"SELECT * FROM bazar");
?>
<!DOCTYPE html>
<html>
<head>
<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Delete data</title>
</head>
<body>
<div>
<?php if(isset($message)) { echo $message; } ?>
</div>
<form method="post" action="">
<table class="table table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="checkAl"> Select All</th>
<th>Sl</th>
<th>Date</th>
<th>Item</th>
<th>Paid</th>
<th>Due</th>
<th>Remark</th>
</tr>
</thead>
<?php
$i=0;
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><input type="checkbox" id="checkItem" name="check[]" value="<?php echo $row["sl"]; ?>"></td>
<td><?php echo $row["sl"]; ?></td>
<td><?php echo $row["date"]; ?></td>
<td><?php echo $row["item"]; ?></td>
<td><?php echo $row["paid"]; ?></td>
<td><?php echo $row["due"]; ?></td>
<td><?php echo $row["remark"]; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
<p align="center"><button type="submit" class="btn btn-success" name="save">DELETE</button></p>
</form>
<script>
$("#checkAl").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
</script>
</body>
</html>
First you need to copy the data from one table to another using INSERT ... SELECT syntax and only then you can delete.
You should be using prepared statements for this.
if (isset($_POST['save'])) {
// Prepared INSERT query
$stmt_insert = $conn->prepare('INSERT INTO bazarduepayment(date,item,paid,due,remark)
SELECT date,item,paid,due,remark FROM bazar WHERE sl=?');
// Prepare DELETE query
$stmt_delete = $conn->prepare('DELETE FROM bazar WHERE sl=?');
// Loop on all checkboxes selected
foreach ($_POST['check'] as $del_id) {
$stmt_insert->bind_param('s', $del_id);
$stmt_insert->execute();
$stmt_delete->bind_param('s', $del_id);
$stmt_delete->execute();
}
}
You could even simplify this to get rid of the foreach loop entirely.

PHP, Error in Shopping Cart Program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to create a Shopping Cart in PHP. It worked fine. But then I removed all items from the Shopping Cart and it failed. I think it has something with the session, but I not complete sure.
I am getting this error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\phpshop\index.php on line 85
Call Stack
# Time Memory Function Location
1 0.0002 244096 {main}( ) ...\index.php:0
2 0.0017 255352 mysqli_fetch_array ( )
I used this Shopping cart tutorial to build this program.
cart.php code:
<?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 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 id_product IN (";
foreach($_SESSION['cart'] as $id => $value)
{
$sql.=$id.",";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
line 85 about here ---> $query = mysqli_query($con,$sql);
$totalprice=0;
$numrows = mysqli_num_rows($query);
if($numrows == 0)
{
header("Location: index.php");
}
while($row=mysqli_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>
</form>
<br />
<p>To remove an item, set it's quantity to 0. </p>
index.php
<?php
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 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.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 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.",";
}
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query = mysqli_query($con,$sql);
while($row=mysqli_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 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=mysqli_query($con,$sql_s);
if(mysqli_num_rows($query_s)!=0)
{
$row_s=mysqli_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>
<?php
$sql = "SELECT * FROM products ORDER BY name ASC";
$query = mysqli_query($con,$sql);
while ($row=mysqli_fetch_array($query)) {
?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['description'] ?></td>
<td><?php echo $row['price'] ?>$</td>
<td>Add to cart</td>
</tr>
<?php
}
?>
</table>
Your assignment of
$query = mysqli_query($con,$sql);
is failing and returning a boolean value of FALSE. This is because $con is not being set properly.
http://php.net/manual/en/mysqli.query.php
so, you are passing FALSE into mysqli_fetch_array as the $query
while($row=mysqli_fetch_array($query))
This is causing the error you reported
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\phpshop\index.php on line 85

Shopping cart using 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.

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."',";
}

Categories