How to validate checkbox in a for loop - php

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"); ?>

Related

How to display data from multiple table with php

Here is my Song.php code which i created a class so i can use it in the index.php file
<?php
require_once("dbInfo.php");
Class Song{
public $length;
public $picture;
public $urlSong;
public $songId;
public $lastname;
public static function getAllRecords($pageNo, $pageSize, &$totalRecords) {
// Connect to database.
$options = array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = "mysql:host=" . DatabaseInfo::getServer() . ";dbname=" . DatabaseInfo::getDatabaseName() . ";charset=utf8";
$conn = new PDO($dsn, DatabaseInfo::getUserName(), DatabaseInfo::getPassword(), $options);
$pageNo = (int)$pageNo;
$pageSize = (int)$pageSize;
$sql = "SELECT COUNT(*) AS Count
FROM `
(SELECT song.SongId,song.Picture,song.Length,song.UrlSong,artist.Lastname FROM song LEFT JOIN
songandartist on song.SongId= songandartist.SongId INNER JOIN artist on songandartist.ArtistId=artist.ArtistId)AS T1`";
// Prepare statement.
$stmt = $conn->prepare($sql);
// Execute the statement.
$stmt->execute();
// Get total records count.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$totalRecords = $row['Count'];
$stmt = NULL;
$totalPages = ceil($totalRecords / $pageSize);
if ($pageNo > $totalPages) {
$pageNo = $totalPages;
}
$start = $pageSize * $pageNo - $pageSize;
if($start < 0) {
$start = 0;
}
$sql = "SELECT `Length`,`Picture`,`SongId`,`Lastname`,`UrlSong` FROM
`(SELECT song.SongId,song.Picture,song.Length,song.UrlSong,artist.Lastname FROM song left join songandartist on song.SongId= songandartist.SongId INNER JOIN artist on songandartist.ArtistId=artist.ArtistId)AS T1`
LIMIT $start, $pageSize;";
// Prepare statement.
$stmt = $conn->prepare($sql);
// Execute the statement.
$stmt->execute();
// Fetch all records.
$list = Array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$song = new GetAllSong();
$song->length = $row["Length"];
$song->picture = $row["Picture"];
$song->songId = $row["SongId"];
$song->lastname = $row["Lastname"];
$song->urlSong = $row["UrlSong"];
array_push($list, $song);
}
// Close the database connection.
$conn = NULL;
return $list;
}
}
?>
And here is my index.php code, i called the class and used the function but it did not work
<?php
include '../Song.php';
?>
<div class="container">
<div class="row py-5">
<div class="col-lg-12 mx-auto">
<div class="p-5 rounded shadow "
style="border-radius: 1rem;background-color: rgba(255, 255, 255, 0.58);">
<h2 class="mb-5">Table Song</h2>
<div class="p-1 bg-light rounded rounded-3 shadow-sm mb-4">
<div class="input-group">
<input type="search" placeholder="Search..." aria-describedby="button-addon1" class="form-control border-0 bg-light">
<div class="input-group-append">
<button id="button-addon1" type="submit" class="btn btn-link text-primary"><strong><i class="bi bi-search"></i></strong></button>
</div>
</div>
</div>
<form class="col-lg-8"name="get_Song" action="<?php echo $_SERVER['PHP_SELF'] ?>?page=listsong" method="POST" enctype="multipart/form-data">
<div class="form-row mb-4 align-items-center">
<!-- <label class="fs-5 fw-bold text-secondary mr-0" for="inlineFormInput">Page No</label>-->
<div class="col-sm-4">
<input type="number" class="form-control form-control-lg mb-2 border-0" name="PageNo" id="PageNoid" placeholder="Page No">
</div>
<!-- <label class="fs-5 fw-bold text-secondary mr-0" for="inlineFormInputGroup">Page Size</label> -->
<div class="col-sm-4">
<input type="number" class="form-control form-control-lg mb-2 border-0" name="PageSize" id="Pagesizeid" placeholder="Page Size">
</div>
<div class="col-sm-3 text-center">
<input type="submit" class="btn btn-info mb-2 form-control-lg fs-5 fw-bold" id="ResetId" name="reset" value="Reset" />
</div>
</div>
</form>
<div class="table-responsive custom-table-responsive">
<table class="table custom-table">
<thead>
<tr>
<th scope="col">
<label class="control control--checkbox">
<input type="checkbox" class="js-check-all" />
<div class="control__indicator"></div>
</label>
</th class="">
<th scope="col">SongId</th>
<th scope="col">Lastname</th>
<th scope="col">Length</th>
<th scope="col">Picture</th>
<th scope="col">UrlSong</th>
</tr>
</thead>
<tbody>
<?php
$pageNo = 1;
$pageS = 4;
if (!empty($_POST['reset'])) {
$pageNo = $_POST['PageNo'];
$pageS = $_POST['PageSize'];
}
$getdb = new Song();
$arr = $getdb->getAllRecords($pageNo, $pageS, $totalRecords);
// $strTbl = "";
//
// $stt = 1;
for ($i = 0; $i < count($arr); $i++) {
$obj = $arr[$i];
?>
<tr scope='row'>
<th scope="row">
<label class="control control--checkbox">
<input type="checkbox" />
<div class="control__indicator"></div>
</label>
</th>
<td> <?php echo $obj->songId ?></td>
<td> <?php echo $obj->lastname ?></td>
<td> <?php echo $obj->length ?></td>
<td> <?php echo $obj->picture ?></td>
<td> <?php echo $obj->urlSong ?></td>
<td>
<div style='display:flex;'>
<a href="Admin.php?page=addsong&id=<?php echo $obj->songId; ?>" class='btn btn-info mr-1' id='updatef'><i class='i bi-arrow-repeat'></i></a>
<a href="../backend/delete/delsong.php?id=<?php echo $obj->songId; ?>" class='btn btn-danger mr-1' id='deletef'><i class='bi bi-trash'></i></a>
</div>
</td>
</tr>
<tr class="spacer"><td colspan="100"></td> </tr>
<?php } ?>
</tbody>
</table>
<?php
if (!empty($_POST['reset'])) {
echo "Page : " . $pageNo . " " . "Size: " . $pageS;
}
;
?>
</div>
</div>
</div>
</div>
</div>
I want to display multiple tables from the database with these code, but it did not work, it only showed the blank page without any errors when i click the button. I tried to change the sql to echo test and it worked, so i think the problem in my code is that i did not use the right sql statement.Please help me with this, thank you very much.
I can see a couple of problems.
First, in index.php you're calling an instance method, rather than a static method. Instead of
$getdb = new Song();
$arr = $getdb->getAllRecords($pageNo, $pageS, $totalRecords);
You should use
$arr = Song::getAllRecords($pageNo, $pageS, $totalRecords);
... but that's not what's causing your error.
In your class definition, you have
$song = new GetAllSong();
but I think it should be
$song = new Song();
Also although I can't see an error with your SQL, I'm not sure why you're using a nested query. It might be easier and more peformant to use a simple SQL statement?
Edit: Also you have an SQL injection vulnerability. You're taking whatever someone has POSTed and passing it directly into your SQL statement. If someone crafts a malicious POST request to your web page they could perform whatever SQL they wanted to on your database.

MySQL on PHP need 2 reloads to update the values

I made a message deleter button, but I need 2 reloads to appear the changes...
(The rest of the code work, so it's normal that I don't show you the rest of the code...)
<?php while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST"><button name="delete<?= $r['id'] ?>">Test</button></form>
<?php
$test = "delete".$r['id'];
if(isset($_POST[$test])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($r['id']));
$success = "Your message was successfully removed !";
}
?>
</div>
</div>
<br>
<?php } ?>
UPDATE:
I added the deleting code at the top of my php code, and it's working, thanks to Ray Andison
By the way thanks to keidakida too; he helped me to find a solution to my value problem. (And I think he don't know that)
Your form doesn't contain any data (the id to be deleted) or action (page to submit data to)?
<form method="POST" action="thispage.php">
<input id="test" name="test" type="hidden" value="<?= $r['id'] ?>">
<input type="submit">
</form>
UPDATED:
<?
if(isset($_POST[id])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST[id]));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()){
echo '
<div class="message" id="'.$r[id].'">
<div class="profile">
<img class="avatar" src="members/avatars/';
if(empty(get_avatar($r[id_author]))){
echo "default.png";
}else{
echo get_avatar($r[id_author]);
}
echo '
" width="150" height="150">
<h3 style="text-align:center;">
'.get_username($r[id_author]).'
</h3>
</div>
<div class="content">
<div class="date">
'.date('d F Y - g:iA', strtotime($r[date_hour_post])).'
</div>
<br>
<br>
'.htmlspecialchars_decode($r[content]).'
<form method="POST" action="thispage.php">
<input id="id" name="id" type="hidden" value="'.$r[id].'">
<input type="submit">
</form>
</div>
</div>';
}
?>
This is how I would code this, you need to change the action="thispage.php" to be the name of itself so it posts to itself, replace with the actual name of your php file
It is because the delete PHP code is at the bottom. Actions such as delete should be at the top of the HTML or while loops before presenting the data. SO try this:
<?php
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST">
<button type="button" name="delete" value="<?php echo $r['id']; ?>">Test</button>
</form>
</div>
</div>
<br>
<?php
}
?>
But you can do the same functionality without any page reload. Check AJAX PHP
Since it would be better and easier with AJAX, this is how it goes:
main.php
<?php
while ($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<?php echo htmlspecialchars_decode($r['content']) ?>
<button onclick="delete('<?php echo $r['id']; ?>')">Delete</button>
</div>
<br>
<?php } ?>
<script>
function delete(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Delete successfully");
location.reload();
}
};
xmlhttp.open("POST", "delete.php", true);
// Mandatory for simple POST request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send id you want to delete
xmlhttp.send("id=" + id);
}
</script>
And make another PHP file name is delete.php like this:
<?php
include 'YOUR_DB_Connect.php';
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
}
?>

How do i post a $_GET variable value using a REQUEST METHOD

I am trying to post a $_GET value so it cant insert the variable value into the database using $_SERVER["REQUEST_METHOD"].
<?php require_once("../includes/initialize.php"); ?>
<?php include("../includes/form_validation_card.php"); ?>
<?php $username = $_SESSION['username']; ?>
<?php
if(!isset($_GET['total']) && !isset($_GET['order_id'])){
redirect_to('order_summary.php');
}
$total = $_GET['total'];
$order = $_GET['order_id'];
?>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
?>
<?php include_layout_template('header2.php'); ?>
<div class="container">
<div class="row">
<br/><br/><?php echo output_message($message); ?>
</div>
<div class="row ">
<div class="jumbo jumbotron-fluid mx-auto d-block" style="height: 500px; width: 440px; background-color:#DCDCDC; border-radius: 5px;" >
<div class="text-center" style="margin: 3px;"><img src="logo/eden_petshop_logo.png" width="32" height="32"/><?php echo $found_user['first_name']; ?> <?php echo $found_user['last_name']; ?></div>
<p class="text-center">order id: #<?php echo $order; ?></p>
<h4 class="display-4 lead text-center">N<?php echo $total; ?></h4>
<div class="col-sm-6 col-sm-offset-3 mx-auto d-block">
<?php echo output_message($message); ?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post" class="form-horizontal">
<div class="form-group">
<div class="col">
<input type="text" name="card_number" onchange="trim(this)" placeholder="Card Number" class="form-control" id="card_number"/>
<span style="color: #EA4335"><?= $card_number_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<input type="text" name="mm_yy" class="form-control" onchange="trim(this)" placeholder="MM/YY">
<span style="color: #EA4335"><?= $mm_yy_error; ?></span>
</div>
<div class="col">
<input type="password" name="cvv" class="form-control" onchange="trim(this)" placeholder="CVV">
<span style="color: #EA4335"><?= $cvv_error; ?></span>
</div>
</div>
</div>
<div class="col-sm-12 col-sm-push-3">
<button type="submit" name="submit" value="Pay" class="btn bg-info btn-sm btn-block" onClick="return confirm('Are you sure your details are correct?');">Pay</button>
</div>
</form>
</div>
</div>
</div>
<?php include_layout_template('footer2.php'); ?>
This is the input display page but i am trying to the $total and $order $_GET variables insert into the database... Please note that every other part of the code assignment is working fine.
<?php
//define variables and set them to empty values
$total_error = $order_error = $card_number_error = $mm_yy_error = $cvv_error = "";
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
//form is submitted with post method
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["card_number"])){
$card_number_error = "<div class=''>Card number is required</div>";
}else{
$card_number = test_input($_POST["card_number"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{16,}$/",$card_number)){
$card_number_error = "<div>Only 16 numbers allowed</div>";
}
}
if(empty($_POST["mm_yy"])){
$mm_yy_error = "<div class=''>Card expiry is required</div>";
}else{
$mm_yy = test_input($_POST["mm_yy"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$mm_yy)){
$mm_yy_error = "<div class=''>Only numbers allowed</div>";
}
}
if(empty($_POST["cvv"])){
$cvv_error = "<div class=''>Card verification is required</div>";
}else {
$cvv = test_input($_POST["cvv"]);
//check if username is atleast 7 characters
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$cvv)){
$cvv_error = "<div class=''>Card verification must not be more than 3 numbers</div>";
}
}
if($card_number_error == "" && $mm_yy_error == "" && $cvv_error == ""){
$token = 'vfjhvbkebecbjDRCWVJEcbkrvlnke24tir7c_zdvbejw968350124';
$token = str_shuffle($token);
$token = substr($token, 0, 15);
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
$email = $found_user['email_address'];
$pay = new Payment();
$pay->username = $username;
$pay->order_id = $order;
$pay->total = $total;
$pay->card_number = $card_number;
$pay->expiry = $mm_yy;
$pay->cvv = $cvv;
$pay->transaction_id = $token;
$pay->status = 0;
$pay->created_at = $timestamp;
if($pay->save()){
//$mail = new Mail();
//$mail->email_address = $email_address;
//$mail->send_transaction_confirmation();
unset($_SESSION['shopping_cart']);
$session->message('<div class="btn bg-success">Congratulations!!! Your order has been processed.</div>');
redirect_to('photos.php');
}
}
if(empty($_POST["message"])){
$message = "";
} else{
$message = test_input($_POST["message"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
?>
Please note that my $order and total are not getting inserted into my database... Any assistance on my preg_match would be appreciated... Thanks in advance.
You need to use $_POST in your broken code instead of $_GET. Notice your working code used $_POST instead, which is why it works.

Getting a select option instead of different buttons php class

Im trying to get a select between the different sizes of the product. I made a script which echos a button for every size but how can i do this with a select form?
In the DB the product has a master and every size is an option.
To get the product im using ($_GET['add']) to get the product on the cart page.
At the last past im giving the wagen.html?add='.$s['id'] so i can use that id in the cart.
class ProductDisplay {
public function display($content){
global $db, $properties, $cms, $adb;
$content = unserialize($content);
$itm = $adb->queryrow("SELECT * FROM products WHERE id=? LIMIT 1", array(intval($content['wlpid'])));
$vat = $adb->querykeyvalues("SELECT id, multiplier FROM tax");
$prijs = (($itm['price']*($vat[$itm['tax']]/100))/100);
$subs = $adb->queryarray("SELECT *, (SELECT value FROM propertyvarchar WHERE lang=1 AND propid=1 AND product=p.id lIMIT 1) as name, (SELECT value FROM propertyvarchar WHERE lang=1 AND propid=5 AND product=p.id lIMIT 1) as opt FROM products p WHERE master=?", array($itm['id']));
echo '
<div id="the_product_container" class="para_container"></div>
<div id="anchor_1_product"></div>
<div id="anchor_2_product"></div>
<div id="anchor_3_product"></div>
<div id="page_product" class="anchor_pos"></div>
<div id="page_product_check" class="anchor_check"></div>
<div class="bonds">
<div class="scaleme">
<img alt="shirt" class="content" src="/uploaded/overige/'.$content['main'].'">';
$ar = array(
1=>"point_one",
2=>"point_two",
3=>"point_tree",
4=>"point_four",
5=>"point_five",
);
for($i=1; $i<=3; $i++)
{
if(!empty($content['info'.$i]))
echo '<img alt="Product point" id="'.$ar[$i].'" class="'.$ar[$i].'" src="/uploaded/overige/'.$content['info'.$i].'">';
}
echo '</div>
</div>
<div class="mobiel_text_con">';
for($i=1; $i<=3; $i++)
{
if(!empty($content['info'.$i]))
echo '<div class="text_block">
<h3>'.$content['info'.$i.'h'].'</h3>
<hr />
<p>
'.$content['info'.$i.'t'].'
</p>
</div>';
}
echo '</div>';
if(empty($subs))
{
echo '<div class="pricetag">
<p>'.number_format($prijs,2,',','.').' €</p>
</div>
<div class="button_holder_ordernow">
<a title="Order Now" href="/winkelwagen.html?add='.$itm['id'].'" class="sumbit_button">order now</a>
</div>
<div class="photo_overlay_filter2"></div>';
}
else
{
echo '<div style="display:inline-block; text-align:center; width:100%;">
<div class="pricetag">
<p>'.$itm['name'].' ('.$itm['opt'].') '.number_format($prijs,2,',','.').' €</p>
</div>
<div style="display:inline-block;">
<div class="button_holder_ordernow" style=" padding-bottom:20px;">
<a title="Order Now" href="/winkelwagen.html?add='.$itm['id'].'" class="sumbit_button">order now</a>
</div>
</div>
</div>
<div class="photo_overlay_filter2"></div>';
foreach($subs as $s)
{
$prijs = (($s['fromprice']*($vat[$s['tax']]/100))/100);
echo '<div style="display:inline-block; text-align:center; width:100%;">
<div class="pricetag">
<p>'.$itm['name'].' ('.$s['opt'].') '.number_format($prijs,2,',','.').' €</p>
</div>
<div style="display:inline-block;">
<div class="button_holder_ordernow" style=" padding-bottom:20px;">
<a title="Order Now" href="/winkelwagen.html?add='.$s['id'].'" class="sumbit_button">order now</a>
</div>
</div>
</div>
<div class="photo_overlay_filter2"></div>';
}
echo '<br /><br /><br /><br />';
}
}
}
?>

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