Why does my Submit button not redirect - php

I have a form with a submit button.
<input type="submit" name="submitOrder" id="submitOrder" value="Purchase" class="btn btn-warning">
Below this I have a couple lines of code:
<?php
if (isset($_POST['submitOrder'])) {
header ("location:payment.php?discount=". $discountCode ."");
}
?>
Why does that button when clicked, do nothing but reload the page? I want it to redirect the user to payment.php?
Entire form with the submit button...
<form method="post" action="cart_update.php">
<div class="row" style="padding-bottom: 10px;">
<div class="col-md-2">
<strong>Quantity</strong>
</div>
<div class="col-md-3">
<strong>Name</strong>
</div>
<div class="col-md-2">
<strong>Price</strong>
</div>
<div class="col-md-2">
<strong>Total</strong>
</div>
<div class="col-md-3">
<strong>Remove</strong>
</div>
</div>
<?php
if(isset($_SESSION["cart_products"])) { // Check session var
$total = 0; // Set initial total value
foreach ($_SESSION["cart_products"] as $cart_itm) {
// Set variables to use in content below
$ProductName = $cart_itm["ProductName"];
$product_qty = $cart_itm["product_qty"];
$Price = $cart_itm["Price"];
$ProductCode = $cart_itm["ProductCode"];
$subtotal = ($Price * $product_qty); // Calculate Price x Qty
echo '<div class="row" style="padding: 10px 0;">';
echo '<div class="col-md-2">Qty: <input type="text" size="2" maxlength="4" name="product_qty['. $ProductCode .']" value="'. $product_qty .'" /></div>';
echo '<div class="col-md-3">Product Name: '. $ProductName .'</div>';
echo '<div class="col-md-2">Price: '. $currency . $Price .'</div>';
echo '<div class="col-md-2">Total: £';
echo money_format('%i', $subtotal);
echo '</div>';
echo '<div class="col-md-3"><input type="checkbox" name="remove_code[]" value="'. $ProductCode .'" /></div>';
echo '</div>';
echo '<hr>';
$total = ($total + $subtotal); // Add subtotal to total var
$grand_total = $Price * $product_qty;
}
$grand_total = $total + $shipping_cost; // Grand total including shipping cost
foreach($taxes as $key => $value) { // List and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; // Add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value) { // List all taxes
$list_tax .= $key. ' : '. $currency . sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost) ? 'Shipping Cost: ' . $currency . sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<br />
<div class="row">
<span style="float: right; text-align: right; width: 100%;">Amount Payable: <strong>£<?php echo sprintf("%01.2f", $_SESSION['grand_total'] = $grand_total); ?><br />Price inc. VAT and Postage + Packaging</strong><br />Discount Code: <input type="text" name="discountCode" id="discountCode" value="TEST" /></span>
<br />
<br />
Continue Shopping
<button type="submit" class="btn btn-warning">Update</button>
<!-- Purchase -->
<input type="submit" name="submitOrder" id="submitOrder" value="Purchase" class="btn btn-warning">
<?php
if (isset($_POST['submitOrder'])) {
header ("location:payment.php?discount=". $discountCode ."");
}
$_SESSION['ProductName'] = $ProductName;
$_SESSION['product_qty'] = $product_qty;
$_SESSION['grand_total'] = $grand_total;
?>
</div>
<input type="hidden" name="return_url" value="<?php $current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); echo $current_url; ?>" />
</form>

The problem is, there is output, before you send the redirect headers, because your condition is in the html section.
You should place the code with the redirect before any output is sent to the client.
An other option would be to turn on output buffering, but this must also be done, before something is sent to the client.

ensure the very first item returned is the header with no whitespace or anything before it ie echos or text,
check the log files for headers already sent errors
make sure the button is inside the form

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 validate checkbox in a for loop

I am creating a seat reservation system. In my system, the code check number of seats a bus contains then pass it inside a for loop. When a user pick 2 passengers, it means two seats will be booked. How can I validate the checkbox in the for loop depending on the number of passenger(s) selected.
Using the GUI for more explanation.
on the main page, 2 there indicates number of passenger(s) selected.
When you come to the second page where the values are passed to, you can see 2 Adults as the selected number of passengers. When you click on Submit Button it does not validate the checkbox based on the number of passenger(s) selected. And if I should put required in the checkbox it validates the whole checkbox since it is in a loop
$_SESSION['seat_no'] is the number of seat(s) a bus contains. Let assume a user that want to book a seat selected two passengers which means two seats is booked, how can I validate the checkbox based on the number of seat(s) selected?
Here is my code:
<?php
for ($i = 1; $i <= $_SESSION['seat_no']; $i++) {
if(in_array($i,$mseat)){
echo "<div class='checkbox_wrapper_pick'>
<label>".$i."</label>
</div>";
}else{
echo "<div class='checkbox_wrapper'>
<input type='checkbox' value=".$i." name='seat_book[]' />
<label>".$i."</label>
</div>";
}
}
?>
The full source code:
<?php include("header.php"); error_reporting(0); ?>
<?php
if(isset($_POST['submit'])){
$from = $_POST['from'];
$to = $_POST['to'];
$date = $_POST['d_date'];
$nop = $_POST['nop'];
$_SESSION['from'] = $from;
$_SESSION['to'] = $to;
$_SESSION['date'] = $date;
$_SESSION['nop'] = $nop;
$get = mysqli_query($mysqli,"SELECT * FROM routes WHERE present_loc = '$from' and destination = '$to' ");
while($roys = mysqli_fetch_array($get)){
//get bus details
$bno = $roys['bus_no'];
$ploc = $roys['present_loc'];
$des = $roys['destination'];
$time = $roys['dept_time'];
$_SESSION['time'] = $time;
$amt = $roys['amount'];
$_SESSION['amt'] = $amt;
$b = str_replace( ',', '',$_SESSION['amt'] );
if( is_numeric($b) ) {
$a = $b;
}
$bus = mysqli_query($mysqli,"select * from bus where bus_no = '$bno'");
while($bu = mysqli_fetch_array($bus)){
$_SESSION['model'] = $bu['model'];
$_SESSION['seat_no'] = $bu['seat_no'];
$_SESSION['ac'] = $bu['bus_type'];
$_SESSION['excess_luggage'] = $bu['excess_luggage'];
$_SESSION['more_legs'] = $bu['more_legs'];
$_SESSION['id'] = $bu['id'];
}
$coun = mysqli_query($mysqli, "select count(booking_id) as seat, seats from booking where bus_no = '$bno' and seats !='' GROUP by booking_id" );
$mseat = array();
while($e = mysqli_fetch_array($coun)){
$bseat = $e['seat'];
$mseat[] = $e['seats'];
}
//$seatss = array();
$seat_string = implode(",",$mseat);
//get seats
$couns = mysqli_query($mysqli, "select sum(counter) as seat from booking where bus_no = '$bno' and seats !='' GROUP by bus_no" );
$rseats = mysqli_fetch_array($couns);
$lseat = $rseats['seat'];
if($_SESSION['seat_no'] == $lseat){
$tell = " No more seat(s) available.";
}else{
$tell = $_SESSION['seat_no'] - $lseat. " Seat(s) remaining.";
}
}
}
?>
<!--Main layout-->
<main class="mt-5">
<!--Main container-->
<form action="details" method="POST">
<!--Grid row-->
<div class="row">
<div class="col-lg-12 title-header mb-3 mx-auto z-depth-1">
<div class="row">
<div class="col-lg-8">
<?php echo '<h2> '.$_SESSION['from']. ' to '. $_SESSION['to']. '</h2>'; ?><br/>
<b><?php echo $_SESSION['date']; ?> :: <?php if($_SESSION['nop'] < '2') { echo $_SESSION['nop'] . ' Adult'; }
elseif($_SESSION['nop'] > 1) { echo $_SESSION['nop'] . ' Adults'; }
?></b>
</div>
</div>
</div>
<div class="col-lg-12 mbody"> <label style="margin-left: 4%; font-weight:bolder; font-size:20px; color:#000;">Details </label> </div>
<div class="col-lg-12 mbody bg-white ">
<table class="table table_view" style = "width: 100%; margin-left: 4%; margin-right:4%;">
<tbody>
<tr>
<td><b><?php echo $_SESSION['model']; ?></b><br/><?php echo $_SESSION['from']. ' to '. $_SESSION['to']; ?>
<br/><?php if($_SESSION['ac'] == 'AC') { echo '<span class="alert-info ac">'. $_SESSION['ac'] .'</span>'; }
else{ echo '<span class="alert-warning">No AC</pan>'; } ?>
<?php if($_SESSION['more_legs'] == 'Yes') { echo '<span class="alert-info ac">More Leg Room</span>'; }
else{ echo '<span class="alert-warning no">More Leg Not Available</pan>'; } ?>
</td>
<td><b>Departing Time</b><br/><i class="fa fa-clock-o" aria-hidden="true"></i> <?php echo $_SESSION['time']; ?></td>
<td> <img id = "seatimg" src="../images/seatsLayout/av.gif" class="img-responsive"> <?php echo $tell; ?></td>
<td>Adult <b>₦<?php echo $_SESSION['amt']; ?></b></td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-12">
<div class="col-lg-12 mbody"> <label style="margin-left: 3%; font-weight:bolder; font-size:20px; color:#000;"><img id = "seatimg" src="../images/seatsLayout/av.gif" class="img-responsive"> Select Seat</label> </div>
<div class="row detail">
<!--Grid column-->
<div class="col-lg-7 animation slideUp" >
<div class="well" id="bus_seats_layout" >
<table class="table table-bordered" cellspacing = "1" id="seatstable">
<tr>
<td><img id = "driverimg" src="../images/seatsLayout/steering.png" class="img-responsive" width="25" height="25"></td>
<td colspan="2" rowspan="3">
<?php
for ($i = 1; $i <= $_SESSION['seat_no']; $i++) {
if(in_array($i,$mseat)){
echo "
<div class='checkbox_wrapper_pick'>
<label>".$i."</label>
</div>
";
}else{
echo "
<div class='checkbox_wrapper'>
<input type='checkbox' value=".$i." name='seat_book[]' />
<label>".$i."</label>
</div>
";
}
}
?>
</td>
</tr>
</table>
</div>
</div>
<div class="col-lg-5">
<ul class="bt">
<li><img src="../images/seatsLayout/seat_available.png" class="img-responsive"> Available</li>
<li><img src="../images/seatsLayout/picked.png" class="img-responsive"> Selected</li>
<li><img src="../images/seatsLayout/seat_booked.png" class="img-responsive"> Booked</li>
</ul>
</div>
</div>
<div class="col-lg-12">
<input type="hidden" name="bus_no" value="<?php echo $bno; ?>">
<input type="hidden" name="to" value="<?php echo $to; ?>">
<input type="hidden" name="from" value="<?php echo $from; ?>">
<input type="hidden" name="amt" value="<?php echo $nop*$a; ?>">
<input type="hidden" name="nop" value="<?php echo $nop; ?>">
<div class="form-group">
<div align="right">
<input type="submit" name="submit" class="bme" value="Continue">
</div>
</div>
</div>
</div>
</div>
</form>
</main>
<?php include("footer.php"); ?>

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>

foreach loop results to INSERT into database

I have three different div's that contain the checkout information.
Shipping info
Billing Info
Order confirmation
The shipping information and billing information is obtained by the customer entering that information in manually, but the order confirmation, that contains what they are ordering, the quantity, and pertinent information to that order resides there. That information is obtained from a foreach loop I have in place that displays the information based on the product's ID.
I am trying to figure out how I am going to INSERT the string that displays from my foreach loop into my database. I have an order report page that I want to display what was ordered.
For the shipping information, I validate it and then send my query in with that information. Like this...
<?php
if(Input::exists()) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'fullname' => array(
'required' => true,
'min' => 2,
'max' => 50
)
if($validation->passed()) {
if(isset($_POST['create'])){
$fullname = trim( $_POST['customer_name'] );
?>
<div class="field">
<label class="paddingleft" for="fullname">Full Name</label>
<div class="center"><input type="text" class="biginputbarinline" name="fullname" value="<?php echo escape(Input::get('firstname')); ?>" required></div>
</div>
The part that I am really confused with is how to INSERT the actual string this foreach loop displays. If the result of my foreach loop was:
2 balls
4 shoes.
I want that information to send in with my query.
This is how I have the Order confirmation section as of now..
<div class="checkoutconfirmationcontainer">
<?php foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
?>
<span class="tealmedium"><?php echo $product['quantity'] . " - " . $products[$product_id]['name'] . $message; ?></span><br><br><br>
<div class="floatleft"><div class="smallerimgcontainer">
<?php
$result = mysqli_query($con,"SELECT * FROM products");
if($row = mysqli_fetch_array($result)) {
$products[$row['product_id']] = $row;
if($row['image'] == ""){
echo "<img class='sizedimg' src='/productpics/coming_soon.png' alt='Coming Soon'>";
} else {
echo "<img class='sizedimg' src='/productpics/".$row['img']."' alt='Product Picture'>";
}
echo "<br><br><br><br>";
}
?>
</div></div>
<div class="checkoutitemsummary">
<?php echo "<a href='./viewProduct.php?view_product=$id'>" . $product['name'];?><?php echo $products[$product_id]['name']; ?> </a>
<p><span class="redprice"><?php echo '$' . $products[$product_id]['price'] . "<br />"; }?></span></p>
</div>
How can I get the results of my foreach loop to be inserted into my database with my query?
Shopping Cart
<tr>
<th class="cartth">Name</th>
<th class="cartth">Price</th>
<th class="cartth">Category</th>
<th class="cartth">Quantity</th>
</tr>
<?php
$base_price = 0;
foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
$base_price += $products[$product_id]['price'] * $product['quantity'];
$shipping_price += $products[$product_id]['shippingprice'] * $product['quantity'];
?>
<tr>
<td class="carttd"><?php echo "<a href='./viewProduct.php?view_product=$id'>" . $product['name'];?><?php echo $products[$product_id]['name']; ?> </a>
</td>
<td class="carttd"><?php echo '$' . $products[$product_id]['price']; ?></td>
<td class="carttd"><?php echo $products[$product_id]['category']; ?></td>
<td class="carttd">
<?php echo "<input type='text' name='quantity[$product_id]' value='" . $product['quantity'] . "' />"; ?> </td>
</tr>
<?php
}
Javascript/Jquery that produces my div transition:
$('.checkoutmenu>li').on('click',function(e){
$('.checkoutprocess>.'+ e.target.classList[0]).show().siblings().hide();
});
<script>
$('.paymentinfocontainer').hide();
$('.confirmationinfocontainer').hide();
</script>
<script>
$('#button2').click(function () {
$(".checkoutprocess > div").hide();
$('.paymentinfocontainer').show("slow");
});
</script>
<script>
$('#button3 ').click(function () {
$(".checkoutprocess > div").hide();
$('.confirmationinfocontainer').show("slow");
});
</script>
<script>
/*
$('#button1').click(function () {
$(".checkoutprocess > div").hide();
$('.shippinginfocontainer').show("slow");
});
</script>
<script>
$('#button2 ').click(function () {
$(".checkoutprocess > div").hide();
$('.paymentinfocontainer').show("slow");
});
</script>
<script>
$('#button3 ').click(function () {
$(".checkoutprocess > div").hide();
$('.confirmationinfocontainer').show("slow");
});
*/
</script>
Ok, when I clicked on "3. Order Confirmation", I got the following HTML:
<div class="confirmationinfocontainer" style="display: block;">
<span class="summarytitle"><p>Order Confirmation</p></span>
<br>
<div class="floatrightinline">
<div class="confirmshippinginfo">
<p>Shipping to:</p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>
</div>
<div class="checkoutconfirmationcontainer">
<div name="product_id"></div>
<span class="tealmedium">1 - Lakers Hat</span>
<br>
<br>
<br>
<div class="floatleft">
<div class="smallerimgcontainer">
<img alt="Coming Soon" src="/productpics/coming_soon.png" class="sizedimg">
<br>
<br>
<br>
<br>
</div>
</div>
<div class="checkoutitemsummary">
Lakers Hat
<p><span class="redprice">$25<br></span></p>
</div>
<input type="hidden" value="405bb6b2b562b4f00dac620d3f68620f" name="token">
<input type="submit" value="Place Your Order" class="widebutton">
<br>
</div>
</div>
So I see you're already making use of a hidden field. So when a users clicks the "Place Your Order" button, you want the details to be passed along. You can simply add these details back to the form via a hidden field. Like so:
<div class="checkoutconfirmationcontainer">
<?php
foreach($_SESSION['shopping_cart'] as $id => $product) {
$product_id = $product['product_id'];
?>
<input type="hidden" name="product_quantity[<?php echo $id; ?>]" value="<?php echo $product['quantity']; ?>" />
<span class="tealmedium"><?php echo $product['quantity'] . " - " . $products[$product_id]['name'] . $message; ?></span><br><br><br>
<div class="floatleft"><div class="smallerimgcontainer">
<?php
$result = mysqli_query($con,"SELECT * FROM products");
if($row = mysqli_fetch_array($result)) {
$products[$row['product_id']] = $row;
if($row['image'] == ""){
echo "<img class='sizedimg' src='/productpics/coming_soon.png' alt='Coming Soon'>";
} else {
echo "<img class='sizedimg' src='/productpics/".$row['img']."' alt='Product Picture'>";
}
echo "<br><br><br><br>";
}
?>
</div></div>
<div class="checkoutitemsummary">
<?php echo "<a href='./viewProduct.php?view_product=$id'>{$product['name']} {$products[$product_id]['name']}</a>"; ?>
<p><span class="redprice"><?php echo '${$products[$product_id]['price']}<br />"; }?></span></p>
</div>
<input type="hidden" name="token" value="405bb6b2b562b4f00dac620d3f68620f">
<input class="widebutton" type="submit" value="Place Your Order">
<br />
</div>
Looking over this, I see no <form> for this. So I suspect JQuery is handling this somewhere else. So my fix may not really get read if your JQuery or app does not now what to look for, or does not hook onto that hidden field. If this is a framework that you're using or Catalog that you're modifying, check their support. I would say you have a lot more work ahead of you.

Wordpress the_excerpt showing same data for all id's

I have a cart plugin for Wordpress. It uses the_excerpt to show the product description. it works on all pages except the checkout page. On the checkout page it shows the same description for all the products. The description it shows is always from the first product in the database even if that product is not in the cart. I have tried many variations nothing fixes it. it pulls the correct id and price for the product but just the description is always the same for al products.
<?php the_excerpt(get_the_ID()); ?>
<input id="item-<?php echo $item->ID; ?>-price" name="item-<?php echo $item->ID; ?>-price" type="hidden" value="<?php echo intval($price); ?>"/>
In the code above, the price pulls correctly but the_excerpt is same for every product.
i have tried:
<?php the_excerpt(get_the_ID()); ?>
<?php the_excerpt($item->ID); ?>
<?php the_excerpt(get_the_excerpt); ?>
i have also tried if and while but then it just shows all 20 product descriptions for each product
this is all the code for the page:
<script>
window.onload = calculate_order(0,0);
function calculate_order(qty_item, qty_type) {
//qty_type could be add or substract
total = 0;
numberofitems = 0;
if (qty_type == "add"){
document.getElementById((qty_item+"-qty")).value++;
}
if (qty_type == "subtract") {
if (document.getElementById((qty_item+"-qty")).value > 0) {
document.getElementById((qty_item+"-qty")).value--;
}
}
//return;
$('.store-item').each(function(i, obj) {
price = document.getElementById(($(this).attr("id")+"-price")).value;
//price = price * 1 ;
qty = document.getElementById(($(this).attr("id")+"-qty")).value;
//qty = qty * 1;
numberofitems = numberofitems + (qty*1);
total = total + ((price*1)*(qty*1));
//alert (numberofitems);
});
document.getElementById("total_price").innerHTML = total ;
document.getElementById("total_qty").value = numberofitems ;
discount = 100*Math.floor(numberofitems/2);
document.getElementById("total_discount").innerHTML = discount ;
document.getElementById("final_price").innerHTML = (total - discount);
document.getElementById("tot_discount").value = discount ;
document.getElementById("tot_order").value = (total - discount);
document.getElementById("tot_price").value = total ;
if (numberofitems <2) {
$("#total-price").hide();
$("#total-discount").hide();
}
else {
$("#total-price").show();
$("#total-discount").show();
}
return;
}
</script>
<div id="shopping-cart">
<div>
<h2>Shopping Cart</h2>
</div>
<div id="section group">
<div class="col span_1_of_4"> Items in Cart</div>
<div class="col span_1_of_4">
Description
</div>
<div class="col span_1_of_4" style="text-align:center">
Price
</div>
<div class="col span_1_of_4" style="text-align:right">
Quantity
</div>
</div></div>
<div style="clear:both"></div>
<div class="cart-header">
<div id="checkout-form" class="cart-header" style="border:0px;">
<fieldset class="addressdetails">
<table width="330" border="0" cellspacing="0" cellpadding="0">
<tr><td style="width:120px;padding-bottom:5px">Your Name:</td><td style="padding-bottom:5px"><input id="yName" type="text" name="order_name2" style="background-color:#D3E3F8"/></td></tr>
<tr><td>Your Email</td><td style="padding-bottom:5px"><input id="Email" type="text" name="order_email" style="background-color:#D3E3F8"/> </td></tr>
<tr><td></br></td><td>
<tr><td style="width:120px;padding-bottom:5px">Shipping Name:</td><td style="padding-bottom:5px"><input id="Name" type="text" name="order_name" style="background-color:#D3E3F8"/></td></tr>
<tr><td>Shipping Address:</td><td style="padding-bottom:5px"><input id="Address" type="text" name="order_address" style="background-color:#D3E3F8"/></td></tr>
<tr><td>City: </td><td style="padding-bottom:5px"><input id="City" type="text" name="order_city" style="background-color:#D3E3F8"/></td></tr>
<tr><td>State:</td><td style="padding-bottom:5px"><input id="State" type="text" name="order_state" style="background-color:#D3E3F8"/></td></tr>
<tr><td>Zip Code:</td><td style="padding-bottom:5px"><input id="ZipCode" type="text" name="order_zipcode" style="background-color:#D3E3F8"/></td></tr>
<tr><td>Country:</td><td><input id="Country" type="text" name="order_country" style="background-color:#D3E3F8"/></td></tr>
<tr><td></br></td><td>
<tr><td>Comments</td><td style="padding-bottom:5px"><textarea id="Comments" name="order_comments" style="width:180px;background-color:#D3E3F8"></textarea></td></tr>
</table>
</br>
</fieldset>
</br>
<div><label></label><center><input type="submit" name="submit" value="Submit Order" class="submit_order_button"/></center></div>
</div>
</div>
<?php $total = 0; ?>
<?php $nitems = 0; ?>
<?php foreach ($_POST as $item => $quantity): ?>
<?php $matches = array(); ?>
<?php if (preg_match('/^item-([0-9]+)$/', $item, $matches) === 1 and intval($quantity) > 0): ?>
<?php $item = get_post(intval($matches[1])); ?>
<?php if ($item): ?>
<?php $nitems++; ?>
<?php $price = intval(get_post_meta($item->ID, 'price', true)); ?>
<?php $total += $price; ?>
<div class="section group" style="margin:10px 0 10px 0">
<input id="item-<?php echo $item->ID; ?>-ID" type="hidden" name="art_id[]]" value="<?php echo $item->ID; ?>"/>
<div class="col span_1_of_4" style="text-align:center">
<?php echo get_the_post_thumbnail($item->ID, 'checkout-thumbnail'); ?>
</div>
<div class="col span_1_of_4">
<h2><?php
$title = explode('(', $item->post_title, 2);
echo $title[0];
if (count($title) > 1) {
echo '<span class="parenthetical">(';
echo preg_replace('/ /', ' ', $title[1]);
echo '</span>';
}
?></h2>
<?php while ( have_posts() ) : the_post(); ?>
<?php
$my_excerpt = get_the_excerpt();
if ( $my_excerpt != '' ) {
// Some string manipulation performed
}
echo get_the_excerpt($item->ID); // Outputs the processed value to the page
?>
<?php endwhile; ?>
</div>
<div class="col span_1_of_4" style="text-align:center">
$ <span id="price"><?php echo $price; ?></span>
</div>
<input id="item-<?php echo $item->ID; ?>-price" name="item-<?php echo $item->ID; ?>-price" type="hidden" value="<?php echo intval($price); ?>"/>
<div class="col span_1_of_4" style="text-align:right">
<input type="text" class="store-item-quantity" style="width:20px" name="item-<?php echo $item->ID; ?>-qty" id="item-<?php echo $item->ID; ?>-qty" value="<?php echo intval($quantity); ?>" readonly />
<input type='button' class="qtybutton" name='add' onclick='javascript: calculate_order("item-<?php echo $item->ID; ?>", "add");' value='+'/>
<input type='button' class="qtybutton" name='subtract' onclick='javascript: calculate_order("item-<?php echo $item->ID; ?>", "subtract");' value='-'/>
</div></div>
<!--<input id="item-<?php echo $item->ID; ?>-qty" type="text" value="<?php echo intval($quantity); ?>"/>-->
</div></div>
<?php endif; ?>
<?php endif; ?>
<?php endforeach; ?>
<!-- MSR 11062013 display mode of discount -->
<?php $discount = 100*intval(floor($nitems/2)); ?>
<div id="price-totals" style="padding-right:20px">
Price includes international shipping<br />
<table id="price-table">
<input id="total_qty" type="hidden" value="<?php echo $nitems; ?>"/>
<tr id="total-price" <?php if ($nitems < 2) echo 'style="display:none"' ?>>
<td class="price-label">Total:</td>
<td class="price-value">$ <span id="total_price"><?php echo $total; ?></span></td>
</tr>
<tr id="total-discount" <?php if ($nitems < 2) echo 'style="display:none"' ?>>
<td class="price-label">Discount:</td>
<td class="price-value">$ <span id="total_discount"><?php echo $discount; ?></span> </td>
</tr>
<tr>
<td class="price-label"><strong>Final Price:</strong></td>
<td class="price-value"><strong>$ <span id="final_price"><?php echo $total - $discount; ?></strong></span></td>
</tr>
</table>
<input id="tot_price" type="hidden" name="tot_price" value="<?php echo $total; ?>"/>
<input id="tot_discount" type="hidden" name="tot_discount" value="<?php echo $discount; ?>"/>
<input id="tot_order" type="hidden" name="tot_order" value="<?php echo $total - $discount; ?>"/>
</div>
</div>
</div>
</div>
You can't pass parameters to the_excerpt, it always uses the "post in the loop", same goes for get_the_excerpt (I was wrong earlier). By looking at your code, you are looping over each item and getting its corresponding WP_Post object. Its excerpt should then be in $item->post_excerpt
A potentially cleaner way of doing this would be to create a new WP_Query that you can loop over. See http://codex.wordpress.org/The_Loop#Multiple_Loops

Categories