Sorting Using PHP - php

I am a php novice so please be kind.... Need to sort date, after location has been selected.
<div id="enroll_now">
<form name="enroll" id="enroll" method="post" action="<?php echo get_permalink(762); ?>">
<p>
<label >Class Title</label>
<input type="text" name="class_title" value="<?php echo $title;?>">
</input>
</p>
<p>
<label>Choose Location</label>
<select name="location" id="location" >
<option selected="selected" value="0">--Select Location--</option>
<?php
$result = mysql_query("SELECT * from wp_location WHERE class_id=$page_id ORDER BY location ASC");
while($row = mysql_fetch_array($result))
{
echo "<option value=".$row['id'].">".$row['location']."</option>";
}
?>
</select>
</p>
<p>
<label>Choose Date</label>
<select name="choose_date" id="choose_date">
<?php
if (isset($datesavailable) && is_array($datesavailable)) {
foreach($datesavailable as $val)
{
echo' <option value="'.$val.'">'.$val.'</option>\n';
}
}
?>
</select>
</p>
<p>
<input type="image" src="<?php bloginfo('template_url'); ?>/images/confirm.png" alt="Confirm Information" />
</p>
</form>
</div>
The locations sorts fine, but then when I get to the date, I need them to sort by closest date first. Any help would be appricated. Thanks.

Use ORDER BY somecolumn in your query; http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html

If the dates are just an array, you can use asort or arsort.
http://php.net/manual/en/function.asort.php

I examined your page and see that you're sending a POST (id & location) when the event change is triggered in your combo. My suggestion is to query the database like this
SELECT * from wp_location WHERE class_id=$_POST['id'] AND location=$_POST['location'] ORDER BY date
I'm assuming date field in your database is DATE, DATETIME or TIMESTAMP type.

Related

How to maintain the PHP GET value on the address bar if I use another GET?

I am passing a variable from page1 to page2 using GET and it's already working. However, I also use another get in the <select> <option> on page2 which means when I click an item in the option, the value I get from page1 disappears and becomes undefined since the address bar changes. I want the variable I get from page1 to be compared on SQL where clause. I can't think of a way on how to solve this, I'm not really knowledgeable in PHP, can you help me?
Here is my code(I remove some unnecessary lines): page1
<form method="get" action="home.php">
<div class="form-group">
<input id="codehe" class="form-control" type="codehe" name="codehe" placeholder="Class Code">
</div>
<div class="form-group">
<input class="form-control button" type="submit">
</div>
</form>
page2 (this is how i get the value from page1)
<?php
$codehe = $_POST['codehe'];
echo $codehe;
?>
The other GET (form) on page2
<form method="GET">
<select id="state" multiple name="state" onchange='if(this.value != 0) { this.form.submit(); }'>
<option value="ALL">ALL</option>
<option value="<?php echo $row['subjects'];?>"><?php echo $row['subjects'];?></option>
</select>
</form>
<?php
if(isset($_GET['state'])) {
$str = $_GET["state"];
$sql = "SELECT * FROM classvideo WHERE subjects = '$str' AND linkcode = ''";
?>
The traditional way to do things like this (without client-side code) is to put a hidden input in your form on page 2:
<form method="GET">
<select id="state" multiple name="state" onchange='if(this.value != 0) { this.form.submit(); }'>
<option value="ALL">ALL</option>
<option value="<?php echo $row['subjects'];?>"><?php echo $row['subjects'];?></option>
</select>
<!-- Add this line -->
<input type="hidden" name="codehe" value="<?php echo $_GET['codehe'] %>">
</form>

Setting a select option default to a previously set option

In my modal window, I have a select where a user can select a breakfast meal from my database. By selecting a meal and submitting it, a record is saved in the database. However, I would like to achieve that when the user enters into the same modal window, whatever meal they have selected before hand will appear as the default option. I have created a query that checks to see if a meal has already been selected (optionquery1). Any ideas to achieve this? Thanks
On a side note, I'm not sure that I'm setting the date php variable currently. The day, month and year is stored in the html hidden inputs but not sure how to extract the values.
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<div class="modal-body">
<form action="my_planner.php" method="post">
<!--<span class="test5"></span>-->
<!--<span class="test"><input type="text" name="id_disabled" value="" disabled/>-->
<input class="test" type="text" name="id1" value="" style="text-align:center; border:0px; font-weight:bold; font-size: 25px;"/>
<hr class="my-4">
<input type="hidden" name="id" value=""/>
<input type="hidden" name="month" value=""/>
<input type="hidden" name="year" value=""/>
<br>
<p id="breakfastTag"><br>Breakfast:</p>
<select id="breakfast" name="breakfast">
<option value="" disabled selected>Select your breakast</option>
<?
$meal='breakfast';
$date='<input type="hidden" name="id" value=""/>'.'<input type="hidden" name="month" value=""/>'.'<input type="hidden" name="year" value=""/>';
$query = $db->prepare("select * from recipe_category where categoryID=1");
$query->execute();
while ($results = $query->fetch()) {
$recipeID=$results["recipeID"];
$query3 = $db->prepare("select * from recipe where id=:recipeID");
$dbParams3=array('recipeID'=>$recipeID);
$query3->execute($dbParams3);
$breakfast = $query3->fetchAll();
$optionquery = $db->prepare("select * from user_planner where userID=:userID and date=:date and meal=:meal");
$optionParams= array ('userID'=>$thisUser, 'date'=>$date,'meal'=>$meal);
$optionquery->execute($optionParams);
while ($results12 = $optionquery->fetch()) {
$selectedmeal = $results12['recipeID'];
}
$optionquery1 = $db->prepare("select * from recipe where id=:recipeID");
$optionParams1= array ('recipeID'=>$selectedmeal);
$optionquery1->execute($optionParams1);
while ($results123 = $optionquery1->fetch()) {
$selectedrecipe = $results123['name'];
}
foreach($breakfast as $breakfast): ?>
<option value="<?= $breakfast['id']; ?>"><?= $breakfast['name']; ?></option>
<?php endforeach;} ?>
</select>
Of course you can, you need to use the selected attribute on the <option> you want to show.
First remove the selected attribute from the first <option>:
<option value="" disabled>Select your breakast</option>
Then in the foreach loop you need an if condition:
$results123 = $optionquery1->fetch();
$selectedrecipe = $results123['id'];
foreach($breakfast as $breakfast): ?>
<option value="<?= $breakfast['id']; ?>" <?php if ($breakfast['id'] == $selectedrecipe) echo 'selected' ?>><?= $breakfast['name']; ?></option>
<?php endforeach;} ?>
Notice I have removed the while loop since we are sure Mysql will return only one record (WHERE ID = <ID>).

keep selected values in select box field after search

I want to keep the selected values in select box after search .This is a vehicle search filter page and Page is coded using php and connected with database.
Database have 2 columns for both options that is driver age for 21-24 and driver_age for 25+ as some vehicles also available for both age of drivers
code below
<script>
$('#driver').change(function() {
if($('#driver option:selected').val() == '21-24') {
$('#driver').attr('name','driverage');
}
if($('#driver option:selected').val() == '25+') {
$('#driver').attr('name','driver_age');
}
});
</script>
<form id="myform" method="GET" action="">
<div class="fields">
<p>Vehicle Type</p>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<?php if(count($vehicleType) > 0 ){
foreach($vehicleType as $vt){ ?>
<option value="<?php echo $vt ?>" <?=isset($_GET['car_type'])&&$_GET['car_type']==$vt?'selected':'';?> ><?php echo $vt ?></option>
<?php }
} ?>
</select>
</div>
<div class="fields">
<p>Age of Youngest Driver</p>
<select class="half" id="driver" name="">
<option value="21-24">21-24</option>
<option value="25+">25+</option>
</select>
</div>
<input type="hidden" name="search" />
<div class="fields" style="text-align:center">
<input type="submit" value="Search" class="mitsub" />
</div>
</form>
Thanks and please help
You can add a conditional statement inside your foreach() that adds selected attribute to option. This will ensure that the selected value is selected in the list of options.
<?php
if(count($vehicleType) > 0 ){
foreach($vehicleType as $vt){
echo "<option value='$vt'";
if(isset($_GET['car_type']) && $_GET['car_type'] == $vt){
echo " selected";
}
echo ">$vt</option>\r\n";
}
}
?>
You can do this all in one, you just have to make sure the logic is correct.
echo "<option value='$vt'" . ((isset($_GET['car_type'] && $_GET['car_type'] == $vt) ? " selected" : "") . ">$vt</option>\r\n";
I just find it easier to work with a full if statement.

select input type to use database fields

How would I utilise my code for a select input type to use data within a database? I've got a connection to my datebase that works fine it terms of writing data and also retrieving data to a text box etc. Yet to workout how it works for a select type though.
Im currently using :
<select name="product" width="100" style="width: 245px">
<option value="laptop">laptop</option>
<option value="keyboard">keyboard</option>
</select>
How could I change my code so that when a user selects the drop down menu from the select it lists all options from a specific row in my products table?
Updated code:
if(isset($_POST['product'])){
$choice = $_POST['product'];
}
$query="SELECT * from loanproducts WHERE product = '$choice'";
while($row = fetch_assoc($query)){
echo $row[product];
}
endwhile;
if (isset($_POST['addloan'])):
$username=$_SESSION['username'];
$product=$_POST['product'];
$date_collected=$_POST['date_collected'];
$date_return=$_POST['date_return'];
$returned=$_POST['returned'];
$my_query="INSERT INTO loans VALUES ('','$username','$product','$date_collected','$date_return','$returned')";
$result= mysqli_query($connection, $my_query);
if ($result):
header ('location: homepage.php?confirm=New loan successfully created');
else :
echo "<b>This didn`t work, error: </b>";
echo mysqli_error($connection);
endif;
endif;
HTML:
<form method=post action="addloan.php" enctype="multipart/form-data">
<input type="text" name="username" autocomplete="off" size="30" value="<? php echo $_SESSION['username']; ?>" disabled>
<br><br>
<select name="product" width="100" style="width: 245px">
<option value="" disabled selected>Product?</option>
<option value="laptop">laptop</option>
<option value="keyboard">keyboard</option>
</select>
<br><br>
<input type="date" name="date_collected" autocomplete="off" placeholder="Collection Date?" size="30">
<br><br>
<input type="date" name="date_return" autocomplete="off" placeholder="Return Date?" size="30">
<br><br>
<select name="returned" width="100" style="width: 245px">
<option value="" disabled selected>Returned?</option>
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<br><br>
<input type="submit" name="addloan" value="Create Loan" >
</form>
Given no code to work with (consult my "footnotes"), this is the logic you can use.
Use a WHERE clause from values pulled from a POST/GET array and name attribute(s).
HTML:
<form method="post" action="handler.php">
<select name="product" width="100" style="width: 245px">
<option value="laptop">laptop</option>
<option value="keyboard">keyboard</option>
</select>
<input type="submit" name="submit">
</form>
PHP:
if(isset($_POST['product'])){
$choice = $_POST['product'];
}
Query: N.B.: query() is an example here. Consult my "footnotes".
SELECT * FROM table where col_x = '$choice'
or actual columns:
$query = query($con, "SELECT col_1, col_2, col_3 FROM table where col_x = '$choice'");
Then you would loop over results; fetch_assoc() is an example here. Consult my "footnotes".
while($row = fetch_assoc($query)){
echo $row['col_1'] . " " . $row['col_2'] . " " . $row['col_3'];
}
Footnotes:
The API used to connect with is unknown, so you will need to escape that value and use the respective functions to connect/query with. As is the db schema being unknown.
You will need to adjust accordingly.

Form field changes focus when I click on the text input

I have a search form below that has two select input types and one text input field where the user can search by keywords. For some reason, whenever I click on keywords text box, the focus changes immediately back to the first select box drop down for Category and I so I can't type anything in the keywords text box. Can anyone see why this is happening?
$categories_list = array();
$ratings_list = array();
try {
$query = $dbh->query("SELECT category, genre, rating FROM posts WHERE 1
GROUP BY category, genre, rating");
$query->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($query);
foreach ($iterator as $row) {
if (empty($row['category']) == false && !in_array($row['category'],
$categories_list))
$categories_list[] = $row['category'];
if (empty($row['rating']) == false && !in_array($row['rating'],
$ratings_list))
$ratings_list[] = $row['rating'];
}
} catch (Exception $e) {
echo '<p>', $e->getMessage(), '</p>';
}
?>
<p> </p>
<p> </p>
<h2>Search Completed Stories</h2>
<form name="search" method="get"
action="http://example.com/searchB/">
<label>
Category:
<select name="category">
<?php foreach($categories_list as $category) : ?>
<option><?php echo $category; ?></option>
<?php endforeach; ?>
</select>
</label>
<label>
Rating:
<select name="rating">
<option value="">Any</option>
<?php foreach($ratings_list as $rating) : ?>
<option><?php echo $rating; ?></option>
<?php endforeach; ?>
</select>
</label>
<label>
Keywords:
<input type="text" name="keywords">
</label>
<input type="hidden" name="active" value="0">
<input type="submit"/>
It appears that I solved the problem by simply changing the label
tags to p tags instead. I guess that got around the conflict.

Categories