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
Related
filter the record using selected field catname. Need to filter the course record using category filter. category id is selecting properly. I need to filter by category name. dropdown list from table category and the filter to be done in course table. Example : if $selected = 1 then $selectedcat="Information Technology" then pass it to the query. This way it works. But I need to filter using the category directly.
<?php
include('header-basic-light.php');
require_once('dbconnect.php');
$selsql="SELECT catno,catname FROM category";
$res=mysqli_query($con,$selsql);
if ($res == '')
{
echo "No connection";
die(mysqli_error($con));
}
$selected=0;
if (isset($_POST['categories']))
{
$selected=$_POST['categories'];
//echo $selected;
}
$selectsql="SELECT * FROM courses";
$res1=(mysqli_query($con,$selectsql));
if (!mysqli_query($con,$selectsql))
{
die(mysqli_error($con));
}
if ($selected==1)
{
$selectsql="SELECT * FROM courses where ccategory='$selectedcat'";
$res1=(mysqli_query($con,$selectsql));
}
else
if ($selected==2)
{
$selectsql="SELECT * FROM courses where ccategory='$selectedcat'";
$res1=(mysqli_query($con,$selectsql));
}
mysqli_close($con);
?>
<html>
<head>
<title>Drop down list </title>
<meta charset="UTF-8">
<meta name="viewport">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<label for="categories">Select the Category : </label>
<select name="categories" style="width:250px;" onchange="this.form.submit();">
<?php
while($row=mysqli_fetch_assoc($res)) {
if($selected==$row['catno']) {
$selectedcat= $row['catname'];
/* here you can get $selectedcat*/
}
?>
<option value="<?php echo $row['catno'];?>"
<?php
if($selected == $row['catno']) { echo 'selected="selected"'; }
?>
>
<?php echo $row['catname'];?>
</option>
<?php } ?>
</select>
</form>
<h2>View Information</h2>
<table class="table">
<tr>
<th>#</th>
<th>cname</th>
<th>start_date</th>
<th>duration</th>
<th>Remarks</th>
<th>Options</th>
</tr>
<?php
while ($r=mysqli_fetch_assoc($res1))
{
?>
<tr>
<td><?php echo $r['cno'];?></td>
<td><?php echo $r['cname'];?></td>
<td><?php echo $r['start_date'];?></td>
<td><?php echo $r['duration'];?></td>
<td><?php echo $r['remarks'];?></td>
<?php if ($r['ccategory']=='Information Technology') {$catnum=1;}
if ($r['ccategory']=='Management') {$catnum=2;} ?>
<td>Details  
</tr>
<?php } ?>
</table>
</body>
</html>
please try this
<?php
while($row=mysqli_fetch_assoc($res)) {
if($selected==$row['catno']) {
$selectedcat= $row['catname'];
/* here you can get $selectedcat*/
}
?>
<option value="<?php echo $row['catno'];?>"
<?php
if($selected == $row['catno']) { echo 'selected="selected"'; }
?>
>
<?php echo $row['catname'];?>
</option>
and please see updated answer and you should not close mysqli connection before any mysqli instruction.
so use mysqli_close($con); at the bottom of page or after you used all mysqli instruction in code
<?php
include('header-basic-light.php');
require_once('dbconnect.php');
$selsql="SELECT catno,catname FROM category";
$res=mysqli_query($con,$selsql);
if ($res == '')
{
echo "No connection";
die(mysqli_error($con));
}
$selected=0;
if (isset($_POST['categories']))
{
$selected=$_POST['categories'];
//echo $selected;
}
$selectsql="SELECT * FROM courses";
$res1 = mysqli_query($con,$selectsql);
if (!mysqli_query($con,$selectsql))
{
die(mysqli_error($con));
}
if ($selected != 0)
{
/* fetch $selectedcat from input hidden name hid_selected_cat_name*/
$selectedcat = mysqli_real_escape_string($con,trim($_POST['hid_selected_cat_name']));
$selectsql="SELECT * FROM courses where ccategory='$selectedcat'";
$res1=mysqli_query($con,$selectsql);
}
?>
<html>
<head>
<title>Drop down list </title>
<meta charset="UTF-8">
<meta name="viewport">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<label for="categories">Select the Category : </label>
<select name="categories" style="width:250px;" onchange="this.form.submit();">
<?php
while($row=mysqli_fetch_assoc($res)) {
if($selected==$row['catno']) {
$selectedcat= $row['catname'];
/* here you can get $selectedcat*/
}
?>
<option value="<?php echo $row['catno'];?>"
<?php
if($selected == $row['catno']) { echo 'selected="selected"'; }
?>
>
<?php echo $row['catname'];?>
</option>
<?php } ?>
</select>
/* store $selectedcat into hidden id*/
<input type="hidden" id="hid_selected_cat_name" name="hid_selected_cat_name" value="<?php echo $selectedcat;?>" >
</form>
<h2>View Information</h2>
<table class="table">
<tr>
<th>#</th>
<th>cname</th>
<th>start_date</th>
<th>duration</th>
<th>Remarks</th>
<th>Options</th>
</tr>
<?php
while ($r=mysqli_fetch_assoc($res1))
{
?>
<tr>
<td><?php echo $r['cno'];?></td>
<td><?php echo $r['cname'];?></td>
<td><?php echo $r['start_date'];?></td>
<td><?php echo $r['duration'];?></td>
<td><?php echo $r['remarks'];?></td>
<?php if ($r['ccategory']=='Information Technology') {$catnum=1;}
if ($r['ccategory']=='Management') {$catnum=2;} ?>
<td>Details  
</tr>
<?php } ?>
</table>
</body>
</html>
simple one. try this.
<?php
while($row=mysqli_fetch_assoc($res)) {
$selectedFlag = ($selected==$row['catno']) ? "selected" : "";
?>
<option value="<?php echo $row['catno'];?>" <?php echo $selectedFlag ?> >
<?php echo $selectedcat= $row['catname'];?>
</option>
<?php } ?>
I am making a page where it displays a table with staffID and staffName using PHP. When the user clicks the staffID it should then display a new table using the code from another file with extra details about that staffID such as shippingDate, OrderID, etc.
task9.php file below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Task 9</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<?php
$sID= isset($_GET['staffID']) ? $_GET['staffID'] : '';
$conn = mysqli_connect('localhost', 'TWA', 'TWA_test', 'factory');
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT s.staffID,s.staffName
FROM staff s";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
?>
<h1> Staff Table </h1>
<table>
<tr>
<th>Staff ID</th>
<th>Staff Name</th>
</tr>
<?php while($row = mysqli_fetch_array($results)) { ?>
<tr>
<td> <?php echo $row[0] ?></td>
<td><?php echo $row[1] ?></td>
</tr>
<?php } ?>
<?php mysqli_close($conn); ?>
</table>
</body>
</html>
task8.php asks a user to enter a staffID and it displays all of the details, if the staffID does not exist then it displays an error. This file works fine and displays everything correctly. task8.php file below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PHP Task 8</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<?php
$conn = mysqli_connect('localhost', 'TWA', 'TWA_test', 'factory');
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error());
}
//obtain the staff ID input from the $_GET array
$sID= isset($_GET['staffID']) ? $_GET['staffID'] : '';
$sql = "SELECT s.staffID, p.orderID, p.orderDate, p.shippingDate,s.staffName
FROM purchase p
INNER JOIN staff s
ON p.staffID = s.staffID
WHERE p.staffID = '$sID'";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
?>
<h1> Order Details </h1>
<?php $rows = mysqli_num_rows($results); ?>
<?php if($rows <= 0){ ?>
<p><?php echo "The staff ID entered is invalid"; ?></p>
<?php } else { ?>
<table>
<tr>
<th>Staff ID</th>
<th>Order ID</th>
<th>Order Date</th>
<th>Shipping Date</th>
<th>Staff Name</th>
</tr>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<?php if($row[0] != ""): ?>
<td><?php echo $row[0]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
<?php if($row[1] != ""): ?>
<td><?php echo $row[1]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
<?php if($row[2] != ""): ?>
<td><?php echo $row[2]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
<?php if($row[3] != ""): ?>
<td><?php echo $row[3]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
<?php if($row[4] != ""): ?>
<td><?php echo $row[4]; ?></td>
<?php else: ?>
<td><?php echo "N/A"; ?></td>
<?php endif; ?>
</tr>
<?php } ?>
<?php } ?>
<?php mysqli_close($conn); ?>
</table>
</body>
</html>
The problem I am facing is that when I click the staffID from the table on task9.php it just shows the error I included in task8.php "The staff ID entered is invalid". I don't know why it isn't displaying the details from task8.php
you did not build your link correctly, it should be
<?php echo $row[0] ?>
also, i feel somehow uncomfortable echoing outputs without htmlentities().
Yes, it is boring to type that everytime so i usually keep a function in every of my PHP projects like this
function e($whatToConvert){
return htmlentities($whatToConvert); //or htmlspecialchars
}
so the above code for instance becomes
<?php echo e($row[0]) ?>
You need to pass the parameter like this
<a href = "task8.php?staffID=<?php echo $row[0]?>">
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')";
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."',";
}
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.