Country and state field in form - php

I have two select fields(country and state) in "My Account" form for user which are auto populated with countries and state list from countries.js. This works fine
But whenever user opens his account details(like amazon) I want the respective fields to be populated with current values from database (since these are active input fields user can also change the values). I am doing this by echoing values in input field like(see code below)
<input type="text" class="form-control" id="tgender" name="tgender" value="<?php echo "$trainer_gender"?>" >
nter code here
But this doesn't work for country and state. If I am echoing the values in country and state field then dropdown of countries doesn't work(if user wants to change or for first time user)

Values of select boxes are set different compared to text input fields.
What you are searching for is the selected attribute of the <option> tag (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option).
Wherever you build your selection box for the country/state, you need to iterate over that list, and check if the current iteration value matches the one from the database.
For example:
<select name="state">
<option value=''>SELECT</option>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$result = mysqli_query($conn, 'SELECT id, name FROM states');
while ($row = mysqli_fetch_assoc($result))
{
$selected = ($stateFromDB == $row['name']) ? 'selected' : '';
echo "<option value='$row[id]' $selected >$row[name]</option>";
}
?>
</select>
You can also select the correct value via Javascript, e.g. by using jQuery:
$("#state-list").val("Your State from DB");

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.

how to set variable to default selection on select statement and also list choice from an array

Im currently using a select statement for a dropdown box to select from multiple products. On an edit form i want the select to automatically select the choice that was originally chosen which is stored in the variable $product. Im using an array to bring in all choices from the database table however can't get the array to work aswell as select the data stored in $product.
The code i've currently got is;
$selectquery = "SELECT * FROM `loanproducts`";
$selectresult = mysqli_query($connection, $selectquery);
<select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult)):;?>
<option><?php echo $row1[1];?></option>
<?php endwhile;?>
</select></p></div>
Im not sure if I've explained what im trying to do well enough as it is confusing me even trying to explain.
-Basically for example I have 3 choices from the array- A, B & C.
-If the user goes through the form and selects B, when I then go to edit their choices I want their option to appear in the select box (B) - rather than the first choice on the array which would presumably be A
Thanks
I changed a little your programming style which is not very confortable to me. Anyway, the important thing here is that I create the variable $selected with two possible values : "" or "selected", depending if the current product ($row1[1]) is equal to the product selected ($product). All options but one will get "", only the selected product will get "selected" :
<select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult))
{ if ( $row1[1] == $product ) // IF CURRENT PRODUCT WAS SELECTED
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}
?>
</select></p></div>

Save result from dropdown list to another table

I have two tables in my database. I have a form to add information to table news. In my form I have dropdown list with information from another table courses. I want to save the result of the selection and save it in table news. How I can do that?
code:
<p>Course</p>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("university");
$sql = "SELECT name FROM courses";
$result = mysql_query($sql);
print '<select>';
while ($row = mysql_fetch_assoc($result)) {
print '<option value='.$row['name'].'>'.$row['name'].'</option>';
}
print '</select>';
?>
First you would need to give a nameattribute to your select tag, then as soon as you post your form, you will get the value of the selected option the exact same way as you get the value of other input fields.
I would also advise to get both the id and the name of your courses from your selct query. You should then use the id as the value attribute of your option , qhile you can keep the name to display it to the user. That way you would store the id of the selected course instead of the name, meaning that if a name slightly changes, you will still have the proper course id stored.
So your final HTML for this field should look something like that :
<select name="selectedcourse">
<option value="1">Course 1</option>
<option value="2">Course 2</option>
<option value="3">Course 3</option>
</select>
And you would get the seleted value server-side in PHP using something like :
$_POST["selectedcourse"]
If, of course, your form method was POST and not GET...

Categories