As I only have one value in the first dropdown, I am trying to create a cascading dropdown in PHP that populates the second dropdown on page load.
My database has a table called 'nights' with fields called: 'city', 'name' and 'day'.
To fill my first box I'm using SELECT DISTINCT cities from nights etc which has worked fine.
To fill the second box I need something along the lines of SELECT name WHERE city = $city - my problem is that I'm not sure how to set $city (being the name of the <select> tag). I can't use $_POST['city'] because the form hasn't been sent at this point.
Any ideas?
If you want this to be dynamic (i.e. after the user changes the dropdown) you will have to use javascript to firstly query a PHP page (probably using jQuery get) then adjust the dropdowns accordingly. There are lots of tutorials for this on the web.
If you just want the initial page data to be populated you can pick the first city from your query and set the option as selected, then use that city in your next query.
Something like:
$first = True;
while($row = mysql_fetch_array($result))
{
echo "<option" . (($first) ? " selected" : "") . ">" . $row['city'] . "</option>";
if($first)
{
$first = !$first;
$city = $row['city'];
}
}
//now do stuff with with $city
<?
$CITIES = query_result("SELECT DISTINCT cities FROM nights;");
if (isset($_POST["city"])) {
$NAMES = query_result("SELECT name FROM nights WHERE city = '{$_POST[city]}'");
if (isset($_POST["day"])
$DAYS = query_result("SELECT day FROM nights WHERE city='{$_POST[city]}'".
" AND name = '{$_POST[name]}'");
else
$DAYS = array();
} else
$NAMES = array();
/* now output the <select> markup for $CITIES, $NAMES and $DAYS */
?>
Note: you have to define the query_result function yourself (I just used it to simplify the code).
You can use AJAX for this.
On change event call javascript-ajax function that call php script which makes you second dropdown caode.
You will need to use ajax to load options from php script.
Here is an example of how you can do it with jquery and ajax:
Autopopulate Select Dropdown Box Using jQuery
Related
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.
I have created a contacts database using PHP, MySQL on a XAMPP server.
The page opens with a 'Contacts' table with Add, Edit & Delete buttons.
Add & Delete are working fine.
Edit button opens a modal form with all the usual inputs which are filled in with values from the table row using...
$("#dlgeditContactName").val(ContactName);
$("#dlgeditEmail").val(Email);
etc.
There is also a select element (Contact Type) which is populated using PHP...
<?php
$conn = new mysqli('xxxx', 'xxxx', 'xxxx', 'xxxx') or die ('Cannot connect to db');
$result = $conn->query("select contacttypeid, contacttype from tblcontacttypes");
echo "<select id = 'dlgeditcontacttypeid'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['contacttypeid'];
$name = $row['contacttype'];
echo '<option value = "'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
The contacttypeid & contacttype are int and string eg.
1, Personal
2, Family
etc.
At the moment this select box acts as expected and user can choose an option during an edit session.
I just don't know the best way to put a default value in this select box based upon what's in the value in the table row.
Filling the other input elements was easy but using the following for the select does not work...
$("#dlgeditcontacttypeid").val(ContactTypeID);
I think I will have to use 'selected' as in ...
<option value="audi" selected>Audi</option>
(from W3Schools), but not sure if this is best or even how to do it.
I thought of a hidden div on the form with the ID but no luck getting the value to PHP
I tried putting some Java inside the PHP ...
echo "<script> function(); </script>";
but it looks 'messy' and I don't believe it's the best approach
There must be a standard method for this issue - anyone had to deal with this?
Is this what you are looking for:
$ContactTypeID = 2; //Considering you have default value with you.
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['contacttypeid'];
$name = $row['contacttype'];
if($id == $ContactTypeID) //If default value and id in loop are same
echo '<option value = "'.$id.'" selected="selected">'.$name.'</option>';
else
echo '<option value = "'.$id.'">'.$name.'</option>';
}
I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/
I am new to php and web programming.
I am programming a website that collects essays. In the submission form, I want the date to be entered by 3 select dropdown forms (day-month-year). I used to add them in a text field and save them as strings in database. I added already hundreds of essays so I am not changing the type of data.
I did the following:
1- I made a dynamic dropdown using php:
function get_dropdown_options( $name, array $options, $selected=null ) {
$dropdown = '<select name="'.$name.'" id="'.$name.'">'."\n";
$selected = $selected;
foreach( $options as $key=>$option )
{
$select = $selected==$key ? ' selected' : null;
$dropdown .= '<option value="'.$key.'"'.$select.'>'.$option.'</option>'."\n";
}
$dropdown .= '</select>'."\n";
return $dropdown; }
2- then I made a function to show three dropdown menus for days, months and years.
function show_date_dropdown_row($name, $label, $option1, $option2, $option3, $value = "") {
echo "<tr class=\"".get_row_bg()."\" valign='top'>\n<td><p class=\"rowtitle\">".$label."</p></td>\n";
echo "<td><p>\n";
echo get_dropdown_options($name1, $option1, $value1).get_dropdown_options($name2, $option2, $value2).get_dropdown_options($name3, $option3, $value3);
return $name = $name1." - ".$name2." - ".$name3;
}
3- in the submission form page, I put the following code:
show_date_dropdown_row("release_date", "Release Date", $days_list, $months_list, $years_list, "");
4- the name "release_date" is then added to the database.
The page shows the three dropdown lists perfectly. But the problem is that the "release_date" in database don't store any value.
I tried the function in step1 and it works perfectly. I know that the problem is in step two, but don't know where.
First your return statement inside show_dropdown_row will not provide you with the date you want. That function will run only once when user request for the page.
So instead of $name1,$name2 and $name3 in your get_dropdown_options function you should put values like. day,month and year as names for your select elements.
When submiting your form at on your php script you should catch those value using post or get.
like.
$dates=$_POST['year']."-".$_POST['month']."-".$_POST['day'];
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 ?>)