Insert multiple rows mysql - php

i have the following code:
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<br>
<div id="books-wrapper">
<!-- #content to center the menu -->
<div id="content">
<!-- This is the actual menu -->
<ul id="darkmenu">
<li>Home</li>
<li>Catalogue</li>
<li>Search</li>
<li>Cart</li>
<li>Orders</li>
</ul>
<div id = "welcome" >
Welcome, <?=$_SESSION['login_user']?>! <br> Logout
</div>
</div>
<br><br>
<h1 id = "mainHeader" >View Cart</h1>
<br>
<div class="view-cart">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["books"]))
{
$total = 0;
echo '<form method="post" action="">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["books"] as $cart_itm){
$ISBN = $cart_itm["ISBN"];
$results = $mysqli->query("SELECT Title,BookDesc,Price FROM books WHERE ISBN='$ISBN'");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-Price">'.$currency.$obj->Price.'</div>';
echo '<div class="book-info">';
echo '<h3>'.$obj->Title.' (ISBN :'.$ISBN.')</h3> ';
echo '<div class="p-quantity">Quantity : '.$cart_itm["quantity"].'</div>';
echo '<div>'.$obj->BookDesc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["Price"]*$cart_itm["quantity"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$ISBN.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->BookDesc.'" />';
echo '<input type="hidden" name="item_quantity['.$cart_items.']" value="'.$cart_itm["quantity"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '<button name="submit_btn" class="save_order">Save Order</button>';
echo '</form>';
if(isset($_POST['submit_btn']) ){
$insquery = "INSERT INTO `pending_orders` (`OrderNo`,`BookName`,`Quantity`,`TotalPrice`,`ISBN`,`StudentID`) VALUES (NULL, '" . $obj->Title . "', '" . $cart_itm['quantity'] . "', '" . $total . "', '" . $ISBN . "', '" . $_SESSION['login_user'] . "');";
$stmt = $mysqli->prepare($insquery);
$stmt->execute();
}
}
?>
</div>
</div>
</body>
</html>
The code is supposed to save a customers book order into a database, It works perfectly fine for ONE book. Line 76 to 81 has the insert statement.
however if the person has purchased two books then only the last book gets added to the database. Screenshots added:
This is what it looks like on my website. As you can see the person has selected two books to be purchased:
http://postimg.org/image/3kj1gvytx/
However this is what i get in my phpmyadmin site:
http://postimg.org/image/k85hs56xj/
We can see that only the second book (biology) gets stored in the database. as well as the total of the two books
Any ideas how i could fix the issue and store both books.
Thanks

<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<br>
<div id="books-wrapper">
<!-- #content to center the menu -->
<div id="content">
<!-- This is the actual menu -->
<ul id="darkmenu">
<li>Home</li>
<li>Catalogue</li>
<li>Search</li>
<li>Cart</li>
<li>Orders</li>
</ul>
<div id = "welcome" >
Welcome, <?=$_SESSION['login_user']?>! <br> Logout
</div>
</div>
<br><br>
<h1 id = "mainHeader" >View Cart</h1>
<br>
<div class="view-cart">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["books"]))
{
$total = 0;
echo '<form method="post" action="">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["books"] as $cart_itm){
$ISBN = $cart_itm["ISBN"];
$results = $mysqli->query("SELECT Title,BookDesc,Price FROM books WHERE ISBN='$ISBN'");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-Price">'.$currency.$obj->Price.'</div>';
echo '<div class="book-info">';
echo '<h3>'.$obj->Title.' (ISBN :'.$ISBN.')</h3> ';
echo '<div class="p-quantity">Quantity : '.$cart_itm["quantity"].'</div>';
echo '<div>'.$obj->BookDesc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["Price"]*$cart_itm["quantity"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="itemname_['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="itemcode_['.$cart_items.']" value="'.$ISBN.'" />';
echo '<input type="hidden" name="itemdesc_['.$cart_items.']" value="'.$obj->BookDesc.'" />';
echo '<input type="hidden" name="itemquantity_['.$cart_items.']" value="'.$cart_itm["quantity"].'" />';
echo '<input type="hidden" name="total_['.$cart_items.']" value="'.$total.'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '<button name="submit_btn" class="save_order">Save Order</button>';
echo '</form>';
if(isset($_POST['submit_btn']) ){
$item_array = array();
foreach($_POST as $key => $value) {
// echo "POST parameter '$key' has '$value';
$pieces = explode("_",$key)
if(strstr($pieces[0] == 'itemname')
{
$item_array[$pieces[1]]['BookName'] = $value;
}
if(strstr($pieces[0] == 'itemcode')
{
$item_array[$pieces[1]]['ISBN'] = $value;
}
if(strstr($pieces[0] == 'itemquantity')
{
$item_array[$pieces[1]]['Quantity'] = $value;
}
if(strstr($pieces[0] == 'total')
{
$item_array[$pieces[1]]['TotalPrice'] = $value;
}
}
$insquery = "INSERT INTO `pending_orders` (`OrderNo`,`BookName`,`Quantity`,`TotalPrice`,`ISBN`,`StudentID`) VALUES ";
foreach($item_array as $row)
{
$insquery .= "(NULL, '" . $row['BookName'] . "', '" . $row['Quantity'] . "', '" .$row['TotalPrice']. "', '" . $row['ISBN'] . "', '" . $_SESSION['login_user'] . "'),";
}
$insquery = substr($insquery, 0, -1);
$stmt = $mysqli->prepare($insquery);
$stmt->execute();
foreach($_POST as $row)
$insquery = "INSERT INTO `pending_orders` (`OrderNo`,`BookName`,`Quantity`,`TotalPrice`,`ISBN`,`StudentID`) VALUES (NULL, '" . $obj->Title . "', '" . $cart_itm['quantity'] . "', '" . $total . "', '" . $ISBN . "', '" . $_SESSION['login_user'] . "');";
$stmt = $mysqli->prepare($insquery);
$stmt->execute();
}
}
?>
</div>
</div>
</body>
</html>
you form the insert statement like above

As you don't know Ajax, you can do something like this:
1) Reset $result array, to select items again for MySQL query.
2) With while loop insert each selected value into DB.
reset($result);
while($row=mysqli_fetch_array($result))
{
$ins = mysqli_query($con, "Here goes insert statement for each");
}
EDIT
$ISBN = $cart_itm["ISBN"];
$con = mysqli_connect("localhost","root","","yourbasename");
$result = mysqli_query($con, "SELECT Title,BookDesc, Price FROM books
WHERE ISBN='$ISBN'");
while($row=mysqli_fetch_array($result)
{
$insert = mysqli_query($con, "INSERT.....");
}

Related

how do I store quantity from all items in session?

I'm not seeing what goes wrong here? I want to allow my users to up the quantity from an item in their shopping cart. when they press enter I want the quantity to change from 1 to the number the use rput in and I want that it calculates everything correctly. but right now it only wants to update the last item that the user changed the quantity from. how do I fix this? I thought of using a $_SESSION but that doesn't make any difference. this is part of the code
<body>
<!--navbar-->
<a class="back" href="index.php"> <i class="bi bi-arrow-left-circle-fill bi-5x"></i></a>
<?php
include "config.php";
?>
<div class="text-center" style="font-size: 100px;">🛍</div>
<h2 class="text-center">Winkelmandje</h2><br>
<section class="container content-section">
<!-- <h2 class="section-header">CART</h2> -->
<div class="cart-row">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-item cart-header cart-column">PRICE</span>
<span class="cart-item cart-header cart-column">QUANTITY</span>
<span class="cart-item cart-header cart-column">berekening</span>
<!-- <span class="cart-item cart-header cart-column">Verwijderen</span> -->
</div>
<?php
$broodjes = $_GET['broodjes_ID'];
if (isset($_SESSION['basket'])){
if( in_array( $broodjes ,$_SESSION['basket']) )
{
}else{
$_SESSION['basket'][] = $broodjes;
}
}else{
$_SESSION['basket'][]= $broodjes;
}
$sumtotal = 0;
foreach($_SESSION['basket'] as $key => $value){
//echo "Key = $key; value = $value; <br>";
$sql = "SELECT broodjes_ID, broodnaam, prijs, voorraad FROM broodjes WHERE broodjes_ID=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $value);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
echo '<div class="cart-items">';
echo '<div class="cart-row">';
echo '<div class="cart-item cart-column">';
echo $row['broodnaam'];
echo '</div>';
echo '<div class="cart-item cart-column">';
echo '€ ' . $row['prijs'];
echo '</div>';
//quantity
echo '<div class="cart-item cart-column">';
echo '<form method="POST" action"">';
echo '<div class="col-xs-4">';
echo '<input type="hidden" name="broodnaam" id="broodnaam" value="' . $row['broodnaam'] . '">';
echo '<input type="number" name="quantity" id="quantity" class="form-control input-sm" placeholder="1" min="1" max="100" value="1">';
echo '</div>';
echo '</form>';
echo '</div>';
//session for quantity???'
$_SESSION['quantity'] = $_POST['quantity'];
$quantity = 1;
if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
$_SESSION['quantity'] = $_POST['quantity'];
if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
if ($_POST['broodnaam'] == $row['broodnaam']){
$quantity = $_POST['quantity'];
}
}
}
echo '<div class="cart-item cart-column">';
$rowtotaal = $row['prijs'] * $quantity;
$sumtotal += $rowtotaal;
echo $rowtotaal;
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?> <br />
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price"> € <?php echo $sumtotal;?></span>
</div>
<br/>
and this is what it does
now situation:
how do I store the information in a session??

How to select a result from a result that return by a SQL

I'm using SQL and PHP to pull information from my database and it returned a list of users that met the criteria. And I need to redirect to another page using the selected amount from the picture below. How can I grab this amount to another page?
For example, when I click the first select, I can go to the other page that showing $24, and Rubinsztein Abdel, 182 Crownhardt Lane...
<!--loader end-->
<!-- Main -->
<div id="main">
<!-- wrapper -->
<div id="wrapper">
<div class="content">
<!-- Map -->
<div class="map-container column-map right-pos-map">
<div id="map-main"></div>
<ul class="mapnavigation"></ul>
<div class="scrollContorl mapnavbtn" title="Enable Scrolling"><span><i class="fa fa-lock"></i></span></div>
</div>
<!-- Map end -->
<!--col-list-wrap -->
<div class="col-list-wrap left-list">
<!-- list-main-wrap-->
<div class="list-main-wrap fl-wrap card-listing">
<!-- listing-item -->
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$severname = "localhost";
$username = "root";
$password = "";
$dbname = "dbn";
//$conn = mysqli_connect('xx', 'xx', 'xx','xx');
$conn = mysqli_connect('dxx', 'xx', 'xx','xx');
//check connection
if (mysqli_connect_errno())
{echo nl2br("Failed to connect to MySQL: ". mysqli_connect_error() . "\n"); }
else
{ echo nl2br("");}
$city = mysqli_real_escape_string($conn, $_POST['city']);
$date1 = mysqli_real_escape_string($conn, $_POST['date1']);
$date2 = mysqli_real_escape_string($conn,$_POST['date2']);
$pet = mysqli_real_escape_string($conn, $_POST['pet']);
//var_dump($date2);
$sql = "SELECT CONCAT(s.lname, ' ', s.fname) AS fullName, s.ratings, s.rate, s.phone, s.address FROM Pet_Sitter AS s WHERE s.citystate='".$city."' AND s.pet_type='".$pet."' "
;
//echo $sql."<br/>";
$result = mysqli_query($conn,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("");
}
//var_dump($result);
$num_rows = mysqli_num_rows($result);
?> <div class="container"> <?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
//var_dump($row);
// echo "<tr><td>" . $row['fullName'] . " </td><td>" . $row['ratings'] . " </td><td>" . $row['rate'] . " </td></tr>";
// echo '<div class="listing-item">';
echo '<div class="listing-item">';
echo '<article class="geodir-category-listing fl-wrap">';
echo '<div class="geodir-category-img">';
echo '<img src="../images/all/1.jpg" alt="">';
echo '<div class="overlay"></div>';
echo '<div class="list-post-counter"><span>' . $row['rate'] . '</span></div>';
echo '</div>';
echo '<div class="geodir-category-content fl-wrap">';
echo '<a class="listing-geodir-category" href="../index.html">Pet sitting</a>';
echo '<h3>' . $row['fullName'] . '</h3>';
echo '<p>PET-SITTER INFORMATION</p>';
echo '<div class="geodir-category-options fl-wrap">';
echo '<span>' . 'Reviews ' . $row['ratings'] .'</span>';
echo '<div class="geodir-category-location">'. $row['address'] . " · " . $row['phone'] .
'</div>';
echo '</div>';
echo '</div>';
echo '</article>';
echo '</div>';
}?>
<?php
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</div>
</div>
An easy way to do it is to create one page (the one you wanna go if you click on your items) and use GET on URL to get the page id;
On your actual page you will use a link like :
<a href="new-page.php?id=<?php echo $row['id']; ?>"
Here the ?id= on URL is a parameter, that you can get on the other page :
$pageId = $_GET['id'];
Then, you just have to make a SQL request
SELECT * FROM Pet_Sitter WHERE id=$pageId
(better to use prepare and execute for this request as the value of $pageId can be change by everybody by changing the URL).
So every time you click on a link, the page will display the matching informations.
Also you should closed <?php when you are writing HTML instead of using a lot of echo.

Send SESSION GET information in POST contact form together with the POST fields

On the website i'm currently working on I made a list (cart idea) where customers can put products on. It works with GET method + a session, the code for the making of the session is as follows:
`<?php session_start();
require("dbconnect.php");
?>
<?php
if(!isset($_SESSION['cart'])) {
$cart = array();
$_SESSION['cart'] = $cart;
}
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(in_array($id, $_SESSION['cart'])){
if (($key = array_search($id, $_SESSION['cart'] !== false))){
unset($_SESSION['cart'][$key]);
}
}
else {
array_push($_SESSION['cart'],$id);
}
}
if(isset($_GET['action']) && $_GET['action']=="delete"){
$id = intval($_GET['id']);
if (in_array($id, $_SESSION['cart'])){
$key = array_search($id, $_SESSION['cart']);
unset($_SESSION['cart'][$key]);
}
}
?>
Nothing special, just a regular cart in a session with an array where I put all the unique product codes to remember what is on the list. Now when customers go to the page where they could send the list of product they also can select how many of each product they want. They have to fill in a number and when they are done they click on the button 'calculate (berekenen in my language)' and they get the subtotal price of all the products, the VAT and the total price. However, I want it this way that the customer can fill in their personal information plus the list plus the amounts to be send in an e-mail. I made selfmade PHP forms myself earlier but now i'm getting stuck. I use GET for the order list but I always use a POST form for my contactforms. How can I manage to make one button that sends the list plus the amounts plus the input of the contact form fields to me? At this moment I tried it as follows (and many more ways, but it all failed so far).
<main>
<div class="main-center">
<div class="offerte-container">
<form action="" method="get" value="offertelijst">
<ul class="offerte-list">
<?php
$per_page = 9;
$args = array(
'post_type'=> 'wpcproduct',
'order' => 'ASC',
'orderby' => 'menu_order',
'posts_per_page' => $per_page
);
$products = new WP_Query($args);
?>
<?php
while($products->have_posts()): $products->the_post();
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
echo '<li class="wpc-product-item">';
echo 'Verwijder ';
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
echo '<div class="item-title"> ' .$title. ' </div>';
echo '<div class="item-take"> <img width="25px" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/pijltje.png" /> </div>';
echo '<div class="item-nr"> '.$product_id. '</div>';
if((isset($_GET["amount$id"]) && $_GET["amount$id"] == 1) || $_GET["amount$id"] == "" ){
if (is_numeric($price) && (floor($price) == $price)) {
echo '<div class="item-price"> €' .number_format ($price , 0 , "," , "." ). ',- </div>';
}
else {
echo '<div class="item-price"> €' .$price. '</div>';
}
echo '</li>';
}
else if(isset($_GET["amount$id"]) && floatval($_GET["amount$id"]) > 1){
changeFormat($price);
$priceTotal = number_format($price * floatval($_GET["amount$id"]), 2);
if (is_numeric($priceTotal) && (floor($priceTotal) == $priceTotal)) {
echo '<div class="item-price"> €' .$priceTotal . ',- </div>';
}
else {
echo '<div class="item-price"> €' .$priceTotal . '</div>';
}
echo '</li>';
}}
endwhile;
?>
</ul>
<input type="submit" value="Bereken"> </input>
</form>
<div class="totalprice">
<?php
(float)$total = 0;
while($products->have_posts()): $products->the_post(); {
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
if (is_numeric($price) && (floor($price) == $price)) {
$price = number_format($price, 2);
}
else {
$price = str_replace(',', '.', $price);
}
$total += (floatval($price) * floatval($_GET["amount$id"]));
}}
endwhile;
(String)$total;
number_format($total, 2);
$totalDecimal = str_replace('.', ',', $total);
echo 'Subtotaal: €' .$totalDecimal. '<br />';
echo 'BTW: €' . str_replace('.',',', number_format($total * 0.21,2)). '<br />';
echo 'Totaal: €' . str_replace('.',',', number_format($total * 1.21,2));
function changeFormat($var) {
if(is_numeric($var) && (floor($var) == $var)){
return number_format($var, 0) + ',-';
}
else {
if (is_numeric($var)) {
return number_format($var, 2, ',', '.');
}
else if (is_string ($var)){
return str_replace(',', '.', $var);
}
else {
echo "What the hell is dit voor een formaat?";
}
}}
?>
</div>
</div>
</div>
</main>
The calculate function and the orderlist are all working fine and i'm able to make a standard POST form as a contactform but I can't manage to get this done. I want the button 'send' to send the list plus the given amounts per product and the filled in contact forms.
The URL for this project is: http://www.bgc-testomgeving.nl/sem
Underneath the http://www.bgc-testomgeving.nl/sem/offertelijst/ page should be the contact form but every time I try to build this I demolish my perfect order list.
First of all change your form method to post.
<form action="" method="post" value="offertelijst">
Then you have to create inputs for each item in your form element. I see this you have only Amount input in your form:
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
Create input for each element, since user doesnt need to see those inputs you can create them as hidden element, here is one example for item title:
echo '<input type="hidden" name="title['.$id.']" value="' .$title. '"</input>';
Put this below this line
echo '<div class="item-title"> ' .$title. ' </div>';
After you created all inputs, also create second button near of this one:
<input type="submit" name="action" value="Bereken">
<input type="submit" name="action" value="Send">
So When the user click Bereken, you will do your calculation things, but if it is Send button, you will mail it to your self. here is Example code:
<?php
// if send button clicked
if($_POST["action"]=="Send")
{
/// mail to your self all element
mail("you#www.com","New Order",implode("-",$_POST));
}
?>
<main>
<div class="main-center">
<div class="offerte-container">
<form action="" method="post" value="offertelijst">
<ul class="offerte-list">
<?php
$per_page = 9;
$args = array(
'post_type'=> 'wpcproduct',
'order' => 'ASC',
'orderby' => 'menu_order',
'posts_per_page' => $per_page
);
$products = new WP_Query($args);
?>
<?php
while($products->have_posts()): $products->the_post();
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
echo '<li class="wpc-product-item">';
echo 'Verwijder ';
echo '<input alt="hoeveelheid" maxlengt="2" value="' .$_GET["amount$id"]. '" min="1" type="number" max="99" name="amount'.$id.'" size="3" required> </input>';
echo '<div class="item-title"> ' .$title. ' </div>';
// i added below input for example
echo '<input type="hidden" name="title['.$id.']" value="' .$title. '"</input>';
echo '<div class="item-take"> <img width="25px" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/pijltje.png" /> </div>';
echo '<div class="item-nr"> '.$product_id. '</div>';
if((isset($_GET["amount$id"]) && $_GET["amount$id"] == 1) || $_GET["amount$id"] == "" ){
if (is_numeric($price) && (floor($price) == $price)) {
echo '<div class="item-price"> €' .number_format ($price , 0 , "," , "." ). ',- </div>';
}
else {
echo '<div class="item-price"> €' .$price. '</div>';
}
echo '</li>';
}
else if(isset($_GET["amount$id"]) && floatval($_GET["amount$id"]) > 1){
changeFormat($price);
$priceTotal = number_format($price * floatval($_GET["amount$id"]), 2);
if (is_numeric($priceTotal) && (floor($priceTotal) == $priceTotal)) {
echo '<div class="item-price"> €' .$priceTotal . ',- </div>';
}
else {
echo '<div class="item-price"> €' .$priceTotal . '</div>';
}
echo '</li>';
}}
endwhile;
?>
</ul>
<input type="submit" name="action" value="Bereken">
<input type="submit" name="action" value="Send">
</form>
<div class="totalprice">
<?php
// is bereken button clickied
if($_POST["action"]=="Bereken") {
(float)$total = 0;
while($products->have_posts()): $products->the_post(); {
$id = get_the_ID();
$title = get_the_title();
$permalink = get_permalink();
$price = get_post_meta(get_the_id(),'wpc_product_price',true);
$product_id = get_post_meta(get_the_id(), 'product_ID', true);
if(in_array($id, $_SESSION['cart'])){
if (is_numeric($price) && (floor($price) == $price)) {
$price = number_format($price, 2);
}
else {
$price = str_replace(',', '.', $price);
}
$total += (floatval($price) * floatval($_GET["amount$id"]));
}}
endwhile;
(String)$total;
number_format($total, 2);
$totalDecimal = str_replace('.', ',', $total);
echo 'Subtotaal: €' .$totalDecimal. '<br />';
echo 'BTW: €' . str_replace('.',',', number_format($total * 0.21,2)). '<br />';
echo 'Totaal: €' . str_replace('.',',', number_format($total * 1.21,2));
}
function changeFormat($var) {
if(is_numeric($var) && (floor($var) == $var)){
return number_format($var, 0) + ',-';
}
else {
if (is_numeric($var)) {
return number_format($var, 2, ',', '.');
}
else if (is_string ($var)){
return str_replace(',', '.', $var);
}
else {
echo "What the hell is dit voor een formaat?";
}
}}
?>
</div>
</div>
</div>
</main>

syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE) in Insert statement

Im trying to insert data from sessions into a database using an insert statement. I have data passed from a login screen which is stored in a session variable called "login_user". I also have a session called "books" which stores multiple variables such as the ISBN number, Title and Price of a book.
I have the following code:
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<br>
<div id="books-wrapper">
<!-- #content to center the menu -->
<div id="content">
<!-- This is the actual menu -->
<ul id="darkmenu">
<li>Home</li>
<li>Catalogue</li>
<li>Search</li>
<li>Cart</li>
<li>Orders</li>
</ul>
<div id = "welcome" >
Welcome, <?=$_SESSION['login_user']?>! <br> Logout
</div>
</div>
<br><br>
<h1 id = "mainHeader" >View Cart</h1>
<br>
<div class="view-cart">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["books"]))
{
if(isset($_POST['submit_btn']) ){
$sql = "INSERT INTO `orders` (`OrderNo`, `BookName`, `Quantity`, `TotalPrice`, `ISBN`, `StudentID`) VALUES (NULL, '$obj->Title', '$cart_itm['quantity']', '$total', '$ISBN', '$_SESSION['login_user']');";
}else {
$total = 0;
echo '<form method="post" action="">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["books"] as $cart_itm)
{
$ISBN = $cart_itm["ISBN"];
$results = $mysqli->query("SELECT Title,BookDesc,Price FROM books WHERE ISBN='$ISBN'");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-Price">'.$currency.$obj->Price.'</div>';
echo '<div class="book-info">';
echo '<h3>'.$obj->Title.' (ISBN :'.$ISBN.')</h3> ';
echo '<div class="p-quantity">Quantity : '.$cart_itm["quantity"].'</div>';
echo '<div>'.$obj->BookDesc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["Price"]*$cart_itm["quantity"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$ISBN.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->BookDesc.'" />';
echo '<input type="hidden" name="item_quantity['.$cart_items.']" value="'.$cart_itm["quantity"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '<button name="sumbit_btn" class="save_order">Save Order</button>';
echo '</form>';
}else{
echo 'Your Cart is empty';
}
}
?>
</div>
</div>
</body>
</html>
However my insert statement doesnt seem to work.
I get the ( ! ) Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) on line 43 which is the insert statement
I do have a page called Catalogue where the variables are instantiated but these are then passed onto the view cart page which is above.
Any idea whats wrong with the statement?
replace line 43 with
$sql = "INSERT INTO `orders` (`OrderNo`, `BookName`, `Quantity`, `TotalPrice`, `ISBN`, `StudentID`) VALUES (NULL, '{$obj->Title}', '{$cart_itm['quantity']}', '{$total}', '{$ISBN}', '{$_SESSION['login_user']}');";
And remember to sanitize your variables!
just replace 43 line with the below code
$sql = "INSERT INTO `orders` (`OrderNo`, `BookName`, `Quantity`, `TotalPrice`, `ISBN`, `StudentID`) VALUES (NULL, $obj->Title, $cart_itm['quantity'], $total, $ISBN, $_SESSION['login_user']);";
let me know its working or not?.

MySQL separate in to DIV elements

I would greatly enjoy knowing how to separate the results of my query based on the "season" using PHP only. The products should be placed in separate divs according to what season they are for. I would also like to do this in the most efficient way possible. I have thought about his for some time and have failed both in a solution and in finding someone else's similar results on the internet. Please ignore the jquery, it is a leftover for something I may or may not use.
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Shop</title>
<link rel="stylesheet" type="text/css" href="style/main.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0
/jquery.min.js"></script>
<script type="text/javascript" src="script/jquery.simplyscroll.min.js"></script>
<script type="text/javascript">
(function($) {
$(function() {
$("#scroller").simplyScroll();
});
})(jQuery);
</script>
</head>
<body>
<div id="container">
<div id="header">
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Shop</li>
<li>Contact</li>
</ul>
</div>
</div>
<div id="content">
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
//$results = $db->query('SELECT id, name, thumb, description, price, season FROM products
BY season ASC');
foreach($db->query('SELECT id, name, thumb, description, price FROM products BY season
ASC') as $results){
if ($results) {
//output results from database
$last_season = 1;
echo '<div class="products">';
while($obj = $results->fetch_object())
{
if ($last_season != $obj->season){
echo '</div><div class="products">';
}
echo '<div class="product">';
echo '<form method="post" action="cart_update.php">';
echo '<div class="product-thumb"><img src="image/'.$obj->product_img_name.'"></div>';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-desc">'.$obj->product_desc.'</div>';
echo '<div class="product-info">Price '.$currency.$obj->price.' <button
class="add_to_cart">Add To Cart</button></div>';
echo '</div>';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
$last_season = $obj->season;
}
echo '</div>';
}
}
?>
<div id="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<ol>';
foreach ($_SESSION["products"] as $cart_itm)
{
echo '<li class="cart-itm">';
echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&
return_url='.$current_url.'">×</a></span>';
echo '<h3>'.$cart_itm["name"].'</h3>';
echo '<div class="p-code">P code : '.$cart_itm["code"].'</div>';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div class="p-price">Price :'.$currency.$cart_itm["price"].'</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}
echo '</ol>';
echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> Check-out!</span>';
echo '<span class="empty-cart"><a href="cart_update.php?emptycart=1&
return_url='.$current_url.'">Empty Cart</a></span>';
}else{
echo 'Your Cart is empty';
}
?>
</div>
</div>
<div id="footer">Footer goes here.</div>
</div>
</body>
</html>
I am getting an error on line 44, which is the start of the "foreach" statement. I am again at a loss. Thank you a ton for your help so far. If I can get this working, with help of course, I will be extremely excited and in your debt.
Here's a loop that will create a new div each time the season changes in a new row. You will need to change the query to order the results by season, e.g.
ORDER BY season ASC
Here's the loop:
if ($results) {
//output results from database
$last_season = 1; //initial value
echo '<div class="season">'; //opens first season div
while($obj = $results->fetch_object()){
if ($last_season != $obj->season){
echo '</div><div class="season">';
}
echo '<div class="product">';
echo '<form method="post" action="cart_update.php">';
echo '<div class="product-thumb"><img src="image/'.$obj->product_img_name.'"></div>';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-desc">'.$obj->product_desc.'</div>';
echo '<div class="product-info">Price '.$currency.$obj->price.' <button class="add_to_cart">Add To Cart</button></div>';
echo '</div>';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
$last_season = $obj->season;
}
echo '</div>'; //closes final season div
}
Regarding the line 44 error in the foreach, I believe what you want there instead of a foreach is simply:
$results = $db->query('SELECT id, name, thumb, description, price FROM products BY season
ASC'); //remember to remove the closing bracket of the foreach

Categories