Storing order details in MYSQL database using php - php

I'm trying to learn php and MYSQL through developing an eCommerce website. So far the experience with these new languages are really good, but I'm stuck on one of my ideas. I have managed to add the order details to my database, however it adds only a product at a time. Originally what I wanted to do is to add more than a product and store it in a database.
For an example let's say an user wants to buy 5 items. How can I store this into my database. With my current code this just add as a single product with the total of 5 products.(Even the quantity is not adding up).
I'm not sure whether my code is correct. Any suggestions on this is really appreciated. (Please feel free to modify code, it will be really helpful)
Following is the code I'm using to add orders to database.
<div class="col-md-12">
<h4 class="text-center">Paypal Intergration Goes Here.</h4>
<img src="./images/paywith_paypal.png" class="img-responsive center-block" alt="Pay With Paypal">
<?php
// Getting product details
$total = 0;
global $con;
$ip = getIp();
$sel_price = "SELECT * FROM zeus_limited.cart WHERE ip_address='$ip'";
$run_price = mysqli_query($con, $sel_price);
while($p_price=mysqli_fetch_array($run_price)){
$product_id = $p_price['cart_product_id'];
$product_price = "SELECT * FROM zeus_limited.product WHERE product_id='$product_id'";
$run_product_price = mysqli_query($con,$product_price);
while ($prod_price = mysqli_fetch_array($run_product_price)){
$product_price = array($prod_price['product_price']);
$product_id = $prod_price['product_id'];
$pro_name = $prod_price['product_title'];
$values = array_sum($product_price);
$total +=$values;
}
}
// Getting Quantity from cart
$get_quantity = "SELECT * FROM zeus_limited.cart WHERE cart_product_id='$product_id'";
$show_quantity = mysqli_query($con, $get_quantity);
$row_qty = mysqli_fetch_array($show_quantity);
$quantity = $row_qty['quantity'];
if($quantity == 0){
$quantity = 1;
}
else {
$quantity = $quantity;
$total = $total * $quantity;
}
// Getting Customer details
$user = $_SESSION['customer_email'];
$get_customer = "SELECT * FROM zeus_limited.customer WHERE customer_email='$user'";
$show_customer = mysqli_query($con, $get_customer);
$row_c = mysqli_fetch_array($show_customer);
$customer_id = $row_c['customer_id'];
$customer_email = $row_c['customer_email'];
$customer_name = $row_c['customer_fname'];
$trx_id = mt_rand();
$currency = 'USD';
$invoice = mt_rand();
// Insert data to ORDER table
$add_order = "INSERT INTO zeus_limited.orders (order_product_id, order_customer_id, order_quantity, invoice_no, status, order_date) VALUES ('$product_id','$customer_id','$quantity','$invoice','in Progress',NOW())";
$run_order = mysqli_query($con, $add_order);
// Insert data to PAYMENT table
$add_payment = "INSERT INTO zeus_limited.payment (amount, payment_customer_id, payment_product_id, trx_id, payment_currency, payment_date) VALUES ('$total','$customer_id','$product_id','$trx_id','$currency',NOW())";
$run_payment = mysqli_query($con, $add_payment);
// Removing products from CART
$empty_cart = "DELETE FROM zeus_limited.cart";
$show_customerart = mysqli_query($con, $empty_cart);
if($total == $total){
echo "<div class='text-center'>";
echo "<h3>Welcome:" . $_SESSION['customer_email']. "<br>" . "Hooray! Your Payment was successful!</h3>";
echo "<a href='./customer/my_account.php'>Go to your Account</a><br>";
echo "</div>";
}
else {
echo "<div class='text-center'>";
echo "<h4>Welcome Guest, Payment process failed... Please try again</h4><br>";
echo "<a href='/shop_products.php'>Go to Back to shop</a>";
echo "</div>";
}
?>
</div>
I'm attaching the cart code as well.(if it's needed)
<?php
session_start();
require_once './includes/init.php';
require_once './functions/functions.php';
echo getCart();
?>
<!DOCTYPE html>
<html>
<head>
<title>Zeus Pvt. Ltd</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/font-awesome.min.css" />
<link rel="stylesheet" href="css/style.css" />
<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
<script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="header">
<div class="container container-bg">
<div class="row">
<div class="col-md-4"><img src="images/logo.png" class="img-responsive" alt="Responsive image"></div>
<div class="col-md-5"></div>
<div class="col-md-3">
<div class="zeus_cart">
<div class="cart_bg">
<ul class="cart">
<i class="cart_icon"></i><p class="cart_desc"><?php getTotalCartPrice() ?><br><span class="yellow"><?php getTotalItems() ?></span></p>
<div class='clearfix'></div>
</ul>
<ul class="product_control_buttons">
<li><img src="images/close.png" alt=""/></li>
<li>Edit</li>
</ul>
<div class='clearfix'></div>
</div>
<ul class="quick_access">
<li class="view_cart">View Cart</li>
<li class="check">Checkout</li>
<div class='clearfix'></div>
</ul>
</div>
</div>
</div>
</div>
<div class="container container-bg">
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand"></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Home</li>
<li class="active">Shop Products</li>
<li>My Account</li>
<li>Contact Us</li>
<li>
<?php
if(!isset($_SESSION['customer_email'])){
echo 'Login';
}
else {
echo 'Logout';
}
?>
</li>
<li class="welcome"><a>Welcome <?php echo getUsername(); ?></a></li>
</ul>
<form method="get" action="results.php" enctype="multipart/form-data" class="navbar-form navbar-right">
<div class="form-group search">
<input type="text" name="user_query" class="form-control" placeholder="Search Products">
</div>
<button type="submit" class="btn btn-default btn-search"></button>
</form>
</div>
</div>
</div>
</nav>
</div>
<div class="main">
<div class="container container-bg">
<div class="row">
<div class="col-md-12">
<div class="shoppingcart-title">
<h4 class="text-center sidebar-main-menu">Shopping Cart</h4>
<div class="table-responsive">
<form action="" method="POST" enctype="multipart/form-data">
<table class="table">
<thead>
<tr>
<th>Product No.</th>
<th>Product(s)</th>
<th>Name</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Sub Total</th>
<th>Remove</th>
</tr>
</thead>
</tbody>
<?php
global $con;
$total = 0;
$ip = getIp();
$select_price = "SELECT * FROM zeus_limited.cart WHERE zeus_limited.cart.ip_address='$ip'";
$run_price = mysqli_query($con, $select_price);
while ($product_price = mysqli_fetch_array($run_price)) {
$product_id = $product_price['cart_product_id'];
$product_quantity = $product_price['quantity'];
$product_price = "SELECT * FROM zeus_limited.product WHERE zeus_limited.product.product_id ='$product_id'";
$run_product_price = mysqli_query($con, $product_price);
while ($product_new_price = mysqli_fetch_array($run_product_price)) {
$product_price = array($product_new_price['product_price']);
$product_id = $product_new_price['product_id'];
$product_image = $product_new_price['product_image_carousel'];
$product_title = $product_new_price['product_title'];
$unit_product_price = $product_new_price['product_price'];
$values = array_sum($product_price);
$total += $values * $product_quantity;
?>
<tr>
<td><?php echo $product_id; ?></td>
<td><img src="images/products/<?php echo $product_image; ?>" </td>
<td><?php echo $product_title; ?></td>
<td><input id="" type="text" name="quantity[<?php echo $product_id; ?>]" size="5" value="<?php echo $product_quantity; ?>" style="text-align:center;"/>
<input type="hidden" name="product_id[<?php echo $product_id; ?>]" value="<?php echo $product_id; ?>"
</td>
<!--Updating the quantity-->
<?php
$ip = getIp();
if (isset($_POST['update_cart'])){
foreach ($_POST['product_id'] as $pid => $id) {
$product_id = $id;
$product_quantity = $_POST['quantity'][$pid];
$update_products = "UPDATE zeus_limited.cart SET quantity = '$product_quantity' WHERE cart_product_id = '$product_id' AND ip_address = '$ip';";
$run_update = mysqli_query($con, $update_products);
}
if($update_products){
echo "<script>window.open('cart.php','_self')</script>";
}
}
?>
<td><?php echo 'Rs '. $unit_product_price; ?></td>
<td><?php echo 'Rs '.$unit_product_price * $product_quantity ?></td>
<td><input type="checkbox" name="remove[]" value="<?php echo $product_id; ?>"/></td>
</tr>
</tbody>
<?php } } ?>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th>Grand Total: </th>
<th><?php echo 'Rs '. $total ?></th>
<th></th>
</tr>
</thead>
</table>
<div class="cart_buttons">
<input type="submit" name="update_cart" value="Update Cart"/>
<input type="submit" name="continue_shopping" value="Continue Shopping"/>
<input type="submit" name="checkout" value="Checkout"/>
<?php if (isset($_POST['checkout'])){echo "<script>window.open('checkout.php','_self')</script>"; } ?>
</div>
</form>
<?php
global $con;
$ip = getIp();
if (isset($_POST['update_cart'])){
foreach ($_POST['remove'] as $remove_id) {
$delete_product = "DELETE FROM zeus_limited.cart WHERE cart_product_id='$remove_id' AND ip_address='$ip'";
$run_delete = mysqli_query($con, $delete_product);
if($run_delete){
echo "<script>window.open('cart.php','_self')</script>";
}
}
}
if (isset($_POST['continue_shopping'])){
echo "<script>window.open('shop_products.php','_self')</script>";
}
?>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-4 footer-grid">
<h3>Menu</h3>
<ul class="list1">
<li>Home</li>
<li>Shop Products</li>
<li>My Account</li>
<li>Contact Us</li>
<li>Login</li>
</ul>
</div>
<div class="col-md-4 footer-grid">
<h3>Your Account</h3>
<ul class="list1">
<li>My Orders</li>
<li>Edit Account</li>
<li>Change Password</li>
<li>Delete Account</li>
<li>My Cart</li>
</ul>
</div>
<div class="col-md-4 footer-grid">
<h3>About Us</h3>
<p class="footer_desc">Zeus is a pharmacy focused on providing patients with what they need and deserve - exceptional pharmacy care. It is our responsibility and passion to care for your medication needs.</p>
<p class="f_text"><span class="fa fa-phone" aria-hidden="true"></span> Phone: +081 123 45 67</p>
<p class="email"><span class="fa fa-envelope" aria-hidden="true"></span> Email: <span>info#zeuspharmacy.com</span></p>
</div>
<div class="clearfix"> </div>
</div>
</div>
</div>
</div>
<div class="footer-bottom">
<div class="container">
<div class="row">
<div class="col-md-12 footer-grid-bottom">
<div class="copyrights">
<p>© 2017 Zeus Pharmacy. Made with <span class="fa fa-heart" aria-hidden="true"></span> by Dilum Tharaka</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
order table structure image
payment table structure image
Above are the table structures I'm using. Thanks in advance

Related

Add to cart button not adding products to cart in PHP

I have attempted to code a shopping basket phrage that will allow a user to enter the quantity of a product and then click the button to add to the cart. When I click the add to cart button though nothing happens. The code is shown here:
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "stock");
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))
{
$item_array = array(
'item_id' => $_GET["id"],
'item_product' => $_POST["hidden_product"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
array_push($_SESSION['shopping_cart'], $item_array);
}
else
{
echo '<script>alert("Item has already been added to your
shopping basket")</script>';
echo '<script>window.location="ShoppingCart.php"</script>';
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_product' => $_POST["hidden_product"],
'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 from cart")</script>';
echo '<script>window.location="ShoppingCart.php"</script>';
}
}
}
}
?>
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="HomePage.php">Home <span class="sr-only">
(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href="CDPage.php">Shop</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="About.php">About</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search"
aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0"
type="submit">Search</button>
</form>
</div>
</nav>
<div class = "container>
<?php
$query = "SELECT * FROM stock ORDER BY ID ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<div class="col-md-4">
<form method ="post" action = "shoppingcart.php?
action=add&id=<?php echo $row["id"];?>">
<div style="border:10px solid background-color:blue
border-radius:5px padding: 50px" align = "center">
<img src="<?php echo $row["image"];?>" class = "img-
responsive" ><br/>
<h4 class = "text-info"><?php echo $row["product"];?
></h4>
<p class="text-info"><?php echo
$row["description"];?>
<h4 class = "text-danger">€ <?php echo $row["price"];?>
</h4>
<input type="text" name="quantity" class="form-control"
value = "1" >
<input type="hidden" name="hidden_product" value = "<?
php echo $row["product"];?>" >
<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%">Product 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_product"]; ?></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><a href="shoppingcart.php?action=delete&id=<?php
echo $values["item_id"]; ?>"><span class="text-danger">Delete</span></a>
</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>
<a href="CheckoutPage.php" class="btn btn-success btn-lg active"
role="button" aria-pressed="true">Checkout</a>
</div>
</div>
</body>
</html>
Prior to this attempt I have very little experience writing code with PHP so I am pretty certain that the issue is in there.
I originally tried to put the shopping cart on a seperate page but I couldn't get that at all, this is the closest I've gotten so far.

undefined variable sub_total. even after defining the variable

<?php
include('includes/db.php');
?>
<?php include('functions/functions.php'); ?>
<?php
include('header.php');
?>
<?php
include('topheader.php');
?>
<?php
include('nav.php');
?>
<div id="content">
<div class="container">
<div class="col-md-12">
<ul class="breadcrumb">
<li>Home</li>
<li>Cart</li>
</ul> <!--breadcrumb ends--->
</div> <!---col-md-12 ends-->
<div class="col-md-9" id="cart">
<div class="box">
<form action="cart.php" method="post" enctype="multipart-form-data">
<h1>Shopping Cart</h1>
<?php
$ip_add = getUserIP();
$select_cart = "select * from cart where ip_add='$ip_add'";
$run_cart = mysqli_query($conn, $select_cart);
$count = mysqli_num_rows($run_cart);
?>
<p class="text-muted">You currently have <?php echo $count; ?> items in your cart</p>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th colspan="2">Product</th>
<th>Quantity</th>
<th colspan="1">Unit Price</th>
<th>Container</th>
<th colspan="1">Delete</th>
<th colspan="2">Sub Total</th>
</tr>
</thead> <!--thead ends-->
<tbody>
<?php
$total = 0;
while ($row_cart = mysqli_fetch_array($run_cart)) {
$pro_id = $row_cart['p_id'];
$pro_size = $row_cart['size'];
$pro_qty = $row_cart['qty'];
$get_products = "select * from products where product_id='$pro_id'";
$run_products = mysqli_query($conn, $get_products);
while ($row_products = mysqli_fetch_array($run_products)) {
$product_title = $row_products['product_title'];
$product_img1 = $row_products['product_img1'];
$only_price = $row_products['product_price'];
$sub_total = $row_products['product_price'] * $pro_qty;
$total += $sub_total;
}
?>
<tr>
<td><img src="admin_area/product_images/<?php echo $product_img1; ?>"></td>
<td><?php echo $product_title; ?></td>
<td><?php echo $pro_qty; ?></td>
<td>₹<?php echo $only_price; ?>.00</td>
<td><?php echo $pro_size ?></td>
<td><input type="checkbox" name="remove[]" value="<?php echo $pro_id; ?>"></td>
<td>₹<?php echo $sub_total; ?>.00</td>
</tr> <!---tr ends-->
<?php } ?>
</tbody>
<tfoot>
<tr>
<th colspan="5">TOTAL</th>
<th colspan="2">₹ <?php echo $total; ?>.00</th>
</tr>
</tfoot> <!--tfoot ends-->
</table> <!--table ends-->
</div> <!---table-responsive end-->
<div class="box-footer">
<div class="pull-left">
<a href="index.php" class="btn btn-default">
<i class="fa fa-chevron-left"></i>Continue Shopping
</a>
</div> <!--pullleft ends-->
<div class="pull-right">
<button class="btn btn-default" type="submit" name="update" value="Update Cart"><i class="fa fa-refresh"></i>Update Cart </button>
<a href="checkout.php" class="btn btn-primary">
Proceed to checkout<i class="fa fa-chevron-right"></i>
</a>
</div> <!--pullright ends-->
</div> <!----box footer ends-->
</form> <!---form ends-->
</div> <!---box ends-->
<?php
function update_cart() {
global $conn;
if (isset($_POST['update'])) {
foreach ($_POST['remove'] as $remove_id) {
$delete_product = "delete from cart where p_id='$remove_id'";
$run_delete = mysqli_query($conn, $delete_product);
if ($run_delete) {
echo "<script>window.open('cart.php','_self')</script>";
}
}
}
}
echo #$up_cart = update_cart();
?>
<div class="row same-height-row">
<div class="col-md-3 col-md-6">
<div class="box same-height headline">
<h3 class="text-center">Recently Viewed Product</h3>
</div> <!----box same-height headline end-->
</div> <!---col-m-3 col-md-6 ends---->
<?php
$get_products = "select * from products order by rand() LIMIT 0,3";
$run_products = mysqli_query($conn, $get_products);
while ($row_products = mysqli_fetch_assoc($run_products)) {
$pro_id = $row_products['product_id'];
$pro_title = $row_products['product_title'];
$pro_price = $row_products['product_price'];
$pro_img1 = $row_products['product_img1'];
echo "<div class='center-responsive col-md-3 col-sm-6'>
<div class='product same-height'>
<a href='details.php?pro_id=$pro_id'>
<img src='admin_area/product_images/$pro_img1' class='img-responsive'>
</a>
<div class='text'>
<h3><a href='details.php?pro_id=$pro_id'>$pro_title</a></h3>
<p class='price'>₹ $pro_price</p>
</div>
</div>
</div>";
}
?>
</div>
</div>
<div class="col-md-3">
<div class="box" id="order-summary">
<div class="box-header">
<h3>Order Summary</h3>
</div> <!--box-header ends-->
<p class="text-muted">
Shipping and additional costs are calulated based on the value you have entered.
</p>
<div class="table-responsive">
<table class="table">
<tbody>
<tr>
<td>Order Subtotal</td>
<th>₹<?php echo $sub_total; ?></th>
</tr>
<tr>
<td>Shipping and Handling</td>
<td>₹0.00</td>
</tr>
<tr>
<td>Tax</td>
<td>₹0.00</td>
</tr>
<tr class="total">
<td>Total</td>
<th>₹ <?php echo $total; ?></th>
</tr>
</tbody>
</table> <!--table ends-->
</div> <!---table responsive ends-->
</div> <!---box ends-->
</div> <!----col-md-3 ends--->
</div> <!--container ends-->
</div> <!---content ends-->
<?php include_once 'footer.php'; ?>
i get undefined variable sub_total even after defining variable subtotal above. Can someone figure out what the problem is?? I have check all curly brackets and semicolen. Due on a project that needs to be submited tomorrow. I am thinking improving the coding later but the basic functionality is not working.

Timer and Navigation in online aptitude test

I am a novice in php web app dev.I am designing an online aptitude test. But i met some problem that i couldnt proceed further. This are
The timer restart itself when i click on the navigation for next question
When a question is not answered and the next button is clicked, an eror pops out.
I have poor knowlege of ajax and jquery but belive they can be usedful. Help me in what ever way please to achieve my goal.
below are my codes:
//test.php
<?php
session_start();
// th value of q is given as 1 from the start quiz button of the users home page
if (isset($_GET['q'])) {
$number = (int)$_GET['q'];
}else{
header('Location : index.php');
}
if(!isset($_SESSION['user_session']))
{
header("Location: ../login.html");
}
//connection to the db
include_once '../dbconfig.php';
$stmt = $db_con->prepare("SELECT * FROM tbl_admin WHERE aid=:uid");
$stmt->execute(array(":uid"=>$_SESSION['user_session']));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$qr = $db_con->prepare("SELECT * FROM questions ");
$qr->execute();
$count = $qr->rowCount();
$qrow=$qr->fetch(PDO::FETCH_ASSOC);
$qst = $db_con->prepare("SELECT * FROM questions where quesNo='$number' ");
$qst->execute();
$qstrow=$qst->fetch(PDO::FETCH_ASSOC);
?>
<body>
<header id="header">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><div id="hms">00:05:00</div></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
</header>
<div class="item active">
<?php
//Code to process score(saved is session variable) and move to the next question
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$ans=$_POST['ans'];
$number=$_POST['number'];
$next = $number+1;
if (!isset($_SESSION['score'])){
$_SESSION['score'] = '0';
}
$qrs = $db_con->prepare("SELECT * FROM questions ");
$qrs->execute();
$counts = $qrs->rowCount();
$sqlans= "SELECT * FROM answers where quesNo='$number' and right_ans='1'";
foreach ($db_con->query($sqlans) as $rowsans) {
if($ans==$rowsans['ans_id']){
$_SESSION['score']++;
}
if($number==$count){
header('location:final.php');
exit();
}else{
header('location:test.php?q='.$next);
}
}
}
?>
<div class="containerx" style="height:530px;">
<div class="image" style="width:100%">
<div class="main">
<hl> Question <?php echo $number ?> of <?php echo $count; ?></hl>
<div class="test">
<form method="post" action="">
<table>
<tr>
<td coLspan=”2”>
<h3>Que <?php echo $qstrow['quesNo']; ?>: <?php echo $qstrow['ques']; ?></h3>
</td>
</tr>
<?php
$sqla= "SELECT * FROM answers where quesNo='$number'";
foreach ($db_con->query($sqla) as $rowsa) {
?>
<tr>
<td>
<input type="radio" name="ans" value=" <?php echo $rowsa['ans_id']; ?>"/> <?php echo $rowsa['ans']; ?>
</td>
</tr>
<?php } ?>
<tr>
<td>
<input type="submit" id="btn_next" name="submit" value="Next Question"/>
<input type="hidden" name="number" value="<?php echo $number ?>"/>
</td>
</tr>
</table>
<!--<div class="caption page-carousel pull-left">-->
</div>
<div class="site-full-width darkbluecolor">
<div class="container">
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function count(){
var startTime = document.getElementById('hms').innerHTML;
var pieces= startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
console.log( time.setMinutes(pieces[1]));
time.setSeconds(pieces[2]);
console.log( time.setMinutes(pieces[1]));
var timedif = new Date(time.valueOf() - 1000);
var newTime=timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML=newTime;
if(newTime==="00:00:00"){
clearTimeout(time_out);
$('#btn_next').css('display',' none');
alert("Sorry Your time is over");
}
time_out= setTimeout(count,1000);
}
count();
});
</script>

Something wrong while deleting a row in sql table on clicking a button

Trying to delete a row from my SQL table in my shopping cart page,but my code deletes all the rows from the table on clicking a button.Even when I update quantity of the one product the quantity of all the products are changing.The answer might be the same for these two issues.Could you please review my code and tell me where I've done wrong.
Thankyou in advance
<?php
include "header.php";
require "includes/connect.php";
require "includes/product.php";
class Cartitem{
public function fetch_cart(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM cart_items WHERE user_id = ?");
$query->bindvalue(1, $_SESSION['user_id']);
$query -> execute();
return $query->fetchAll();
}
}
$cartitem= new Cartitem;
$cartitems=$cartitem-> fetch_cart();
?>
<div class="cart">
<div class = "container">
<div class="col-md-9 cart-items">
<h1 class="cart-items-h1">Cart</h1>
<hr>
<?php foreach($cartitems as $cartitem) { ?>
<div class="cart-header">
<h3>
<?php echo $cartitem['product_name'] ; ?></h3>
<br>
<?php
if(isset($_POST['delete'])){
$query = $pdo->prepare('DELETE FROM cart_items WHERE product_id=?');
$query->bindValue(1 , $cartitem['product_id']);
$query->execute();
}
?>
<form method = "POST" action="">
<button type="submit" class="close btn btn-default" name="delete"><span class="glyphicon glyphicon-remove " aria-hidden="true"></span></button>
</form>
<div class="cart-sec simpleCart_shelfItem">
<div class="cart-item cyc">
<img src="Tiger.jpg" class="img-responsive" alt=" No image"/>
</div>
<div class="cart-item-info">
<ul class="item-properties">
<li>
<form action="" method="post">
<?php
if(isset($_POST['qty'])){
$quantity=$_POST['qty'];
$query = $pdo->prepare('UPDATE cart_items SET quantity= ? WHERE product_id=?');
$query->bindValue(1 , $quantity);
$query->bindValue(2 , $cartitem['product_id']);
$query->execute();
}
?>
<select class="quantity" name="qty">
<?php
echo '<option >'.$cartitem['quantity'].'</option>';
for($q = 1 ; $q<10 ; $q++){
echo '<option >'.$q.'</option>';
}
?>
</select>
<button type="submit" class="update" name="update">Update</button>
</li>
<li><p>Rs.<?php echo $cartitem['price']; ?></p></li>
</ul>
<div class="delivery">
<p>Service Charges : Rs.190.00</p>
<span>Delivered in 2-3 bussiness days</span>
<div class="clearfix"></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<?php }?>
</div>
This is (productpage.php) from where I'm storing the values to the cart table.Probably not so important to this issue. If yes
<?php
ob_start();
include ('header.php');
require('includes/connect.php');
require('includes/product.php');
$product = new Product;
if(isset ($_GET['id'])) {
$id = $_GET['id'];
$data = $product -> fetch_data($id);
if(isset($_POST['add'])){
if (isset($_SESSION['logged_in'])) {
$query = $pdo->prepare("SELECT product_id FROM cart_items WHERE product_id= ?");
$query -> bindValue(1, $id);
$query ->execute();
$num=$query->rowCount();
if($num == 0){
if(isset($_POST['qty'])){
$qty=$_POST['qty'];
}
$query = $pdo -> prepare("INSERT INTO cart_items(product_id , user_id, quantity,price,product_name) VALUES (?,?,?,?,?)");
$query -> bindValue(1, $id);
$query -> bindValue(2, $_SESSION['user_id']);
$query -> bindValue(3, $qty);
$query -> bindValue(4, $data['new_price']);
$query -> bindValue(5, $data['product_name']);
$query ->execute();
header('location:cart.php');
}
else{
echo " The product is already in your Cart";
}
}
else{
header('location:Login Page.php');
}
}
?>
<div class="showcase-grid">
<div class="container ">
<?php if(isset($error)){ ?>
<small style = "color : #aa0000"; ><?php echo $error ?></small>
<br><br>
<?php } ?>
<div class="col-md-8 showcase" id="showcase-div">
<div class="img-showcase" >
<br>
<div id="myCarousel" class="carousel slide text-center" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class=" img-responsive"></li>
<li data-target="#myCarousel" data-slide-to="1" class="img-responsive"></li>
<li data-target="#myCarousel" data-slide-to="2" class="img-responsive"></li>
<li data-target="#myCarousel" data-slide-to="3" class="img-responsive"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<img class="slide-img" src="images/product2.jpg" alt="jwellery" >
</div>
<div class="item">
<img src="images/product3.jpg" alt="jwellery">
</div>
<div class="item">
<img src="images/product4.jpg" alt="jwellery" >
</div>
<div class="item">
<img src="images/product5.jpg" alt="jwellery" >
</div>
</div>
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
<br>
</div>
</div>
<div class="col-md-4 showcase1 ">
<div class="showcase-rt-top">
<div class = "row">
<div class ="col-md-12">
<br>
<div class="pull-left Product-name">
<h3><?php echo $data['product_name']; ?></h3>
<br>
</div>
</div>
<br><br><br>
<div class ="col-xs-4 price">
<h4>Rs.<?php echo $data['new_price']; ?></h4>
</div>
<div class ="col-xs-4 oldprice text-left">
<s><h4 class="text-left">Rs.<?php echo $data['old_price']; ?></h4></s>
</div>
<div class ="col-xs-4">
<div class="pull-right rating-stars pull-left">
<h4><span class="label label-warning">3.5 <span class="glyphicon glyphicon-star star-stn" aria-hidden="true"></span></span></h5>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<hr class="featurette-divider">
<div class="shocase-rt-bot">
<div class="col-xs-6 discount">
<?php
$discount = (($data['old_price'] - $data['new_price'])/$data['old_price'])*100;
echo round($discount) . '% off ';
?>
</div>
<form action = "" method="post" class="form-inline">
<div class="col-xs-6">
<div class="float-qty-chart">
<!-- <label class=" option">quantity:</label>-->
<select id= "select" class="form-control qnty-chrt" name="qty" >
<option value="1">quantity</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</select>
<div class="clearfix"></div>
</div>
</div>
<ul class="ul_list">
<li class="ad-2-crt simpleCart_shelfItem">
<button type="submit" class="btn item_add" name="add" >Add To Cart</button>
<button type="submit" class="btn item_add" name="buy-now">Buy Button</button>
</li>
</ul>
<br>
</div>
</form>
<div class="features" >
<h3>product details</h3>
<ul>
<li><?php echo nl2br($data['brief_description']); ?></li>
</ul>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<?php
}
else{
header('location: index.php');
exit();
}
Include ('footer.php');
?>
This is the product.php
<?php
class Product {
public function fetch_all() {
global $pdo;
$query = $pdo->prepare("SELECT * FROM ear_rings_list");
$query -> execute();
return $query->fetchAll();
}
public function fetch_data($pid) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM ear_rings_list WHERE listing_id = ?");
$query->bindValue(1, $pid);
$query->execute();
return $query->fetch();
}
}
Actually you are working with an foreach loop
Just check here
<?php foreach($cartitems as $cartitem) { ?>
if(isset($_POST['delete'])){
$query = $pdo->prepare('DELETE FROM cart_items WHERE product_id=?');
$query->bindValue(1 , $cartitem['product_id']);
$query->execute();
}
if(isset($_POST['qty'])){
$quantity=$_POST['qty'];
$query = $pdo->prepare('UPDATE cart_items SET quantity= ? WHERE product_id=?');
$query->bindValue(1 , $quantity);
$query->bindValue(2 , $cartitem['product_id']);
$query->execute();
}
<?php }?>
Here you are just checking the isset($_POST['delete']) which will be true for each $cartitem['product_id'] that's why your each row is deleting and updating.
Solution:-
Use this code
<?php
include "header.php";
require "includes/connect.php";
require "includes/product.php";
class Cartitem
{
public function fetch_cart()
{
global $pdo;
$query = $pdo->prepare("SELECT * FROM cart_items WHERE user_id = ?");
$query->bindvalue(1, $_SESSION['user_id']);
$query->execute();
return $query->fetchAll();
}
}
$cartitem = new Cartitem;
$cartitems = $cartitem->fetch_cart();
?>
<div class="cart">
<div class="container">
<div class="col-md-9 cart-items">
<h1 class="cart-items-h1">Cart</h1>
<hr>
<?php
if (isset($_POST['qty']) && isset($_POST['product_id'])) {
$quantity = $_POST['qty'];
$product_id = $_POST['product_id'];
$query = $pdo->prepare('UPDATE cart_items SET quantity= ? WHERE product_id=?');
$query->bindValue(1, $quantity);
$query->bindValue(2, $product_id);
$query->execute();
}
?>
<?php
if (isset($_POST['delete']) && isset($_POST['product_id'])) {
$product_id = $_POST['product_id'];
$query = $pdo->prepare('DELETE FROM cart_items WHERE product_id=?');
$query->bindValue(1, $product_id);
$query->execute();
}
?>
<?php foreach($cartitems as $cartitem) { ?>
<div class="cart-header">
<h3>
<?php echo $cartitem['product_name']; ?></h3>
<br>
<form method="POST" action="">
<input type="hidden" value="<?php $cartitem['product_id'] ?>" name="product_id">
<button type="submit" class="close btn btn-default" name="delete"><span class="glyphicon glyphicon-remove " aria-hidden="true"></span></button>
</form>
<div class="cart-sec simpleCart_shelfItem">
<div class="cart-item cyc">
<img src="Tiger.jpg" class="img-responsive" alt=" No image"/>
</div>
<div class="cart-item-info">
<ul class="item-properties">
<li>
<form action="" method="post">
<input type="hidden" value="<?php $cartitem['product_id'] ?>" name="product_id">
<select class="quantity" name="qty">
<?php
echo '<option >' . $cartitem['quantity'] . '</option>';
for ($q = 1; $q < 10; $q++) {
echo '<option >' . $q . '</option>';
}
?>
</select>
<button type="submit" class="update" name="update">Update</button>
</form>
</li>
<li><p>Rs.<?php echo $cartitem['price']; ?></p></li>
</ul>
<div class="delivery">
<p>Service Charges : Rs.190.00</p>
<span>Delivered in 2-3 bussiness days</span>
<div class="clearfix"></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<?php }?>
</div>
Changes :-
I just make an hidden input field for $cartitem['product_id'] here <input type="hidden" value="<?php $cartitem['product_id'] ?>" name="product_id">
and placed the delete and update query out side the foreach loop.

How to make multiple checkbox search values in database and display it on the same page

I can't display my search form where i suspect the problem is due to my not working checkboxes. I click search and it contain any error but blank table. Maybe there are probably some php and sql syntax error that i overlook. fyi the form is display at the same page(checkbox) index.php
index.php
<?php require_once('Connections/conn.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title>Casado</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/kahwin/index.php">Casado</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
<div class="container text-center">
<div class="page-header">
<div class="container">
<form method="post">
<div class="form-group">
<h3><label for="usr">Carian bajet anda:</label></h3>
<div class= "col-md-12">
<div class=" col-md-4"></div>
<div class=" col-md-4">
<input name="bajet" type="text" class="form-control" id="usr"></div>
</div>
<div class=" col-md-4"></div>
</div><br>
<h3><label for="sel1">Pilih negeri pilihan anda:</label></h3>
<div class= "col-md-12">
<div class=" col-md-4"></div>
<div class=" col-md-4">
<select class="form-control" name="sel">
<option>Kuala Lumpur</option>
<option>Negeri Sembilan</option>
<option>Pahang</option>
<option>Perak</option>
<option>Terengganu</option>
<option>Selangor</option>
</select>
</div>
<div class=" col-md-4"></div>
</div><br>
<br>
<h5><label for="check">Senarai Pra-perkahwinan:</label></h5>
<center> <div class="checkbox">
<label class="checkbox-inline"> <input type="checkbox"name="check_list[]" value="Jurufoto"><label>Jurufoto</label></label>
<label class="checkbox-inline"> <input type="checkbox"name="check_list[]" value="Butik"><label>Butik</label></label>
<label class="checkbox-inline"> <input type="checkbox"name="check_list[]" value="Hiburan"><label>Hiburan</label></label>
<label class="checkbox-inline"> <input type="checkbox"name="check_list[]" value="Kad Kahwin"><label>Kad Kahwin</label></label>
<label class="checkbox-inline"> <input type="checkbox"name="check_list[]" value="Katering"><label>Katering</label></label>
<br>
</center>
<div class="col-md-4"></div>
<div class="col-md-4">
<button class="btn btn-success btn-sm" name="search">Search <span class="glyphicon glyphicon-search"></span></button><br><br>
</div>
<div class="col-md-4"></div>
</div>
</form>
<table class="table table-bordered">
<thead>
<tr>
<th>Jenis</th>
<th>Vendor</th>
<th>Negeri</th>
<th>No.</th>
<th>Pakej</th>
<th>Harga</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$budget = $_POST['bajet'];
$select = $_POST['sel'];
$check = $_POST['check_list'];
if (isset($_POST['search'])) {
mysql_select_db($database_conn, $conn);
$sql = mysql_query(" SELECT *
FROM vendor
RIGHT JOIN item
ON vendor.v_id=item.v_id
WHERE item.harga <= ' $budget '
AND vendor.state = ' $select '
AND vendor.type = ' $check ' );
while($row = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['companyName'] ?></td>
<td><?php echo $row['state'] ?></td>
<td><?php echo $row['contact'] ?></td>
<td><?php echo $row['harga'] ?></td>
<td><?php echo $row['pakej'] ?></td>
<td>View Package</td>
</tr>
<?php }
}
?>
</tbody>
</table>
</div>
Use implode() for checkbox to convert into string from array of selected checkbox.
<?php
$budget = $_POST['bajet'];
$select = $_POST['sel'];
$check = implode("','", $_POST['check_list']);
$finalCheck = "'".$check ."'";
if (isset($_POST['search'])) {
mysql_select_db($database_conn, $conn);
$sql = mysql_query(" SELECT *
FROM vendor
RIGHT JOIN item
ON vendor.v_id=item.v_id
WHERE item.harga <= '%". $bajet . "%'
AND vendor.state = '%". $select ."%'
AND vendor.type IN (". $finalCheck ." )" );
?>

Categories