I'm new in PHP.. I need your help..
I have 2 dropdownlist that related:
dropdown 1 : manually insert the value
dropdown 2 : attach value from database (value based on condition that selected in dropdown 1)
Then, both value which are selected will display in textbox at another form.
My problem is:
1) The value in 2nd dropdown can't be display.
2) The value in 1st dropdown can pass to other form but the 2nd can't.
Please kindly guide me.
I don't know how to share my code here.
form1.php
//1st dropdown
<select name="fruit_name" id="fruit_name" style="font-family: Calibri;font-size: 10pt;" onchange="loadXMLDoc(this.value); ">
<option value="0">-- please choose --</option>
<option value="Pineapple">Pineapple</option>
<option value="Apple">Apple</option>
//2nd dropdown
$fruit_name = $_POST['fruit_name'];
#Connect to MySQL
#Connect to database
$result = mysql_query("SELECT colour FROM fruit WHERE fruit_name = '$fruit_name'");
echo "<select name='colour' id='colour' style='font-family: Calibri;font-size: 10pt;'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = ''>" . $row['colour'] . "</option>";
}
echo "</select>";
mysql_free_result($result);
//Closes specified connection
?>
form2.php
<?php
//connection
$fruit_name = $_POST['fruit_name'];
$colour = $_POST['colour'];
?>
<label>
<input type="text" name="fruit_name" id="fruit_name" value = "<?php echo $fruit_name;?>" readonly>
</label>
<p>
<label>
<input type="text" name="colour" id="colour" value="<?php echo $colour;?>" readonly>
</label>
</p>
I usually don't do this but since I've some spare time on hand right now, I'm going to give the general approach that you can follow:
Include the following between your <head> tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
Below that, paste this code
<script type="text/javascript">
$(function(){
$('select#fruit_name').change(function(){
var selectedVal = $(this).val(); // get the selected value
$.ajax({ // send ajax request to the php file to process data
type:'post',
url:'php-page-name.php',
data:{'value':selectedVal},
success:function(ret) // display the result from php-page-name.php page
{
$('div#result').html(ret);
}
});
});
});
</script>
Lets move on to your HTML now
<select name="fruit_name" id="fruit_name" style="font-family: Calibri;font-size: 10pt;">
<option value="0">-- please choose --</option>
<option value="Pineapple">Pineapple</option>
<option value="Apple">Apple</option>
</select>
<div id="result">
<select>
<option>Select One</option>
</select>
</div>
php-page-name.php page (Do not forget to create this page and put it in the same folder as form1.php)
<?php
// put the code to connect to your database here
$fruit_name = $_POST['value']; // this will contain the value selected from first dropdown
$result = mysql_query("SELECT colour FROM fruit WHERE fruit_name = '$fruit_name'");
echo "<select name='colour' id='colour' style='font-family: Calibri;font-size: 10pt;'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['colour']."'>" . $row['colour'] . "</option>";
}
echo "</select>";
mysql_free_result($result);
?>
PS : I'm using the mysql_* functions in this example since I'm assuming you're too. But this is not recommended as they are going to be deprecated soon. You might want to switch to mysqli or PDO
Related
I have a form where the 1st select box is required. Depending on the selection, a different table will be used as a source for the query to populate a 2nd select box. Then depending also on the 1st selection a 3rd select box may or may not be necessary. I have designed the form to initially show 3 select boxes, but the user would have to know to skip the 2nd select box in some cases. This is confusing at the least. As an example:
If None is selected for Company, then both the Cemetery & Section select boxes would have to shown (Section being dependent on Cemetery selected). If XYZ Company is selected, then only the Section select box would need to be seen / selected (as the Cemetery is Company specific):
<script>
function getCemetery(val) {
$.ajax({
type: "POST",
url: "get_cemetery.php",
data:'company_name='+val,
success: function(data){
$("#cemetery-list").html(data);
}
});
}
Here is the code of the form:
<body>
<div class="frmDronpDown">
<div class="row">
<label>Company:</label><br/>
<select name="company" id="company-list" class="demoInputBox" onChange="getCemetery(this.value);">
<option value="">Select Company</option>
<?php
foreach($results as $company) {
?>
<option value="<?php echo $company["name"]; ?>"><?php echo $company["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Cemetery:</label><br/>
<select name="cemetery" id="cemetery-list" class="demoInputBox" onChange="getSection(this.value);">
<option value="">Select Cemetery</option>
<?php
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Section:</label><br/>
<select name="section" id="section-list" class="demoInputBox">
<option value="">Select Section</option>
</select>
</div>
</div>
</body>
And here is the additional php code the is called within the script:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["company_name"])) {
if (($_POST["company_name"]<>"None") && ($_POST["company_name"]<>"Other")) {
$sql="SELECT name, available FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$result = mysql_query($sql) or die ( mysql_error());
$row = mysql_fetch_row($result);
$section = $row[0]; // best choice to use if auto fill
$query="SELECT * FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Section</option>';
}else{
$query ="SELECT * FROM cemeteries";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Cemetery</option>';
}
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]." - ".$cemetery["available"]; ?></option>
<?php
}
}
?>
Edit:
Thank you for telling me about .hide and .show. I have looked up examples and what I can find uses a button click. Would you show an example of using them in an php if..else?
Thank you in advance.
Russ
I used the following:
<script>
function wholesection() {
$( "#whole-section" ).slideUp( "fast", function() {
});
}
</script>
AND
echo '<script>',
'wholesection();',
'</script>'
;
I have a dropdownlist populated by a MySql database that shows the titles of books stored in my database.
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
I want the option I choose to send it to another php page search.php
This search.php I want it to get the title and search for this specific book details.(title, price, author.... etc) .I tried to do it with but it ruins the page.
Add below code in form that should work for you.
<form action='search.php' method='post'>
<select id="titles" name='titles'>
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
<input type='submit' value='submit'>
</form>
in search.php:
$title = $_POST['titles'];
You just need to add the form above the select tag and need to give the NAME attribute in the select tag to post the data on another page. You can try with the following code:
<form method="post" action="search.php">
<select id="titles" name="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
<input type="submit" name="submit"/>
</form>
and on the search.php page, you can get the value of the dropdown by this:
$title = $_POST['titles'];
Try as below :
<form method="post" action="YOURPAGEPATH">
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
<input type="submit" name="submit"/>
</form>
Without submit button :
<form method="post">
<select id="titles" onchange="this.form.submit();">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
</form>
Surround that with a form with the appropriate action and add a submit button. Otherwise use something like jQuery to listen for the value of that to change and submit the form.
For example:
<form action="search.php" method="GET">
<select id="titles" name="title">
<?php /* put your stuff here */ ?>
</select>
</form>
And then in jQuery:
$(function(){
$('#titles').on('change', function(){
$(this).closest('form').submit();
});
});
Or you could go real old-school and attach the event listener to the select like this:
<form action="search.php" method="GET">
<select id="titles" name="title" onchange="this.parentNode.submit()">
<?php /* put your stuff here */ ?>
</select>
</form>
Just in case if you don't want to use the Submit Button
<script language="Javascript">
function books(book)
{
var url="http://www.example.com/search.php/?q="+book;
window.open(url, "_self");
}
</script>
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option onClick="books('.$row['title'].')" value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
Here the list will call the Books function on Click and pass the arguments to the function which will redirect you to search.php
To retrieve the book name use
$_GET["q"]
Change the URL as required.
And if the problem is solved don't forget to Mark the answer.
I've got a table that populates data from a MYSQL database and populates a drop-down menu from the same database. I have the drop down menu and table just fine, I would like to be able to choose which data I show in the table however.
<select name = 'peer-id' method='post' style = 'position: relative'>
<?php
while ($content = mysql_fetch_array($peer)) {
echo "<option value='" . $content['Peer'] . "'>" . $content['Peer'] . "</option>";
}
$results = mysql_query("SELECT Destination FROM rate ");
?>
</select>
That's what I have for the select box. How can I get the choice from that and save that as a variable and refresh the table data?
I need to clarify that this will change that current data
#Data#Data#Data
#Data#Data#Data
#Data#Data#Data
Then choose drop down choice and I want it to show new data
#Data2#Data2#Data2
#Data2#Data2#Data2
#Data2#Data2#Data2
So it's going to need to load a new page or refresh some how because it's changing via PHP and not javascript.
I think form may be better, for example
<form id="myform" method="post">
<select name = 'peer-id' style = 'position: relative' onchange="change()">
<option value="1">12</option>
<option value="2">15</option>
<option value="3">16</option>
<option value="4">18</option>
</select>
</form>
<script>
function change(){
document.getElementById("myform").submit();
}
</script>
In the above code, whenever you change the value of select, it will post to the backend, then according to the posted value, you can do want you want, to get the peer-id in php, you can use the following code
$peer-id = $_POST['peer-id'];
Hope helps!
apply this code in select tag hope this works
<select onchange="location = this.options[this.selectedIndex].value;" style="text-decoration:none;">
<option value="customers.php"></font></option>
</select>
insted of the static options, you can do it like this :) here you get all the options from the database. Just replace it with the static options
$peer = mysql_query("SELECT Peer FROM rate Group By Peer Where peer = 'variable'");
$result_peer = mysql_query($peer);
if($result_peer){
while($row_peer = mysql_fetch_array($result_peer)){
echo'<option value='.$row_peer['Peer'].'>'.$row_peer['Peer'].'</option>';
}
I agree in using form, and with this you can echo back onto the page with a submit button (code tested):
<form id="myForm" method="POST">
<select name="select" onchange="<?php echo $_SERVER['PHP_SELF'];?>">
<option value="N">No</option>
<option value="Y">Yes</option>
</select>
<input type="submit" name="formSubmit" value="Submit" >
</form>
<?php
if(isset($_POST['formSubmit']) ){
$var = $_POST['select'];
$query = "SELECT * FROM table_name WHERE DesiredField='$var'";
$result = mysql_query($query)
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$var2 = $row['FieldName'];
echo "First field: " . $var2 . "<br>";
// and so on for what you want to echo out
}
}
?>
I am currently working with a Dependable dropdown menu that functions with the help of jQuery and PHP. The values are being pulled of MySQL database. Is there away to php echo the selected value of a dependable drop down menu?
EXAMPLE
HTML/PHP
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
Please add jquery.js.
your html code
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
//jquery code for source list
<script type="text/javascript">
$(document).ready(function(){
$('#gender').change(function() {
if ($(this).val()!='') {
$("#category").load("postfile.php",{gender_id: $(this).val()});
$("#category").removeAttr('disabled');
}
});
//code on change of sel_source
$('#category').change(function() {
if ($(this).val()!='') {
$("#colour").load("postfile.php",{category_id: $(this).val()});
$("#colour").removeAttr('disabled');
}
});
});
</script>
//postfile.php
//your mysql connection other things goes here
//code for category
$objDb = new PDO('mysql:host=localhost;dbname=dbname', 'ur_username', 'ur_password');
if(isset($_REQUEST['gender_id']) && !empty($_REQUEST['gender_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['gender_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
//code for color
if(isset($_REQUEST['category_id']) && !empty($_REQUEST['category_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['category_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
Hope this will help you.
You are going to have to write a JavaScript function that retrieves the selected value or option from the first HTML select field. This function commonly writes out a new URL path to the current page with the addition of some concatonated Get Variables:
<script type="text/javascript">
getSelectedOptionValue() {
// create some variables to store your know values such as URL path and document
var myPath = " put the URL path to the current document here ";
var currentPage = "currentPage.php";
// get the values of any necessary select fields
var carMake = document.getElementById("carMake").value;
// write out the final URL with the Get Method variables you want using concatnitation
var getMethodURL = myPath + currentPage + "?carMake='" + carMake + "'";
// function refreshes page using the function made URL
window.location.replace( getMethodURL );
}
</script>
Since the second select field is dependent on the first you have to assume that the user is going to make a selection from the first choice of options. This means that the function that retrieves the value of the primary select field must run in response to a change in the fields selection. For example
<select name="carMake" id="carMake" onchange="getSelectedOptionValue();">
Depending on how you have set up your DB, you may want either the value of the option tag or the string presented to the user between the option tags...this is up to you keeping in mind how you may re-query the information if your original record set hasn't already pulled up the necessary info to write the second set of select option tags.
To write out the second select field using php simply repeat the while loop you have used for the first. This time replace your SQL statement with a new one using a variable in which you have stored the value retrieved from the new URL using the get method
<?php
// here I am using the more generic request method although you could use the get as well
$carMake = $_REQUEST['carMake'];
sql_secondSelectField = "SELECT * FROM tbl_carModels WHERE carMake = $carMake";
// Run new query and repeat similar while loop used to write your first select field ?>
Im trying to implement the search feature in my website.
when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.
what i want is to keep the selected category of the combo by default in the form after posted
For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated
I assume you get categories from database.
you should try:
<?php
$categories = $rows; //array from database
foreach($rows as $row){
if($row['name'] == $_POST['category']){
$isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
} else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>
Assuming that by "combo" you mean "A regular select element rendering as a drop down menu or list box" and not "A combobox that is a combination of a drop down menu and free text input":
When outputting the <option> elements, check the value against the submitted data in $_POST / $_GET and output selected (in HTML) or selected="selected" (in XHTML) as an attribute of the option element.
Here is the JQuery way I am using.
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
$("#name").val("<?php echo $_POST['name'];?>");
</script>
But this is only if you have jquery included in your webpage.
Regards
<?php
$example = $_POST["friend"];
?>
<form method="POST">
<select name="friend">
<option value="tom" <?php if (isset($example) && $example=="tom") echo ' selected';?>>Thomas Finnegan</option>
<option value="anna" <?php if (isset($example) && $example=="anna") echo ' selected';?>>Anna Karenina</option>
</select>
<br><br>
<input type="submit">
</form>
This solved my problem.
This Solved my Problem. Thanks for all those answered
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
$countries_uid = $_POST['countries_uid'];
while($row = mysql_fetch_array($result)){
$uid = $row['uid'];
$country = $row['country_name'];
$isSelected = null;
if(!empty($countries_uid)){
foreach($countries_uid as $country_uid){//cycle through country_uid
if($row['uid'] == $country_uid){
$isSelected = 'selected="selected"'; // if the option submited in form is as same as this row we add the selected
}
}
}else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$uid."'".$isSelected.">".$country."</option>";
}
this is my solutions of multiple select dropdown box after modifying Mihai Iorga codes
After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Easy solution:
If select box values fetched from DB then to keep selected value after form submit OR form POST
<select name="country" id="country">
<?php $countries = $wpdb->get_results( 'SELECT * FROM countries' ); ?>
<option value="">
<?php if(isset($_POST['country'])){echo htmlentities($_POST['country']); } else { echo "Select Country *"; }?>
</option>
<?php foreach($countries as $country){ ?>
<option <?php echo ($_POST['country'] == $country->country_name ? 'selected="selected"':''); ?> value="<?php echo $country->country_name; ?>"><?php echo $country->country_name; ?>
</option>
<?php } ?>
</select>