Setting a select option default to a previously set option - php

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>).

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>

change of drop down in php my sql Dynamically

I have two drop downs .one have static value and second get values from db. I want to that if value is selected from 1st drop down then relevant values loaded in 2nd drop down. I have tried. but its load all the data from database according to user.for example when user select from request type dropdown having value inquiry.then 2nd drop down load only the values which have catType Inquiry.and if he select the complaint then complaint data must be shown.I have been tried but all the data is loaded ,or only one data is loading.any body help me in this regard.Thanks in Advance. Here is My Code
<div class="col-md-4">
<div class="form-group">
<label for="requesttype"><?php echo $requestField; ?></label>
<select class="form-control" required="" id="requesttype" name="requesttype" onchange="fcrActionChange(this);">
<option value="">Select Request Type</option>
<option value="Inquiry">Inquiry</option>
<option value="Complaint">Complaint</option>
<option value="Service Request/FCR">Service Request/FCR</option>
<option value="Verification Call">Verification Call</option>
</select>
<span class="help-block"><?php echo $requestHelp; ?></span>
</div>
</div>
$("#requesttype").change(function() {
$("#catId).load("navigation.php?requesttype=" + $("#requesttype").val());
});
</script>
<div class="col-md-4">
<div class="form-group">
<label for="catId"><?php echo $categoryField; ?></label>
<select class="form-control" name="catId" id="catId">
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 AND catType = ".$_GET['requesttype'];
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
while ($tcatrow = mysqli_fetch_assoc($rest)) {
echo "<option value="$tcatrow['catId'] >";
echo clean($tcatrow['catName'])."</option>";
}
</select>
<span class="help-block"><?php echo $categoryHelp; ?></span>
</div>
</div>
</div>
Your code is pretty confusing but anyway, the important part is within your ajax request and your PHP file
Ex. you have a div id secondOpt to be filled from the query made by the requesttype.
**Note I added a userId input field to pass the value for the SQL query in the navigation.php
<select class="form-control" required="" id="requesttype" name="requesttype" onchange="fcrActionChange(this);">
<option value="">Select Request Type</option>
<option value="Inquiry">Inquiry</option>
<option value="Complaint">Complaint</option>
<option value="Service Request/FCR">Service Request/FCR</option>
<option value="Verification Call">Verification Call</option>
</select>
<input type="hidden" id="userId" value="<?php echo $userId;?>">
<div id="secondOpt"></div>
After this, you will have an ajax request below, you can use $.post from jQuery and render the returned data on the secondOpt element
$('#requesttype').change(function(){
$.post("navigation.php",{requesttype: $(this).val(),userId: $('#userId').val()},function(options)
{
$('#secondOpt').html(options);
});
});
And for the navigation.php UPDATED
//don't forget your config file here to connect with the database
$userId = mysql_real_escape_string($_POST['userId']);
$requesttype = mysql_real_escape_string($_POST['requesttype']);
$output = "<select id='catId'>";
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 AND catType = ".$requesttype;
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
while ($tcatrow = mysqli_fetch_assoc($rest)) {
$output.="<option value=".$tcatrow['catId']." >";
$output.=clean($tcatrow['catName'])."</option>";
}
$output.="</select>";
echo $output;

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.

Why am I unable to access form data when submitting using OnChange?

I have a simple HTML select option in which it should automatically send OnChange. The form seems to send or "Reload the page" should I say. I am not getting ANY data the other end. I have tried POST and GET I have renamed every section of the forms data and changed the entire if(isset() information. Any ideas why I am not getting any data?
FORM:
<?php
$system1 = mysqli_fetch_assoc(mysqli_query($conn,
"SELECT * FROM ap_system_status WHERE system_id = '1'"));
$system_id_1 = $system1['system_id'];
$system_name_1 = $system1['system_name'];
$system_status_1 = $system1['system_status'];
?>
<strong><? echo $system_name_1; ?></strong>
<div align="right" style="float:right">
<div class="form-group">
<form action="" method="GET" id="system_status" name="system_status">
<input type="hidden" id="system_id" value="<? echo $system_id_1; ?>" />
<select class="form-control" onchange="this.form.submit()" id="status">
<option disabled="disabled" selected="selected" hidden="hidden"><? echo $system_status_1; ?></option>
<option value='<i class="fa fa-exclamation-triangle" style="color:#F60"></i> Experiencing Errors'>Experiencing Errors</option>
<option value='<i class="fa fa-exclamation-triangle" style="color:#F60"></i> Being Updated'>Being Updated</option>
<option value='<i class="fa fa-exclamation-triangle" style="color:#F60"></i> Maintenance Mode'>Maintenance Mode</option>
<option value='<i class="fa fa-times-circle-o" style="color:#F00"></i> System Offline'>System Offline</option>
<option value='<i class="fa fa-check-circle-o" style="color:#090"></i> Good Service'>Good Service</option>
</select>
<noscript><input type="submit" value="Submit"></noscript>
</form>
DATA COLLECTION (Very basic but only testing!!):
<?php
if(isset($_POST['system_status'])){
$system_id = $_POST['system_id'];
$status = $_POST['status'];
echo $system_id;
echo $status;
}else{
}
?>
A couple of changes to your form and PHP should get this working. In order for the form elements to be submitted with the form, they must have name attributes, and the form method must match the superglobal ($_GET or $_POST) you are accessing in PHP.
<!--Change the form method to match what you are using in your PHP-->
<form action="" method="POST" id="system_status" name="system_status">
<!--Add a name to this input-->
<input type="hidden" id="system_id" value="<? echo $system_id_1; ?>" name="system_id" />
<!--Add a name to this select-->
<select class="form-control" onchange="this.form.submit()" id="status" name="status">
<option disabled="disabled" selected="selected" hidden="hidden"><? echo $system_status_1; ?></option>
<!--Not related to your question, but switch the value attribute with the
option text so you can see your icons and get the value I assume you expect-->
<option value="Experiencing Errors"><i class="fa fa-exclamation-triangle" style="color:#F60"></i> Experiencing Errors</option>
...
</select>
<noscript><input type="submit" value="Submit"></noscript>
I would actually not recommend getting rid of the isset check altogether, but modifying it so that it actually verifies that the values you are going to use are present.
<?php
if (!empty($_POST['system_id']) && !empty($_POST['status'])) {
$system_id = $_POST['system_id'];
$status = $_POST['status'];
echo $system_id;
echo $status;
} else {
// error handling for missing values
}

Sorting Using 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.

Categories