Save session data to table - php

I am after two bits of advice for a project I am working on and would really appreciate any advice you may have..
I have the below code and its working really well as a shopping cart for a student project. At the end of the code, I would like to save all the items added to the shopping cart in the table at the bottom to a MySQL table called orders for example.
Is this possible to do?
Also, for each item for sale on the page there is an image. Is it possible hover over the image and the description from the MySQL table is shown in a hover box?
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "WineCellar");
if(isset($_POST["add_to_cart"]))
{
if(isset($_SESSION["shopping_cart"]))
{
$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 '<script>window.location="Shop.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="shop.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>The Wine Cellar</title>
<script src="style/jquery.min.js"></script>
<link rel="stylesheet" href="style/bootstrap.min.css" />
<script src="style/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container" style="width:700px;">
<h3 align="center"><img src="Images/slide1.jpg" width="644" height="176"></h3>
<p align="center"><br />
<?php
$query = "SELECT * FROM tbl_product ORDER BY id ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
</p>
<div class="col-md-4">
<form method="post" action="shop.php?action=add&id=<?php echo $row["id"]; ?>">
<div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
<img src="<?php echo $row["image"]; ?>" class="img-responsive" /><br />
<h4 class="text-info"><?php echo $row["name"]; ?></h4>
<h4 class="text-danger">$ <?php echo $row["price"]; ?></h4>
<input type="text" name="quantity" class="form-control" value="1" />
<input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
</div>
</form>
</div>
<?php
}
}
?>
<div style="clear:both"></div>
<br />
<h3>Order Details</h3>
<div class="table-responsive">
<table class="table table-bordered">
<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><span class="text-danger">Remove</span></td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["item_price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<br />
</body>
</html>
Thanks in advance
Shane

Related

Submit button not adding items to shopping cart in my PHP page

I'm trying to follow a simple add to cart tutorial using php, sql, with my database on phpmyadmin, but when the user clicks "add to cart", nothing is displayed in the shopping cart table.
Any non-php solutions are welcome.
Here is the tutorial: http://www.webslesson.info/2016/08/simple-php-mysql-shopping-cart.html
Thank you!
<?php
session_start();
require_once ('database_conn.php');
if (isset($_POST["add_to_cart"])) {
if (isset($_SESSION["shopping_cart"])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "productID");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
} else {
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_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="add.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container" style="width:700px;">
<?php
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : null;
$sqlProducts = "SELECT productID, productName, productPrice, productImage, productAisle
FROM s_products WHERE productName LIKE '%$name%'";
$rProducts = mysqli_query($conn, $sqlProducts) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($rProducts)) {
$productID = $row['productID'];
$productName = $row['productName'];
$productImage = $row['productImage'];
$productAisle = $row['productAisle'];
{
?>
<div class="col-md-4">
<form method="post" action="add.php?action=add&id=<?php echo $row["id"]; ?>">
<div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">
<img src="<?php echo $row["productImage"]; ?>" class="img-responsive" /><br />
<h4 class="text-info"><?php echo $row["productName"]; ?></h4>
<h4 class="text-danger">$ <?php echo $row["productPrice"]; ?></h4>
<input type="text" name="quantity" class="form-control" value="1" />
<input type="hidden" name="hidden_name" value="<?php echo $row["productName"]; ?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["productPrice"]; ?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />
</div>
</form>
</div>
<?php
}
}
?>
<div style="clear:both"></div>
<br />
<h3>Order Details</h3>
<div class="table-responsive">
<table class="table table-bordered">
<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 "$productName"; ?></td>
<td><?php echo "$productPrice"; ?></td>
<td>$ <?php echo "$productAisle"; ?></td>
<td><a href="add.php?action=delete&id=<?php echo "$productID";
}
?>"><span class="text-danger">Remove</span></a></td>
</tr>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<br />
</body>
</html>
Giving you a whole reworked code base for you.
<?php
session_start();
require_once('database_conn.php');
if (isset($_POST["add_to_cart"])) {
if (isset($_SESSION["shopping_cart"]) && !empty($_SESSION['shopping_cart'])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "productID");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
} else {
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if (!empty($_GET["action"])) {
switch ($_GET['action']) {
case '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="add.php"</script>';
}
}
break;
case 'add':
if (isset($_SESSION["shopping_cart"]) && !empty($_SESSION['shopping_cart'])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "productID");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
} else {
$item_array = array(
'productID' => $_GET["productID"],
'productName' => $_POST["productName"],
'productPrice' => $_POST["productPrice"],
'productAisle' => $_POST["productAisle"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
break;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br/>
<div class="container" style="width:700px;">
<?php
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : null;
$sqlProducts = "SELECT productID, productName, productPrice, productImage, productAisle
FROM s_products WHERE productName LIKE '%$name%'";
$rProducts = mysqli_query($conn, $sqlProducts) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($rProducts)) {
?>
<div class="col-md-4">
<form method="post" action="add.php?action=add&productID=<?php echo $row["id"]; ?>">
<div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;"
align="center">
<img src="<?php echo $row["productImage"]; ?>" class="img-responsive"/><br/>
<h4 class="text-info"><?php echo $row["productName"]; ?></h4>
<h4 class="text-danger">$ <?php echo $row["productPrice"]; ?></h4>
<input type="text" name="quantity" class="form-control" value="1"/>
<input type="hidden" name="productName" id="productName" value="<?= $row["productName"] ?>"/>
<input type="hidden" name="productPrice" id="productPrice" value="<?= $row["productPrice"] ?>"/>
<input type="hidden" name="productAisle" id="productAisle" value="<?= $row['productAisle'] ?>"/>
<input type="hidden" name="hidden_name" value="<?php echo $row["productName"]; ?>"/>
<input type="hidden" name="hidden_price" value="<?php echo $row["productPrice"]; ?>"/>
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success"
value="Add to Cart"/>
</div>
</form>
</div>
<?php
}
?>
<div style="clear:both"></div>
<br/>
<h3>Order Details</h3>
<div class="table-responsive">
<table class="table table-bordered">
<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><?= $values['productName'] ?></td>
<td><?= $values['productPrice'] ?></td>
<td>$ <?= $values['productAisle'] ?></td>
<td><span class="text-danger">Remove</span>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<br/>
</body>
</html>

how to insert php cart data into mysql database

I have developed shopping cart in PHP but while inserting cart data into the database I got an error of undefined index. Can anybody please tell me how do I solve it? I have called all the three values using POST method and these all are also present in the database still i am getting this error.Why?
Code:
reviewcart.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "midata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$code=$_POST['code'];
$quantity=$_POST['quantity'];
$sql = "INSERT INTO order_final (name, code, quantity)
VALUES ('$name', '$code', '$quantity')";
if ($conn->query($sql) === TRUE) {
}
else{
}
}
else{ echo 'query doesnt execute';
}
?>
<div class="container">
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "remove":
if(!empty($_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($_GET["code"] == $k)
unset($_SESSION["cart_item"][$k]);
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
}
break;
case "empty":
unset($_SESSION["cart_item"]);
break;
}
}
?>
<div class="c-layout-sidebar-content ">
<!-- BEGIN: PAGE CONTENT -->
<div class="c-content-title-1 c-margin-t-30">
<h3 class="c-font-uppercase c-font-bold c-center ">Place Order</h3>
<div class="c-content-panel">
<div class="c-body">
<div class="row">
<div class="col-md-12">
<table class="table table-condensed">
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart <a id="btnEmpty" href="reviewcart.php?action=empty">Empty Cart</a></div>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?>
<table class="col-md-12" cellpadding="10" cellspacing="1" >
<tbody class="col-md-12">
<tr>
<form action="" method="post">
<th class="col-md-3" style="text-align:center;"><strong>Name</strong></th>
<th class="col-md-3" style="text-align:center;"><strong>Code</strong></th>
<th class="col-md-3" style="text-align:center;"><strong>Quantity</strong></th>
<th class="col-md-3" style="text-align:center;"><strong>Price</strong></th>
<th class="col-md-3" style="text-align:center;"><strong>Action</strong></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;"><strong><?php $name=$_POST['name'] ; echo $item["name"]; ?></strong></td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;"><?php $code=$_POST['code'] ; echo $item["code"]; ?></td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;"><?php $quantity=$_POST['quantity'] ; echo $item["quantity"]; ?></td>
<!-- <td style="text-align:center;border-bottom:#F0F0F0 1px solid;"><?php $price=$_POST['price'] ; echo $price ?></td> -->
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">Remove Item</td>
</tr>
<!-- <?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
-->
<tr>
<td colspan="5" align=right><input type="submit" name="submit" value="submit" /></td>
</tr></form>
</tbody>
</table>
<?php
}
?>
</div>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
If we want to post any data via form mean we must want to use input tag then only we can accept it values on global arrays like $_POST, $_GET, $_FILES.
<tr>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">
<strong><?php echo $item["name"]; ?></strong>
<input type="hidden" name="name" value="<?php echo $item['name']?>">
</td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">
<?php echo $item["code"]; ?>
<input type="hidden" name="code" value="<?php echo $item['code']?>">
</td>
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">
<?php echo $item["quantity"]; ?>
<input type="hidden" name="quantity" value="<?php echo $item['quantity']?>">
</td>
<!-- <td style="text-align:center;border-bottom:#F0F0F0 1px solid;">
<?php $price=$_POST['price'] ; echo $price ?>
</td> -->
<td style="text-align:center;border-bottom:#F0F0F0 1px solid;">
<a href="reviewcart.php?action=remove&code=<?php echo $item["code"]; ?>" class="btnRemoveAction">
Remove Item
</a>
</td>
</tr>

Value inserting on last row

Shown in the image above, I have two entries on my stock_transfer table.
As an example, I will insert two different values to show you that it's working. (5 stocks on Product 1 and 10 stocks on Product 2)
Now, when I try to insert the stocks requested remaining on Product 1 and leave the Product 2, it will be successful.
Here comes the problem. When I try to insert value (290 stocks) on my Product 2, it will insert the value in the Product 1 table.
Can anyone help me with this? Here's my query code:
if (isset($_POST['addCart']) && $_POST['addCart']=="Confirm Stock Transfer") {
foreach($_POST['qtyBuy'] as $index=>$value){
if($value > 0){
$cartProd_id = $_POST['product_id'][$index];
$cartProd_name = $_POST['product_name'][$index];
$cartProd_date = $_POST['product_exp'][$index];
$cartProd_desc = $_POST['product_desc'][$index];
$cartProd_transid = $_POST['transfer_id'][$index];
//Update stock_transfer requests
$update_stock = "UPDATE stock_transfer SET stocks_transferred = stocks_transferred + $value WHERE transfer_id = $cartProd_transid;";
$update_stockE = mysqli_query($connection, $update_stock);
Here's is my code:
<table class="table table-striped table-bordered table-hover results table-fixed table-condensed" id="example">
<thead>
<tr>
<th>#</th>
<th>Product Name</th>
<th>Description</th>
<th>Sell Price</th>
<th>Expiry Date</th>
<th>Instock</th>
<th>Stocks Requested Remaining</th>
<th>Stocks Transferred</th>
<th>Quantity to Transfer</th>
</tr>
</thead>
<tbody>
<?php
$getReq = "SELECT * FROM stock_transfer INNER JOIN td_products ON stock_transfer.transfer_product_id = td_products.product_id WHERE stock_transfer.transfer_number = $tid AND stock_transfer.transfer_tobranch = '$capitalPrefix';";
$getReqE = mysqli_query($connection, $getReq);
while ($row = mysqli_fetch_array($getReqE)) {
$transfer_id = $row['transfer_id'];
$transfer_number = $row['transfer_number'];
$transfer_status = $row['transfer_status'];
$transfer_frombranch = $row['transfer_frombranch'];
$transfer_tobranch = $row['transfer_tobranch'];
$transfer_product_id = $row['transfer_product_id'];
$transfer_quantity = $row['transfer_quantity'];
$transfer_date = $row['transfer_date'];
$stocks_transferred = $row['stocks_transferred'];
$remainingStocks = $transfer_quantity - $stocks_transferred;
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$product_price = $row['sell_price'];
$description = $row['description'];
$quantity = $row['quantity'];
$expiry_date = $row['expiry_date'];
echo $transfer_id;
?>
<tr>
<td class="text-center"><?php echo $product_id; ?>
<input type="hidden" name="product_id[]" value="<?php echo $product_id; ?>">
</td>
<input type="hidden" name="transfer_id[]" value="<?php echo $transfer_id; ?>">
<td><?php echo $product_name; ?>
<input type="hidden" name="product_name[]" value="<?php echo $product_name; ?>">
</td>
<td><?php echo $description; ?>
<input type="hidden" name="product_desc[]" value="<?php echo $description; ?>">
</td>
<td>₱ <?php echo number_format($product_price, 2); ?></td>
<td><?php echo $expiry_date; ?>
<input type="hidden" name="product_exp[]" value="<?php echo $expiry_date; ?>">
</td>
<td><strong><?php echo $quantity; ?></strong></td>
<td><?php echo $remainingStocks; ?></td>
<td><?php echo $stocks_transferred; ?></td>
<td>
<?php if (!$remainingStocks == 0){ ?>
<input type="number" name="qtyBuy[]" id="<?php echo "qtyBuy" . $b++; ?>" min="1" max="<?php echo $remainingStocks;?>">
<?php } else{ ?>
<i class="glyphicon glyphicon-check"></i> Completed
<?php } ?>
</td>
</tr>
<?php }?>
</tbody>
</table>
<div class="form-group">
<input type="submit" name="addCart" value="Confirm Stock Transfer" class="btn btn-info pull-right">
Back to Request List
</div>
Tags
Here's my schema:
See this:
<td>
<input type="number" name="qtyBuy[]" id="<?php echo "qtyBuy" . $b++; ?>" min="1" max="<?php echo $remainingStocks;?>" <?php echo ($remainingStocks == 0') ? 'Disabled=true' : '';?> value="0">
</td>
for security issues, I advise you to use ajax and submit just the qty input for one row each time:
<table class="table table-striped table-bordered table-hover results table-fixed table-condensed" id="example">
<thead>
<tr>
<th>#</th>
<th>Product Name</th>
<th>Description</th>
<th>Sell Price</th>
<th>Expiry Date</th>
<th>Instock</th>
<th>Stocks Requested Remaining</th>
<th>Stocks Transferred</th>
<th>Quantity to Transfer</th>
</tr>
</thead>
<tbody>
<?php
$getReq = "SELECT * FROM stock_transfer INNER JOIN td_products ON stock_transfer.transfer_product_id = td_products.product_id WHERE stock_transfer.transfer_number = $tid AND stock_transfer.transfer_tobranch = '$capitalPrefix';";
$getReqE = mysqli_query($connection, $getReq);
while ($row = mysqli_fetch_array($getReqE)) {
$transfer_id = $row['transfer_id'];
$transfer_number = $row['transfer_number'];
$transfer_status = $row['transfer_status'];
$transfer_frombranch = $row['transfer_frombranch'];
$transfer_tobranch = $row['transfer_tobranch'];
$transfer_product_id = $row['transfer_product_id'];
$transfer_quantity = $row['transfer_quantity'];
$transfer_date = $row['transfer_date'];
$stocks_transferred = $row['stocks_transferred'];
$remainingStocks = $transfer_quantity - $stocks_transferred;
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$product_price = $row['sell_price'];
$description = $row['description'];
$quantity = $row['quantity'];
$expiry_date = $row['expiry_date'];
echo $transfer_id;
?>
<tr>
<td class="text-center"><?php echo $product_id; ?>
</td>
<td><?php echo $product_name; ?>
</td>
<td><?php echo $description; ?>
</td>
<td>₱ <?php echo number_format($product_price, 2); ?></td>
<td><?php echo $expiry_date; ?>
</td>
<td><strong><?php echo $quantity; ?></strong></td>
<td><?php echo $remainingStocks; ?></td>
<td><?php echo $stocks_transferred; ?></td>
<td>
<?php if (!$remainingStocks == 0){ ?>
<input type="number" name="qtyBuy[]" id="qty_buy_<?= $transfer_id ?>" min="1" max="<?php echo $remainingStocks;?>"><a class="btn btn-sm add_qty" data-id="<?= $transfer_id ?>"></a>
<?php } else{ ?>
<i class="glyphicon glyphicon-check"></i> Completed
<?php } ?>
</td>
</tr>
<?php }?>
</tbody>
</table>
<div class="form-group">
<input type="submit" name="addCart" value="Confirm Stock Transfer" class="btn btn-info pull-right">
Back to Request List
</div>
<script>
$(function() {
$('.add_qty').click(function() {
var id = $(this).data('id');
var qty = $("#qty_buy_"+id).val();
$.ajax({
type: 'GET',
url:'/your_action',
data: {id : id, qty : qty},
dataType: 'JSON',
}).done(function(json){
// code to update the values in your row
});
});
});
</script>
The problem was on the
<?php if (!$remainingStocks == 0){ ?>
<input type="number" name="qtyBuy[]" id="<?php echo "qtyBuy" . $b++; ?>" min="1" max="<?php echo $remainingStocks;?>">
<?php } else{ ?>
<i class="glyphicon glyphicon-check"></i> Completed
<?php } ?>
I think the problem is with your input names. You have assigned arrays as names of your inputs. Try to make them unique using the product id.

php chart item cannot adding quantity

hi all my name is Fadil Raditya
i am stuck in some code in php. I really need help.
i want add item in chart from selected item how ever it can not increment.
this is some of my code.
<?php session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));
if(!empty($_SESSION["cart_item"])) {
if(in_array($productByCode[0]["code"],$_SESSION["cart_item"])) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($productByCode[0]["code"] == $k)
{
$_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
}
}
}
else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
} else {
$_SESSION["cart_item"] = $itemArray;
}
}
break;
and i want call adding the quantity when hit the add chart button
<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id DESC");
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
?>
<div class="col-xs-6 col-sm-3 col-md-3">
<div class="team-wrapper-big">
<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
<h6><?php echo $product_array[$key]["name"]; ?></h6>
<img src="<?php echo $product_array[$key]["image"]; ?>">
<?php echo "Rp ".$product_array[$key]["price"]; ?>
<hr>
<img src="img/VIEW.png">
<input type="text" name="quantity" value="1" placeholder="quantity in number" />
<input type="submit" value="Add to cart" class="btnAddAction" src="img/BUY.png">
<hr>
</form>
</div>
</div>
<?php
}
}
?>
This is the ouput source
<div id="shopping-cart">
<div class="txt-heading"></div>
<?php
if(isset($_SESSION["cart_item"])){
$item_total = 0;
?><center>
<table cellpadding="10" cellspacing="3" border="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
<th><strong>Total Price</strong></th>
<th><strong>Action</strong></th>
</tr>
<?php
foreach ($_SESSION["cart_item"] as $item){
?>
<tr>
<td><strong><?php echo $item["name"]; ?></strong></td>
<td><?php echo $item["code"]; ?></td>
<td><?php echo $item["quantity"]; ?></td>
<?php $_SESSION["track"] = $item["quantity"]; ?>
<td align=right><?php echo "Rp. ".$item["price"]; ?></td>
<td align=right><?php echo "Rp. ".$item["quantity"]*$item["price"]; ?></td>
<td>Remove Item</td>
</tr>
<?php
$item_total += ($item["price"]*$item["quantity"]);
}
?>
<tr>
<td colspan="6" align=right><strong>Total:</strong> <?php echo "Rp. ".$item_total; ?></td>
</tr>
</tbody>
</table> </center>
<?php
}
?><a id="btnEmpty" href="index.php?action=empty">Empty Cart</a>
</div>
i hope anyone can help me. need suggestion and solution. open to discussion.
regards
Fadil Raditya

cart libraries in codeigniter not work

i have some problem in my libraries cart when i try to insert my product into the cart. could you help me.
here is my code link for product into the cart.
<form method="post" action="<?php echo base_url(); ?>cart/add">
<span style="width: 70%;"><input type="submit" class="fa fa-cart-arrow-down btn btn-primary btn-sm btn-block" value="Add to Cart" <?php echo "$mati";?>/></span>
<input type="hidden" name="id_books" value="<?php echo $row->id_books; ?>"/>
<input type="hidden" name="id_category" value="<?php echo $row->id_category; ?>"/>
<input type="hidden" name="title" value="<?php echo $row->title; ?>"/>
<input type="hidden" name="images" value="<?php echo $row->images; ?>"/>
<input type="hidden" name="price" value="<?php echo $total; ?>"/>
<input type="hidden" name="qty" value="1"/>
</form>
and this is cart controller
class Cart extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library(array('cart'));
session_start();
}
function index()
{
$data['menu'] = 'cart';
$this->load->view('v_cart', $data);
}
function add()
{
$data = array(
'id_books' => $this->input->post('id_books'),
'id_category' => $this->input->post('id_category'),
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'images' => $this->input->post('images'),
'title' => $this->input->post('title'));
$this->cart->insert($data);
/*print_r($data);*/
/*echo "<meta http-equiv='refresh' content='0; url=".base_url()."cart/'>";*/
redirect('cart','refresh');
}
and this is cart view
<?php if($cart = $this->cart->contents()):
?>
<?php echo form_open('cart/update'); ?>
<table id="cart-table" class="table table-condensed">
<thead>
<tr>
<th>Action</th>
<th>Image</th>
<th>Product</th>
<th>Price</th>
<th>Quanity</th>
<th>Sub Total</th>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
<?php foreach($cart as $item): /* $title = str_replace(' ', '-', $item['title']); ?>
<?php $price = $row['price']; $jumlah_desimal = "0"; $pemisah_desimal =""; $pemisah_ribuan =".";?>
<?php /*echo form_hidden('rowid[]', $item['rowid']);*/
echo form_hidden($i.'[rowid]', $item['rowid']); ?>
<tr>
<th class="product-remove">
<a class="remove" title="Remove this product" href="<?php echo base_url().'cart/delete/'.$item['rowid'];?>">×</a>
</th>
<th>
<div class="media">
<div class="relative">
<a href="shop-single.html" title="">
<img src="<?php echo base_url().$item['images'];?>" alt=""/>
</a>
</div>
</div><!-- end media -->
</th>
<th>
<?php echo $item['title'];?>
</th>
<td>Rp. <?php echo $this->cart->format_number($item['price']); /*echo rupiah($item['price']); */?></td>
<td>
<?php echo form_input(array('name' => $i.'[qty]', 'value' => $item['qty'], 'maxlength' => '3', 'class' => 'j')); ?> pcs
</td>
<td>
Rp. <?php echo $this->cart->format_number($item['subtotal']);/*echo rupiah($item['subtotal']);*/ ?>
</td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="5" style="text-align: right!important;"><b>Total </b>(biaya buku)</td>
<td>
Rp. <?php echo $this->cart->format_number($this->cart->total()); ?>
</td>
</tr>
</tbody>
</table>
<?php
echo form_close();
else:
echo 'Sorry, Your Cart is empty';
endif;
?>
the result always show
Sorry, Your Cart is empty
where is the bug? anybody can help me :)
thanks :)
Codeigniter cart has predefined format:
https://ellislab.com/codeigniter/user-guide/libraries/cart.html
$data = array(
'id' => 'sku_123ABC',
'qty' => 1,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($data);
So you code will be,
function add()
{
$data = array(
'id'=>someID,
'name'=>SomeName,
'qty' => $this->input->post('qty'),
'price' => $this->input->post('price'),
'options' =>array('id_books'=> $this->input->post('id_books'),'id_category'=> $this->input->post('id_category'),'images' => $this->input->post('images'),'title' => $this->input->post('title'));
$this->cart->insert($data);
/*print_r($data);*/
/*echo "<meta http-equiv='refresh' content='0; url=".base_url()."cart/'>";*/
redirect('cart','refresh');
}

Categories