filling in value of drop down selection using php - php

I have a drop down menu that the user can select a location from. These are saved settings, so if the user wants to edit these settings I'd like for the previously saved value to populate the list.
The location and it's ID are selected from a table named locations, however, only the location is saved in a table named userinfo. I'm not sure how to go about populating the selection list again considering the id is used in the selection process the first time around.
This is what i have right now to simply select a loation. I'd like for this to fill in with a previously saved location. This is part of a larger form, hence no form tags.
<?
$sql = mysql_query("select locationsid,locationsName from locations");
$selection="";
while ($row=mysql_fetch_array($sql)){
$id=$row["locationsid"];
$locationName = $row["locationsName"];
$selection.="<OPTION VALUE=\"$id\">".$locationName;
}
?>
<!--select location - used for reach location -->
<h4>Nearest Location</h4>
<table>
<tr><td>Location:</td><td><select name ="location"><Option value="<? echo selection2; ?>">Choose Location<? echo $selection; ?></Select></td>
</table>
I'm assuming I'd have to query the database to get the saved location (in userinfo table), then look up the ID for that location from the the locations table. From here, I'm not quite sure how to fill this into the value selection field.
$locationLookup = mysql_query("select location from userinfo where userid = $userid");
$locationLookup = mysql_fetch_array($locationLookup);
$location = $locationLookup['location'];
$idlookup = mysql_query("select locationsID from locations where locationsName = '$location'");
$idlookup = mysql_fetch_array($locationid);
$idlookup = $locationid['locationsID'];
So, this would give me the name and ID, how can I set this as the value in the selection list?

After you get $idlookup:
$idlookup = $locationid['locationsID'];
use it inside while loop:
while ($row=mysql_fetch_array($sql)){
$id=$row["locationsid"];
$locationName = $row["locationsName"];
$selected = ($id == $idlookup) ? 'selected="selected"' : '';
$selection.="<OPTION " . $selected . " VALUE=\"$id\">".$locationName."</OPTION>";
}

Related

PHP Edit form for MySQL database <option> value is not correct after a fetch

I have a Edit form in php and everything work great. The only issue i have is when i click edit it returns all the data except in the Select drop down. it does not have the chosen category it always shows the first value in the list. But i then can click on the drop down and choose a new category and it works.
//Query the category table
$resultSet = $con->query("SELECT * FROM schedule_category");
<select id="schedule_category" name="schedule_category" class="custom-select">
<?php
while($rows = mysqli_fetch_assoc($resultSet))
{
?>
<option value = "<?php echo($rows['schedule_category'])?>">
<?php echo($rows['schedule_category']) ?>
</option>
<?php
}
?>
</select>
I would like to have it show the correct select option record not the first one in the drop down list. Here is an image of what happens https://imgur.com/a/XVXQ2Sa
You'll need to have your code compare each to the selected value, and add the appropriate keyword:
$previous_selection = // whatever it is, from your data
while($rows = mysqli_fetch_assoc($resultSet))
{
$thisone = $previous_selection == $rows['schedule_category'] ? " selected " : "";
echo '<option value = "';
echo ($rows['schedule_category']) . '"' . $thisone . '>';
echo($rows['schedule_category']) . '</option>';
}
What you're doing here is comparing your previously-selected value to each row, when it matches, the variable $thisone is set to "selected", otherwise it's empty. You then add that to each option line after the value and before the close-tag for the option, and it will add "selected" when the value matches.
Also I personally don't like switching in and out of PHP for no good reason, makes it really difficult to read, hence I echo the various bits of HTML here.
ETA - actually that could be simplified further, if your selection value is the same as the text displayed in the list, there's no need to actually specify the value in the option tag. That is only required when the value is different to the display, for example if you want the user to see your category names, but you want to submit the category ID.

Set the default value of a dynamic select drop down list in php

I have a form in an edititem.php page that is used to edit an item. The idea is that from another page, the searchitem.php a user can click edit and is taken to the edititem.php page to edit the selected item. What I'm trying to do is that automatically the default values in the form elements are populated with the values of the item selected to edit (from the searchitem.php) so that the user finds the form populated and only needs to modify the necessary value/s.
I'm passing all the required variables to the edititem.php and I am able to poulate all the input tags but I have a problem with the select tag which is not being set with the desired value. The select tag is being populated dynamically from a mysql database.
<label>Category:</label>
<select name="category">
<?php
$selectedCategory = '';
if (isset($_POST['category'])) {
$selectedCategory = $_POST['category'];
}
$sql_cat = "SELECT id, description FROM category ORDER BY description ASC";
$result_cat = mysqli_query($connection, $sql_cat);
if(mysqli_num_rows($result_cat) > 0){
while($row = mysqli_fetch_assoc($result_cat)){
$selected = '';
if ($selectedCategory == $row['id']) {
$selected = 'selected';
}
echo '<option value="' . htmlspecialchars($row['id']) . '" '.$selected.'>'
. htmlspecialchars($row['description'])
. '</option>';
}
}
?>
With the above code the items in the select tag are being populated dynamically from a table and also if the page is refreshed the selected item is maintained as the selected value.
However I cannot set the default value when I press the edit item from the searchitem.php. The last value in the table is being displayed as default. Any ideas how I can achieve this since I cannot figure out how to do it. Note that all the variables are being passed successfully to the edititem.php page I just need to set the default value of the select drop down list as per the passed variable while keeping the select drop down list dynamic.

HTML php preselected option value loaded in dropdown

I'm struggling with something simple, I found a similar question on Stack but I couldn't make the solution work.
I have a html/php form to edit user's details. Because it is editing already existing information, a dropdown needs to pre-load a user's organisation from the mysql database. Because of db normalisation I put the organisation details in a separate table to the users table, so the user's record just holds their organisation's id.
The code fetches the user's info and populates the form for editing, but I can't get the organisation dropdown to display the user's organisation. I need it to have pre-selected the user's organisation (if applicable), but still have the list of options to alter it.
<td align="right">Organisation:</td>
<td>
<select name="user_org">
<option>Select the organisation</option>
<?php
//query to get the organisations from the db
$get_org = "SELECT * FROM organisations";
$run_org = mysqli_query($con, $get_org);
while ($row_org=mysqli_fetch_array($run_org)){
$org_id = $row_org['org_id'];
$org_name = $row_org['org_name'];
echo "<option value='$org_id';>$org_name</option>";
}?>
</select>
You can pick an option to be the selected one by default with the "selected" attribute. In your situation, you can just check within the loop whether or not the current organization is the user's one. And add the "selected" attribute when it is.
For example, let's say your user's organization id is stored in a variable user_org.
while ($row_org=mysqli_fetch_array($run_org)){
$org_id = $row_org['org_id'];
$org_name = $row_org['org_name'];
echo "<option value='$org_id'";
if($org_id === $user_org) echo " selected";
echo ">$org_name</option>" . PHP_EOL;
}?>
Then, if an organization has an id that matches the user's one, the option will be selected by default.
Try something like this:
while ($row_org=mysqli_fetch_array($run_org))
{
$org_id = $row_org['org_id'];
$org_name = $row_org['org_name'];
$selected = '';
if( $org_id == $already_selected_value )
{
$selected = 'selected="selected"';
}
echo <option value="'.$org_id.'" '.$selected.'>'.$org_name.'</option>';
}
Explanation: Initially $selected is blank but when condition becomes true, its value set the selected attribute of option to make that option default selected.

populate select box with data from mysqltable

How to populate select box with data from mysql table, and then move that value from one page to another.
I did a small coding, and i was able to get all the values from table, but i cant move those value to other page.
$query1="SELECT * FROM seat_no WHERE seatno NOT IN(SELECT seatno FROM check_in_desk)";
$result1 = mysql_query($query1);
<select name="txt_seatno">
<?php
while($nt=mysql_fetch_array($result1))
{
echo "<option value=$nt[id]>$nt[seatno]</option>";
}
</select>
?>
Can you just lookup the values on the page where you need them? If not, you could pass the data as a GET or POST variable, and then use this to generate the select box options on the new page.
There's two ways I can think of;
1) append the value to the url, so it'd be;
echo '' . $nt[seatno] . '';
and in the receiving page, you'd put;
$id = (int) $_GET['id'];
2) Or you could simply use this;
http://www.w3schools.com/html/tryit.asp?filename=tryhtml_select2
(dropdown menu)
(btw; your < /select> should come after ?>)

How to check a check box if it's value is in DATABASE. PHP

I have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.

Categories