I am trying to create a shopping cart and take the quantities in the cart to subtract from my inventory in my table in mysql. But everytime i try and update it keeps on subtracting the wrong amount. So far i have this.
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<center><B>Invoice</B></center>
<?php
require 'connect.php';
require 'item.php';
if(isset($_GET['id'])){
$result = mysqli_query($con, 'select * from products where
id='.$_GET['id']);
$products = mysqli_fetch_object($result);
$item = new Item();
$item->id = $products->id;
$item->name = $products->name;
$item->price = $products->price;
$item->quantity = 1;
// Check if the products exists in the cart
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0; $i<count($cart); $i++)
if($cart[$i]->id==$_GET['id'])
{
$index = $i;
break;
}
if($index==-1)
$_SESSION['cart'][] = $item;
else{
$cart[$index]->quantity++;
$_SESSION['cart'] = $cart;
}
}
// Delete products in cart
if(isset($_GET['index'])){
$cart = unserialize(serialize($_SESSION['cart']));
unset($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
?>
<table cellpadding="3" cellspacing="3" border="0">
<tr>
<th>Id</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub-Total</th>
</tr>
<?php
$cart = unserialize(serialize($_SESSION['cart']));
$s = 0;
$index = 0;
for($i=0; $i<count($cart); $i++){
?>
<tr>
<td><?php echo $cart[$i]->id; ?></td>
<td><?php echo $cart[$i]->name; ?></td>
<td><?php echo $cart[$i]->price; ?></td>
<td><?php echo $cart[$i]->quantity; ?></td>
<td><?php echo $cart[$i]->price * $cart[$i]->quantity; ?></td>
</tr>
<?php
$index++;
$quantitycart=$cart[$i]->quantity;
$idcart=$cart[$i]->id;
}
?>
<td><input type="submit" name="submit" value="submit"></td></tr>
<tr><td colspan="5"</tr>
<tr>
</tr>
</table><br>
<?php
if(array_key_exists('submit', $_POST))
{ $results = mysqli_query($con, 'select * from products');
for($i=0; $i<count($cart); $i++)
{
while($products= mysqli_fetch_object($results)){
$quantity= $products->quantity;
$newquantity= $quantity-$quantitycart;
$sql = "UPDATE products SET quantity='$newquantity' WHERE id='$idcart'";
}}
if ($con->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $con->error;
}
$con->close();
}
$con is my connnection. Any help would be appreciated. The main problem is located in the last part of the code.
Related
I already search more about this topic solution "How to insert multiple item into database", but i can't understand. Hope somebody can help me !
shopping cart
{
while($row=mysqli_fetch_array($res)){
$total=($row['product_price']*$row['quantity']);
$tot = $tot + ($row['product_price']*$row['quantity']);
?>
<tr>
<td align="center"><img src="<?php echo $item['product_image'];?>" width="150px" height="150px" alt=""/></td>
<td><?php echo $row['product_name'];?></td>
<td><?php echo $row['quantity'];?></td>
<td>RM <?php echo $total;?></td>
<td style="text-align:center"><a href="delete_shopping_cart_item.php?id=<?php echo $row["id"];?>" onclick="return confirm('Are you sure you want to delete this item?');">
Remove
</a></td>
</tr>
<?php
}
if(isset($_POST['submit1']))
{
$customer = $_SESSION['login_user'];
$res = mysqli_query($mysqli,"SELECT * FROM shopping_cart where customer ='$customer'");
$row=mysqli_fetch_array($res);
$qty = $row['quantity'];
$product_name = $row['product_name'];
$rname = $_POST['rname'];
$raddress = $_POST['raddress'];
$rcontactno = $_POST['rcontactno'];
$total = $_SESSION['total'] ;
mysqli_query($mysqli,"insert into confirm_order (product_name,quantity,total_price,receiver_name,receiver_address,receiver_contact,customer)
values('$product_name','$qty','$total','$rname','$raddress','$rcontactno','$customer')");
$_SESSION['receiver'] = $rname;
}
}
Try this:
while ($row=mysqli_fetch_array($res)) {
$qty = $row['quantity'];
$product_name = $row['product_name'];
$rname = $_POST['rname'];
$raddress = $_POST['raddress'];
$rcontactno = $_POST['rcontactno'];
$total = $_SESSION['total'] ;
mysqli_query($mysqli,"insert into confirm_order (product_name,quantity,total_price,receiver_name,receiver_address,receiver_contact,customer)
values('$product_name','$qty','$total','$rname','$raddress','$rcontactno','$customer')");
}
I am developing a page where a user can enter the limit of the table in pagination. While I am doing this the data I enter is taken and query is performed according to that. But as I click on another page of that table the value is reset to default which I set to 5 here.
<?php session_start(); ?>
Submit New record<br><br>
<form method="post">
<input type="text" name="dlimit">
<input type="submit" name="submit">
</form>
<?php
$database = 'test';
require 'connection.php';
if(!isset($_POST['submit']))
{
$limit = 5;
}
else
{
$dlimit = $_POST['dlimit'];
$limit = $dlimit;
}
#$id = $_GET['id'];
if($id==""||$id==null)
{
$page=0;
}
else
{
$page = ($id*$limit)-$limit;
}
$qq ="select * from record limit $page,$limit";
$result = $link -> query($qq);
?>
<table border="1"><th>ID</th>
<th>Name</th>
<th>qualification</th>
<th>address</th>
</tr>
<?php
while ($row = mysqli_fetch_object($result))
{
?>
<tr>
<td><?php echo $row->id ?></td>
<td><?php echo $row->user_name ?></td>
<td><?php echo $row->qualification ?></td>
<td><?php echo $row->address ?></td>
</tr>
<?php
}
?>
</table>
<?php
$query = "SELECT * FROM record";
$result = $link -> query($query);
$rows = mysqli_num_rows($result);
$rr = $rows/$limit;
$rr = ceil($rr);
for ($i=1; $i<=$rr ; $i++) {
?>
<?php echo #$i;?>
<?php
}
mysqli_close($link)
?>
Run the above code and check. If my words are not clear to you.
I think that the $_POST data is missing. You click on the link, so the new page will open without POST infos.
You can change this, if you switch to GET instead of POST. You can add the GET parameter to your <a href=""> Tag.
For example
<a href="pagination.php?page=5&dlimit=100
Also try to avoid the #error suppression and don't pass the $_POST/$_GET Vars directly to your sql string. Bad people could use it for SQL Injections
So I got the answer for my question. I am posting it here if anyone need it on later basis.
Submit New record<br><br>
<form method="get">
<input type="text" name="dlimit">
<input type="submit" name="submit">
</form>
<?php
$database = 'test';
require 'connection.php';
if(empty($_GET['dlimit']) && !isset($_GET['submit']) && empty($_GET['n']))
{
$limit = 5;
global $limit;
}
else
{
if (isset($_GET['dlimit']))
{
$limit = $_GET['dlimit'];
}
else
{
#$limit = $_GET['n'];
}
global $limit;
}
if(!isset($_GET['submit'])&& empty($_GET['n']))
{
$n=5;
global $n;
}
else
{
if(empty($_GET['dlimit']))
{
$n=$_GET['n'];
}
else
{
$n=$_GET['dlimit'];
}
global $n;
}
#$id = $_GET['id'];
if($id==""||$id==null)
{
$page=0;
}
else
{
$page = ($id*$limit)-$limit;
}
$qq ="select * from record limit $page,$limit";
$result = $link -> query($qq);
?>
<table border="1"><th>ID</th>
<th>Name</th>
<th>qualification</th>
<th>address</th>
</tr>
<?php
while ($row = mysqli_fetch_object($result))
{
?>
<tr>
<td><?php echo $row->id ?></td>
<td><?php echo $row->user_name ?></td>
<td><?php echo $row->qualification ?></td>
<td><?php echo $row->address ?></td>
</tr>
<?php
}
?>
</table>
<?php
if (!isset($_GET['submit']) && empty($_GET['n'])) {
$n = 5;
global $n;
}
else
{
if (empty($_GET['dlimit'])) {
$n = $_GET['n'];
}
else
{
$n = $_GET['dlimit'];
}
global $n;
}
$query = "SELECT * FROM record";
$result = $link -> query($query);
$rows = mysqli_num_rows($result);
$rr = $rows/$limit;
$rr = ceil($rr);
for ($i=1; $i<=$rr ; $i++) {
?>
<?php echo #$i;?>
<?php
}
mysqli_close($link)
?>
Again I am mentioning here that files which I included here are just connection where I filled my connection details and other is my record entry file where data is entered by the user.
I have add to cart already but I don't want to reload the page when I click Add to Cart Button so I can still choose other products even its not reloading the page.
Index.php
<?php
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}else{
$sql_p="SELECT * FROM products WHERE product_id={$id}";
$query_p=mysqli_query($con, $sql_p);
if(mysqli_num_rows($query_p)!=0){
$row_p=mysqli_fetch_array($query_p);
$_SESSION['cart'][$row_p['product_id']]=array("quantity" => 1, "price" => $row_p['product_price']);
}else{
$message="Product ID is invalid";
}
}
}
?>
product.php
<?php
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}else{
$sql_p="SELECT * FROM products WHERE product_id={$id}";
$query_p=mysqli_query($con, $sql_p);
if(mysqli_num_rows($query_p)!=0){
$row_p=mysqli_fetch_array($query_p);
$_SESSION['cart'][$row_p['product_id']]=array("quantity" => 1, "price" => $row_p['product_price']);
}else{
$message="Product ID is invalid";
}
}
}
?>
<h1>Products</h1>
<?php
if(isset($message)){
echo "<h2>$message</h2>";
}
?>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Items Price</th>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM products WHERE product_category= 'Chicken' ORDER BY product_name ASC");
while($row=mysqli_fetch_assoc($query)){
?>
<tr>
<td><?php echo $row['product_name']; ?></td>
<td><?php echo $row['product_description']; ?></td>
<td><?php echo "$" . $row['product_price']; ?></td>
<td>Add to Cart</td>
</tr>
<?php
}
?>
</table>
Cart.php
<?php
if(isset($_POST['submit'])){
if(!empty($_SESSION['cart'])){
foreach($_POST['quantity'] as $key => $val){
if($val==0){
unset($_SESSION['cart'][$key]);
}else{
$_SESSION['cart'][$key]['quantity']=$val;
}
}
}
}
?>
<h1>View Cart || Products</h1>
<form method="post" action="index.php?page=cart">
<table>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Subtotal</th>
</tr>
<?php
$sql = "SELECT * FROM products WHERE product_id IN(";
foreach($_SESSION['cart'] as $id => $value){
$sql .=$id. ",";
}
$sql=substr($sql,0,-1) . ") ORDER BY product_id ASC";
$query = mysqli_query($con, $sql);
$totalprice=0;
if(!empty($query)){
while($row = mysqli_fetch_array($query)){
$subtotal= $_SESSION['cart'][$row['product_id']]['quantity']*$row['product_price'];
$totalprice += $subtotal;
?>
<tr>
<td><?php echo $row['product_name']; ?></td>
<td><input type="text" name="quantity[<?php echo $row['product_id']; ?>]" size="6" value="<?php echo $_SESSION['cart'][$row['product_id']]['quantity']; ?>"> </td>
<td><?php echo "$" .$row['product_price']; ?></td>
<td><?php echo "$" .$_SESSION['cart'][$row['product_id']]['quantity']*$row['product_price']. ".00"; ?></td>
</tr>
<?php
}
}else{
?>
<tr><td colspan="4"><?php echo "<i>Add product to your cart."; ?></td></tr>
<?php
}
?>
<tr>
<td colspan="3">Total Price: <h1><?php echo "$" ."$totalprice". ".00"; ?></h1><td>
</tr>
</table>
<br/><button type="submit" name="submit">Update Cart</button>
</form>
<br/><p>To remove an item, set quantity to 0.</p>
//how to solve this please all kind guys can direct change code, my error is undifined offset value of product_id
<?php
include('dataconn.php');
$result=mysql_query("select * from product");
while($row=mysql_fetch_assoc($result))
{
echo "<p>$row[Product_Name]</p>";
echo "<p>$row[Product_Quantity]</p>";
echo "<p>Add To Cart</p>";
}
?>
logout
/*--add to cart page--*/
<?php
/* ----------- ADD TO CART PAGE ----------------*/
include("dataconn.php");
$product_id = isset($_GET['pid']) ? $_GET['pid'] : null;
$action = isset($_GET['action']) ? $_GET['action'] : null; //the action
$quantity=isset($_GET['qty']) ? $_GET['qty'] : null;
?>
<html>
<head>
<title>View Cart</title>
</head>
<body>
<?php
$customer_id=$_SESSION['customer_id'];
$result=mysql_query("select * from product");
$row=mysql_fetch_assoc($result);
switch($action)
{
//decide what to do
case "add":
$_SESSION['cart'][$product_id]++;
break;
case "remove":
$_SESSION['cart'][$product_id] = 0;
unset($_SESSION['cart'][$product_id]);
header("Location: payment.php");//if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
header("Location: payment.php");
break;
}
//------- for checkout ---------
if(isset($_SESSION['cart']) && $_SESSION['cart']) {
$total = 0;
echo "<form name='cart' method='POST' action=''>";
echo "<table border=\"1\" padding=\"3\" width=\"100%\" class=\"data-container\">";
echo "<td colspan=\"4\" align=\"right\"><img src=\"image/delete.png\"/></td>";
foreach($_SESSION['cart'] as $product_id => $quantity)
{
$sql = sprintf("SELECT * FROM product WHERE Product_ID = %d;", $product_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$itemsInfo = mysql_fetch_assoc($result);
$cost = $itemsInfo["Product_Price"] * $quantity;
$total = $total + $cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">".$itemsInfo["Product_Name"]."</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity </td>";
echo "<td align=\"center\">RM $cost</td>";
echo "<td align=\"center\"><img src=\"image/remove.png\"/></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" ></td>";
echo "<td align=\"center\">Total</td>";
echo "<td colspan=\"2\" align=\"center\">RM $total</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
?>
<br>
<div>
<span style="margin-left: 88%"><input type="submit" name="shopping_more" class="custom-button" value="Back To Shopping"/></span>
</div>
</html>
I'm making a shopping cart and I'm stuck on the actual cart. I've read a few questions on here and tried them but either they don't work for me, or they're plain rubbish.
PHP Code: addtocart.php
if(isset($_GET['product_id']) && isset($_GET['qty'])){
$product_id = $_GET['product_id'];
$qty = $_GET['qty'];
$cart = $_SESSION['cart'];
if($cart == null) {
$cart = array();
}
if(!isset($cart[$product_id])) {
$cart[$product_id] = 0;
}
$cart[$product_id] += $qty;
//var_dump($cart);
}
$session->setSetting("cart", $cart);
PHP Code: cart.php
try {
if(empty($_GET)) {
$cart = $session->getSetting("cart");
if($cart == null) {
throw new Exception("Empty cart.");
} else {
$template->setVar("cart", $cart);
} elseif($_GET['action'] == 'empty') {
unset($_SESSION['cart']);
header("location: /cart.php");
}
}
} catch (Exception $e) {
$template->setVar("errmsg", $e->getMessage());
}
Output:
<table class="table table-bordered table-striped table-condensed">
<?php foreach($this->cart as $product_id => $qty):
$item = $this->product->buildTotal($product_id); //var_dump($item);
?>
<tr>
<th>Items</th>
<td><?php echo count($item); ?>
</td>
<tr>
<th>Sub-total</th>
<td>
£<?php echo $price = number_format(($item[0]['product_price'] * $qty), 2); ?>
</td>
</tr>
<tr>
<th>Shipping</th>
<td>
£<?php echo $shipping = "2.95"; ?>
</td>
</tr>
<tr class="warning">
<th>Tax</th>
<td>20%</td>
</tr>
<tr class="success">
<th>Total</th>
<td>£<?php $tax = (($price * 20) / 100);
$total = ($price + $tax + $shipping);
echo number_format($total, 2); ?>
</td>
</tr>
<?php endforeach; ?>
Unfortunately, my error is that the totals table at the bottom of the cart displays 'x' amount of times for 'x' amount of products, example of two products makes the table display twice, rather than just totaling up the different prices etc. I've been stuck on this for three days so any help is greatly appreciated. Also, if your answer works, I'll list you in the credits page of the cart.
I'm trying to display my products from the database. I'm trying to split it using the if 4%=0, but I can't get it to display 4 items in a row.
Here is my codes:
<table>
<tr>
<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products
ORDER BY FIELD(category, 'ipad','iphone','others')");
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
$split++;
if ($split%4==0){
echo '</tr><tr>';
}
?>
<td>
<table class="normal_text" align="center">
<tr>
<td><a href="product.php?product_id=<?php echo $id?>">
<img width="200px" height="133px" src="products/<?php echo $product_code?>.jpg" />
</a></td>
</tr>
<tr>
<td align="center" style="font-weight:bold"><?php echo $title;?></td>
</tr>
<tr>
<td align="center">$<?php echo $price;?></td>
</tr>
</table>
</td>
<?php
}
?>
</tr>
</table>
You've got the PHP logic before, rather than inside your HTML table output.
Try reorganizing like this:
<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products
ORDER BY FIELD(category, 'ipad','iphone','others')");
?>
<table class="normal_text" align="center">
<tr>
<?php
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
// output product details -- note use of quotes to include PHP vars
$rowHTML = "<td><a href='product.php?product_id=$id'>";
$rowHTML .= "<img width='200px' height='133px' src='products/$product_code.jpg' />";
$rowHTML .= "</a><br/>";
$rowHTML .= "<strong>$title</strong>";
$rowHTML .= "$price</td>";
echo $rowHTML;
$split++;
if ($split%4==0){
echo '</tr><tr>';
}
}
?>
</tr>
</table>
while($row=mysql_fetch_assoc($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
if ($split % 4 === 0) echo "\n<tr>";
?>
// ONLY <td> CODE </td> here. NO <tr> and NO </table>
<?php
if ($split % 4 === 3) echo "</tr>";
$split++;
}
?>
You are starting and ending at same time and then putting table for each.
You want to start <tr> when %4==0 and end </tr> when %4==3.
Rather than use modulus (%), just add a second variable called $cols, assign it to the amount of columns you want, and compare it. For example:
$rows = 1;
$cols = 4;
$display_all = mysql_query("SELECT * FROM products ORDER BY FIELD(category, 'ipad','iphone','others')");
while($row=mysql_fetch_array($display_all)) {
$id = $row['id'];
$product_code = $row['product_code'];
$title = $row['title'];
$price = $row['price'];
$split++;
if ($rows==$cols){
echo '</tr><tr>';
$rows = 1;
}