I am trying to insert the items in the shopping basket to the table userOrders within my database. The fields in Mysql are productId, Quantity and orderTotal I am aware that I should be using SSL.
I am relatively new to this so please be kind to me, any help would be greatly appreciated.
the shopping basket:
<h1>View Shopping Basket</h1>
<div class="container-fluid">
<div class="row">
<div class="col-lg-6">
<form method="post" value="placeOrder" action="<?php echo
htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<form method="post" value="update" action="checkout.php?
page=cart">
<table class="table-responsive">
<thead>
<tr>
<th>productId</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<?php
//select all from products where ID is in session
$sql="SELECT * FROM products WHERE productId IN (";
//for each session append ID and add comma's to seperate
foreach($_SESSION['cart'] as $id => $val) {
$sql.=$id.",";
}
//subtract last comma from ID's & append last bracket to
prevent error
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
$totalprice=00.00;
$quantity =0;
$productId = 'productId';
while($row=mysql_fetch_array($query)){
//running total
$subtotal=$_SESSION['cart'][$row['productId']]
['quantity']*$row['price'];
//total price added with each loop
$totalprice+=$subtotal;
?>
<tbody>
<tr>
<!--hidden productId-->
<td><?php echo $row['productId'] ?></td>
<!--display product name-->
<td><?php echo $row['name'] ?></td>
<!--display quantity-->
<!--take 'productID' & 'quantity' rows, -->
<td><input type="text" name="quantity[<?php echo
$row['productId'] ?>]" size="2" value="<?php echo $_SESSION['cart']
[$row['productId']]['quantity'] ?>" /></td>
<!--display price-->
<td><?php echo $row['price'] ?>£</td>
<!--products price == quantity of productID in
session * price -->
<td><?php echo $_SESSION['cart'][$row['productId']]
['quantity']*$row['price'] ?>£</td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" style="text-align:right">Total Price: <?
php echo $totalprice ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<br />
<button type="submit" value="update" name="update">Update Shopping
Basket</button>
<br />
<button type="submit" value="PlaceOrder" name="PlaceOrder">Place
Order</button>
</form>
<br />
<p style="text-align:center">To remove an item set its quantity to 0. </p>
<a href="shopsesh.php?page=products"><p style="text-align:left">Continue
Shopping</a></p>
Update Quantity:
<?php
//check form was submitted, if yes & value ==0 then unset session.
if(isset($_POST['submit'])){
foreach($_POST['quantity'] as $key => $val) {
if($val==0) {
unset($_SESSION['cart'][$key]);
//if form was submit and value =! 0 then update quantity
}else{
$_SESSION['cart'][$key]['quantity']=$val;
}
}
}
?>
Insert Query:
<?php
//add items to orders table in DB
if (isset($_POST['placeOrder'])) {
//if no error
if( !$error ) {
$productId = $_POST['productId'];
$quantity = $_POST['quantity'];
//$_POST['$totalPrice'];
//insert order into database
$query = "INSERT INTO userOrders(productId,quantity,orderTotal)
VALUES('$productId','$quantity','$totalprice')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Items added to database";
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>
Related
/*I have two table , 1st table name is bazar and 2nd table name is bazarduepayment having same columne name : sl,date,item,paid,due,remark. 'sl' is auto increment . Delete function is working perfectly . Someone please help me how to insert deleted row data in 2nd table 'bazarduepayment' Here below is code detail i wrote */
<?php
session_start();
include_once("rwdbconnection.php");
error_reporting(0);
if(isset($_POST['save']))
{
$checkbox = $_POST['check'];
for($i=0;$i<count($checkbox);$i++)
{
$del_id = $checkbox[$i];
mysqli_query($conn,"DELETE FROM bazar WHERE sl='".$del_id."'");
$message = "Data deleted successfully !";
}
}
$result = mysqli_query($conn,"SELECT * FROM bazar");
?>
<!DOCTYPE html>
<html>
<head>
<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Delete data</title>
</head>
<body>
<div>
<?php if(isset($message)) { echo $message; } ?>
</div>
<form method="post" action="">
<table class="table table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="checkAl"> Select All</th>
<th>Sl</th>
<th>Date</th>
<th>Item</th>
<th>Paid</th>
<th>Due</th>
<th>Remark</th>
</tr>
</thead>
<?php
$i=0;
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><input type="checkbox" id="checkItem" name="check[]" value="<?php echo $row["sl"]; ?>"></td>
<td><?php echo $row["sl"]; ?></td>
<td><?php echo $row["date"]; ?></td>
<td><?php echo $row["item"]; ?></td>
<td><?php echo $row["paid"]; ?></td>
<td><?php echo $row["due"]; ?></td>
<td><?php echo $row["remark"]; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
<p align="center"><button type="submit" class="btn btn-success" name="save">DELETE</button></p>
</form>
<script>
$("#checkAl").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
</script>
</body>
</html>
First you need to copy the data from one table to another using INSERT ... SELECT syntax and only then you can delete.
You should be using prepared statements for this.
if (isset($_POST['save'])) {
// Prepared INSERT query
$stmt_insert = $conn->prepare('INSERT INTO bazarduepayment(date,item,paid,due,remark)
SELECT date,item,paid,due,remark FROM bazar WHERE sl=?');
// Prepare DELETE query
$stmt_delete = $conn->prepare('DELETE FROM bazar WHERE sl=?');
// Loop on all checkboxes selected
foreach ($_POST['check'] as $del_id) {
$stmt_insert->bind_param('s', $del_id);
$stmt_insert->execute();
$stmt_delete->bind_param('s', $del_id);
$stmt_delete->execute();
}
}
You could even simplify this to get rid of the foreach loop entirely.
I have a site where you can order some tickets. If someone makes an order, I want the order to be send to the database. Also I want to put the specific cart items in to be send to the database. See the model I use:
ORDERS CART ITEMS
id* id
amount order_id*
product_id
quantity
This is the code I use with the form:
<form action="index.php?page=cart" method="post" class="">
<table class=" table__nav">
<thead>
<tr>
<th class="p p--bold p--th th--ticket">Ticket</th>
<th class="p p--bold p--th th--name">Name</th>
<th class="p p--bold p--th th--quantity">Quantity</th>
<th class="p p--bold p--th th--price">Price per ticket</th>
<th class="p p--bold p--th th--itemtotal">Item Total</th>
</tr>
</thead>
<tbody>
<?php
$total = 0;
foreach($_SESSION['cart'] as $ticket) {
$ticketTotal = $ticket['ticket']['price'] * $ticket['quantity'];
$total += $ticketTotal;
?>
<tr>
<td>
<?php echo $ticket['ticket']['eye_cart']; ?>
</td>
<td>
<p class = "p--bold"><?php echo $ticket['ticket']['name']; ?></p>
</td>
<td>
<input class = "p td--quantity" type="number" name="quantity[<?php echo $ticket['ticket']['id'];?>]" value="<?php echo $ticket['quantity'];?>" class="replace" required />
</td>
<td>
<p>€<?php echo $ticket['ticket']['price'];?>,-</p>
</td>
<td>
<p>€<?php echo $ticketTotal;?>,-</p>
</td>
<td>
<td class="remove-item"><button type="submit" class="btn remove-from-cart" name="remove" value="<?php echo $ticket['ticket']['id'];?>">×</button></td>
</td>
</tr>
</tbody>
<?php } ?>
</table>
<div class="table__wrap">
<button type="submit" id="update-cart" class="btn btn--cart" name="action" value="update">
<img width="14" height="14" src="./assets/img/refresh.png" alt="refresh">
</button>
</img>
<p class="table__order--total"><span class="span--bold span--bold-no">Total:</span></p>
<p class="table__order--number"><span class="span--bold span--bold-no">€ <?php echo $total ?>,-</span></p>
</div>
<div class="table__wrap table__wrap--end">
<a class="p p__li p__li--light" href="index.php?page=register">
<button type = "submit" name ="action" value = "details" class="btn btn--big btn--big-2 btn--dark">your details -> </button></a>
</div>
</form>
When the user presses the button to go to "your details" I want to save an order with the total amount + the cart items with the order_id and quantity.
I'm using the MVC model for this but I can't really figure it out.
This is how my controller looks:
if ($_POST['action'] == 'details') {
$data = array(
'amount' => $total,
);
$insertedOrder = $this->orderDAO->insertOrder($data);
$this->set('insertedOrder', $insertedOrder);
if (empty($insertedOrder)) {
$errors = $this->orderDAO->validate($data);
$this->set('errors', $errors);
}
}
if ($_POST['action'] == 'details') {
$dataB= array(
'order_id' => ?,
'product_id' => $_SESSION['cart']['id']['ticket']['id'],
'quantity' => $_SESSION['cart']['quantity'],
);
$insertedCartItem = $this->orderDAO->insertCartItem($data);
$this->set('insertedCartItem', $insertedCartItem);
if (empty($insertedCartItem)) {
$errors = $this->orderDAO->validateB($dataB);
$this->set('errors', $errors);
}
}
And the next code is my DAO:
public function insertOrder($data){
$errors = $this->validate( $data );
if (empty($errors)) {
$sql = "INSERT INTO `orders` (`amount`) VALUES (:amount)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':amount', $data['amount']);
if ($stmt->execute()) {
return $this->selectOrderById($this->pdo->lastInsertId());
}
}
return false;
}
public function insertCartItem($dataB){
$errors = $this->validateB($dataB);
if (empty($errors)) {
$sql = "INSERT INTO `cart_items` (`order_id` `product_id`,`quantity`) VALUES (:order_id, :product_id, :quantity)";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':order_id', $dataB['order_id']);
$stmt->bindValue(':product_id', $dataB['product_id']);
$stmt->bindValue(':quantity', $dataB['quantity']);
if ($stmt->execute()) {
return $this->selectCartItemById($this->pdo->lastInsertId());
}
}
return false;
}
The main problem I have is that I don't know how I can send data from $_SESSION variables to the database. I run into problems in the controller. As you can see I'm sending data with the $data and $dataB, but I think I'm going wrong there.
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')";
I have a page that contains an ordering form, on this form it lists the vendor information and then each of the products for the vendor underneath and in front of the product is an input field that allows the user to input the quantity of each product that they want.
Upon submitting the information goes to a confirmation page where I need to be able to show the order information. On the form on the order page, I have a hidden field that contains the vendor id. and the vendor id is put once for each vendor. What I need to be able to do is not only echo out the quantity but also echo out the vendor id specific for each order. My code is below. The first block is the order page and then the block below that will be the confirm page.
As it stands right now underneath every quantity it displays all the vendor ids as opposed to just the one I need.
<?php defined('C5_EXECUTE') or die("Access Denied.");?>
<div class="ccm-ui">
<?php
$db= Loader::db(); //This loads the database helper.
Loader::model('user'); //This loads the user Model.
$user = new User();
$userInfo = UserInfo::getByID($user->getUserID()); //This gets the user info for the current user.
$userCostCenter = $userInfo->getAttribute('cost_center'); //This sets a variable equal to the attribute Cost Center for the current user.
//The if statement below checks if the user is an admin and then displays the info accordingly.
if ($userCostCenter === "Admin") {
?>
<form name="SelectCostCenter" action="/adminorder" method="POST">
<select name="CostCenter">
<option value="unitedilluminating">United Illumination</option>
<option value="clp">CL&P</option>
</select>
<input type="submit" value="Continue">
<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
<?php
} elseif ($userCostCenter === "United Illuminating") {
?>
<form name="OrderForm" action="/confirm" method="POST">
<?php
$query = 'SELECT * FROM Vendors WHERE costCenterID = 1';
$productQuery = 'SELECT * FROM Products WHERE costCenterID = 1';
$results = $db->getAll($query);
$productResults = $db->getAll($productQuery);?>
<table class="table">
<thead>
<tr>
<th>Quantity/Product</th>
<th>Category</th>
<th>Vendor</th>
<th>Address</th>
</tr>
<?php
foreach ($results as $vendor) {
?>
<tr class="category">
<td></td>
<td><?php echo $vendor['Category']; ?></td>
<td><?php echo $vendor['Vendor']; ?></td>
<td><?php echo $vendor['Address']; ?></td>
</tr>
<?php foreach ($productResults as $product) { ?>
<tr class="product">
<td colspan="4"><span class="name"><input type="text" name="quantities[]" size="1" /><?php echo $product['Product'];?></span></td>
</tr>
<?php } ?>
<td><input type="hidden" name="vendor[]" value="<?php echo $vendor['vendorID']; ?>"/></td>
<?php
}?>
</table>
<input type="submit" value="Checkout"<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
</div><?php
}
else {
?>
<form name="OrderForm" action="/confirm" method="POST">
<?php $query = 'SELECT * FROM Vendors Where costCenterID = 2';
$productquery = 'SELECT * FROM Products WHERE costCenterID = 2';
$results = $db->getAll($query);
$productresults = $db->getAll($productquery);?>
<table class="table">
<thead>
<tr>
<th>Quantity/Product</th>
<th>Category</th>
<th>Vendor</th>
<th>Address</th>
</tr>
<?php
foreach ($results as $vendor) {
?>
<tr class="category">
<td></td>
<td><?php echo $vendor['Category'];?></td>
<td><?php echo $vendor['Vendor'];?> </td>
<td><?php echo $vendor['Address'];?></td>
</tr>
<?php
foreach ($productresults as $product){
?>
<tr class="product">
<td colspan="4"><span class="name"><input type="text" name="quantities[<?php echo $vendor['vendorID']; ?>]" size="1" /><?php echo $product['Product'];?></span></td>
<td><input type="hidden" name="vendor[]" value="<?php echo $vendor['vendorID']; ?>"/></td>
</tr>
<?php
}
?>
<?php
}?>
</table>
<input type="submit" value="Checkout"<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
</div><?php
}
?>
This is the confirm page below.
<?php defined('C5_EXECUTE') or die("Access Denied.");
$db= Loader::db();
$quantity = $_POST['quantities'];
$vendor = $_POST['vendor'];
$minimumorder = 25;
foreach($quantity as $num){
if ($num >= $minimumorder){
echo "$num";
echo "</br>";
foreach($vendor as $vendors){
echo "$vendors";
echo "</br>";
}
}
}
?>
I appreciate any help anyone can give. This has had me stumped for a few days actually.
you might want to rearrange your array, and do something like:
$i = 0;
foreach ($productresults as $product) {
echo '<input name="product['.$i.'][quantity]" />';
echo '<input name="product['.$i.'][vendor_id]" value="'.$vendor['vendorID'].'" type="hidden" />';
++$i;
}
The resulting array in $_POST would have the quantities & their vendor separated into their own arrays.
In your code $vendor['vendorID'] seems the key of your $_POST['quantities'] so in your confirm page you could use:
foreach($quantity as $vendorid=>$num){
if ($num >= $minimumorder){
echo "$num";
echo "</br>";
echo "$vendorid";
}
}
I've been new to programming and I been working with phpmyadmin on localhost. I am making a simple table on a webpage to display data. The problem is that everytime I load the page it only displays the table and not table will load up. Here is my code:
<?php
require('../model/database.php');
require('../model/product_db.php');
$products = get_products();
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'under_construction';
}
// Display the product list
include('view-productList.php');
?>
This is the view-productList.php:
<?php include '../view/header.php'; ?>
<div id="main">
<h1>Product List</h1>
<div id="content">
<!-- display a table of products -->
<h2><?php echo $name; ?></h2>
<table>
<tr>
<th>Code</th>
<th>Name</th>
<th class="right">Version</th>
<th> </th>
</tr>
<?php foreach ($products as $product) : ?>
<tr>
<td><?php echo $product['productCode']; ?></td>
<td><?php echo $product['name']; ?></td>
<td class="right"><?php echo $product['version']; ?></td>
<td><form action="." method="post">
<input type="hidden" name="action"
value="delete_product" />
<input type="hidden" name="product_id"
value="<?php echo $product['productID']; ?>" />
<input type="hidden" name="category_id"
value="<?php echo $product['categoryID']; ?>" />
<input type="submit" value="Delete" />
</form></td>
</tr>
<?php endforeach; ?>
</table>
<p>Add Product</p>
</div>
</div>
<?php include '../view/footer.php'; ?>
Query Page:
<?php
function get_products() {
global $db;
$query = 'SELECT * FROM products
ORDER BY productID';
$products = $db->query($query);
return $products;
}
function get_products_by_category($category_id) {
global $db;
$query = "SELECT * FROM products
WHERE products.categoryID = '$category_id'
ORDER BY productID";
$products = $db->query($query);
return $products;
}
function get_product($product_id) {
global $db;
$query = "SELECT * FROM products
WHERE productID = '$product_id'";
$product = $db->query($query);
$product = $product->fetch();
return $product;
}
function delete_product($product_id) {
global $db;
$query = "DELETE FROM products
WHERE productID = '$product_id'";
$db->exec($query);
}
product_db.php should not be commented out for one - assuming that is the file that holds the "Query Page:" contents.
$products = get_products();
should come immediately after the include.
and your for loop needs the fetch result and not just the product resource:
<?php foreach ($products->fetch() as $product) : ?>
assuming fetch() is relevant to this type of resource since we can't see your db class.