Dynamic Drop-Down Pulling From Database But Option Value Not Working - php

I'm trying to create a dynamic drop down menu that pulls the city name from a database (and automatically updates as I add new cities) and then when selected goes to that city page. The drop down menu works, but when selecting the city nothing happens. Not sure where I'm going wrong. Here's what I've got
<?php mysql_select_db ("db_name");
echo "<select name=database><option value='.'>Select Your City</option>";
$result = mysql_query ("select DISTINCTROW city_head from database order by city_head");
while ($city_head=mysql_fetch_assoc($database)) {
echo "<option value="#CityIDPage">".$city_head[city_head]."</option>\n"; }
echo "</select><p>";
?>

<select> elements to not inherently change the page location when a new option is selected.
You can add this functionality - changing the page location to the value of value for the selected option - by adding the following attribute to select:
onchange="window.location.href=this.options
[this.selectedIndex].value"
i.e.,
<?php
mysql_select_db ("db_name");
echo "<select name=database onchange=\"window.location.href=this.options
[this.selectedIndex].value\"><option value='.'>Select Your City</option>";
$result = mysql_query ("select DISTINCTROW city_head from database order by city_head");
while ($city_head=mysql_fetch_assoc($database)) {
echo "<option value="#CityIDPage">".$city_head[city_head]."</option>\n";
}
echo "</select><p>";
Note that you must set value appropriately for each city; I don't know your database schema, so I cannot advise you there.

Related

php populate option box from database table

I am writing code to register a new project via a html form. I want to be able to click a dropdown box which pulls the values from a table on the database.
At the moment a dropdown box displays but with no values.
PLEASE NOTE: I am a learning the basics so apologies if this is a simple question/answer scenario.
My code is below, any help is appreciated, I connect to the database via a php include script. The table is called 'customers' and the item I want to list is 'name';-
<?php
$result = mysql_query("SELECT customers FROM name");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
}
echo "</select>";
?>
"The table is called 'customers' and the item I want to list is 'name';" -
Do SELECT name FROM customers instead of SELECT customers FROM name
Using mysql_error() to mysql_query()
would have shown you the error that the table name does not exist.
Plus,
[name] are missing quotes inside them => ['name'] which are being treated as constants.
in
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
as caught and kudos to devdesign
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
However, you are using a deprecated MySQL library. If you are still not getting results, then this could mean that you need to use (and should use) mysqli_ or PDO instead.
Here are a few links on the subject:
mysqli with prepared statements
PDO with prepared statements.
Your code should be. Also note the single quotes within $row['name']. You missed that.
<?php
$result = mysql_query("SELECT name FROM customers");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
}
echo "</select>";
?>

I'm not able to change the page contents when i select combo-box options in php

<?php
// select box open tag
$selectBoxOpen = "<select name='store_name' >";
// select box close tag
$selectBoxClose = "</select>";
// select box option tag
$selectBoxOption = '';
// connect mysql server
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// select database
mysql_select_db("store", $con);
// fire mysql query
$result = mysql_query("SELECT store_name FROM store_input");
// play with return result array
while($row = mysql_fetch_array($result)){
$selectBoxOption .="<option value = '".$row['store_name']."'>".$row['store_name'] . "</option>";
}
// create select box tag with mysql result
$selectBox = $selectBoxOpen.$selectBoxOption.
$selectBoxClose;
echo $selectBox;
?>
this is my sample code, I have created combobox in php with option values from database values
but i'm not able to change the page contents when i select options.
any answers
Your code is lacking Javascript, which would be required for the outcome you are expecting. Seeing as you haven't really defined the complete outcome you expect, I will just show you what you need to update the url with the currently selected store:
$selectBoxOpen = "<select name='store_name' onchange=\"location.href=location.href+'?store='+this.value\" >";
I've added an onchange event (read more about DOM events here) so that when you select a different value you are changing the location.
Now when you change the value of the select, your url should change to scriptname.php?store=SomeStoreName

php drop down print selected item

I am trying to print the selected dropdwon item. I have already written the code for dropdown to fetch a column from database.
Now i should print the only the id of selcted dropdown item. i don't know how to make it. please help me, this is my code
<?
$query_name="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`name` ASC";
$result = mysql_query ($query_name);
echo "<select name=category value=''></option>";
while($nt=mysql_fetch_array($result))
{
echo "<option value=$nt[name]>$nt[name]</option>";
}
echo "</select>";
$query_id="SELECT id_cat FROM `fs01_metier_cat`";
$result1 = mysql_query ($query_id);
while($row = mysql_fetch_assoc($result1))
{
echo $row['id_cat'];
}
?>
try this:
while($nt=mysql_fetch_array($result)){
echo "<option value='{$nt['id_cat']}'>{$nt['name']}</option>";
}
with {} php can insert also array values into a string and you should set ' ' around the attribute "value"'s value (alot of values here.. ^^), that the html is w3c conform (i dont know if a browser would take it as correct without them..)
without the { } it would look like that:
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['id_cat']."'>".$nt['name']."</option>";
}
depending on your editor code highlighting might work better in the second case ;)
and about the selected item:
i would suggest you to use jQuery to get the content of the selected item
var selectedId = $('#yourselectid option:selected').attr('value');
and then you can e.g. write it to the document or to a div:
document.write(selectedId);
or
$('#yourDivIdWhereYouWantToPutTheSelectedId').html(selectedId);
important: please note that i changed the value's index to id_cat because then you can handle the options with their id
Since the selected option changes everytime you change the dropdown selection, you can not handle this via php. There are ways to do that without a huge library like jQuery (since they are also just simple Javascript) but they simplify such things alot ;)

How to use a series of drop down list to display data from mysql database

needing some advice.
I am wanting to include 4 drop down lists on a website, which all contain data from different fields in a mysql table.
I then want to be able to press a submit button and display the required data on a webpage.
I am having trouble with knowing what programming language to use and also finding it difficult to find any tutorials. Any help would be greatly appreciated.
Thanks
You mean a HTML dropdown list or just a select dropdown in a form?
If you mean a select dropdown in a form you could do something like this:
<?PHP
$query = mysql_query("SELECT value FROM table ORDER BY value ASC") or die(mysql_error());
$result = mysql_num_rows($result);
// If no results have been found or when table is empty?
if ($result == 0) {
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="your_result.php">';
echo '<select name="list" id="lists">';
// Fetch results from database and list in the select box
while ($fetch = mysql_fetch_assoc($query)) {
echo '<option id="'.$fetch['value'].'">'.$fetch['value'].'</option>';
}
echo '</select>';
echo '</form>';
}
?>
And then in your_result.php you should fetch the data from your MySQL database based on value from the (when you fetch use mysql_real_escape_string):
<?PHP $_POST['list']; ?>
You could also do everything in just one file, but thats up to you. Try to use google, there are dozens of tutorials out there.

retrieve mysql data as array and display in multiple combo boxes

i am trying to use the mysql data items into the select combo box. it basically works well but the problem is when there are multiple combo boxes it is a lot of load to the server since adding each combo box takes a lot of time. i am trying to figure out a better way. may be pull date once into an array just for the session and place it in the combo boxes.
The logic is basically it is a quotation form where about 3500 items will be shown as drop down and user will select and then enter price and other details. the rows are dynamically added or deleted by the user.
i am currently using the following code:-
<?php
$con = mysql_connect('blah blah blah');
if (!$con) {
die ('Could not connect: ' . mysql_error());}
$db = mysql_select_db('blah',$con);
$extract1 = mysql_query("query") OR die (mysql_error());
$numrows1 = mysql_num_rows($extract1);
echo "<select name='itemname' title='select Item Name'>";
echo "
<option>Select Item Description</option>
";
while ($row1=mysql_fetch_assoc($extract1))
{
$ic=$row1['ItemName'];
echo "
<option>$ic</option>
";
}
echo "</select>";
mysql_close($con);
?>
Don't echo your option do this in your while statement:
$ic[]=$row1['ItemName'];
then outside of the while loop anywhere on the page:
foreach($ic as $i){
echo "<option>".$i."</option>";
}
First off, Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
<?php
$con = mysql_connect('blah blah blah') or die(mysql_error());
$db = mysql_select_db('blah',$con) or die(mysql_error());
$result = mysql_query("query MAYBE NARROW DOWN TO MORE RELEVANT RESULT SET") or die (mysql_error());
$option = '<select size="1" name="optionBox">';
if(mysql_num_rows($result)>=1){
while ($row=mysql_fetch_assoc($result)){
$option .="<option selected value=\"".$row['ItemName']."\">".$row['ItemName']."</option>\n";
}
}else{
$option .='<option selected value="0">No items to list</option>';
}
$option .='</select>';
echo $option;
mysql_close($con);
?>
Yes, if your data changes infrequently enough, it may be a good idea to put the data into an array on the session, and render it from there. Depending on the frequency of change of your data, you might be able to get away with rendering it to a non-session data element (for example, a file on your filesystem) and populating your comboboxes from there (or just rendering all your choices into the combobox elements in that file, and using that data directly); that depends on the frequency by which your data is updated, of course.

Categories