Dynamic PHP Dropdown Menu for Countries - php

Okay so I have a table called Countries and it looks like this:
---------------------------
|Country | Code |
---------------------------
|Afganastan | AF |
|Ă…LAND ISLANDS| AX |
| etc. | etc. |
---------------------------
The thing that I want to do is create a dynamic menu in which the user chooses a country and that itself gets stored as a value that I can call after the user hits submit.
I did try something here but I'm not sure what its doing because I am still new to PHP and HTML to the point where I just type things in to see what would happen.
Anyways I am really stuck and I tried using google and the search feature in this site and nothing I found worked for me...
The code I tried is this:
<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo '</select>';
?>
</select>
The result is supposed to look like a dropdown menu with the list of countries from the database in it. But this doesn't work and just shows this in the drop down:
.$row['name']
Which is nothing close to what I want because that's not even a country. when I remove that part of the code, then there is no option for the user to choose, the menu is empty.
EDIT
My code so far that still doesn't work:
<select name = 'country'>
<?php
include ("account.php");
include ("connect.php");
$result = mysql_query('SELECT Code , Country FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['Code']?>"><?php echo $row['Country']?></option>
<?php}
?>
</select>
The include ("account.php"); and include ("connect.php"); lines allow me to connect to my database.

you code should be something like this
$host = "localhost";
$user = "root";
$pass = "yourpassword";
$db = "databasename";
// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = #mysql_connect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}
// Then you need to make sure the database you want
// is selected.
#mysql_select_db($db);
<form method = "POST" action = "abc.php">
<select name = 'country'>
<?php
$result = mysql_query('SELECT id , name FROM Countries');
while ($row = mysql_fetch_array($result))
{?>
<option value="<?php echo $row['id']?>"><?php echo $row['name']?></option>
<?php}
?>
<input type = "submit" value = "Submit">
</form>
Now in php use this
echo '<pre>';
print_r($_POST);
And you will see what user selected. Check your settings there might be some problem.

Your single and double quotes are messing you up:
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
should be:
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
You can use a single quote around your script but when you jump out of it to do the $row['id'] and $row['name'] you are running into issues because it thinks you are jumping back into your quoted code... Either use my example above, starting/ending with double-quotes and escaping all double-quotes inside that need to display, or escape your single quotes in the $row[\'id\'] and $row[\'name\']
Thant should help you out.

Try this code
<?php
$result = mysql_query('SELECT * FROM Countries');
?>
<select name="country">
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>

Firstly your table doesn't have a column id. Try changing your query like
SELECT Country, Code FROM Countries
Then the code and the html should be like this
<?php
$host = "localhost";
$user = "user"; //username
$pass = "pass"; //password
$db = "db"; //database
$con = #mysql_connect($host, $user, $pass);
if ( !$con )
{
echo "Error connecting to database.\n";
}
#mysql_select_db($db);
?>
<select name="country">
<option value="0" selected="selected">Choose..</option>
<?php
//echo '<select name = \'country\'>';
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
?>
</select>

<select>
<?php
$result = mysql_query('SELECT Country FROM Countries');
echo '<select name="country">';
$row = mysql_fetch_array($result)
for ($i=0; $i<count($row ); $i++)
{
echo '<option value="'.$row[$i]['id'].'">'.$row[$i]['name'].'</option>';
}
echo '</select>';
?>
next page use print_r($_POST);
or var_dump($_REQUEST);

If you are using mysql_fetch_array you can use either the field names or their selected index to read them from the fetched row. You can also use either the sprintf or printf functions to merge content into a string to help keep the HTML fragment clean of the quotes needed to merge in values otherwise.
$result = mysql_query('SELECT Country, Code FROM Countries');
while ($row = mysql_fetch_array($result)) {
printf('<option value="%1$s">%2$s</option>',
$row['Code'], $row['Country']);
}

Your SQL statement selected only 'Country' from the 'Countries' table; as a result, it's impossible for you to use $row['id'] and $row['name'].
Use this instead:
echo '<select name="country">';
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['Code'].'">'.$row['Country'].'</option>';
}
echo '</select>';
?>
That should solve your problem.

I figured out the problem I was having. The first being that there was an extra select tag in the page and the second that the file was saved as a html page instead of a php file. Thank you to everyone that helped me figure this out!

Try my code, I'm using this and it really works... just change the values...
<?php
include ('connect.php');
$sql = "SELECT * FROM casestatusfile";
$result = mysql_query($sql);
echo "<select name = 'txtCaseStatus'/>";
echo "<option value = ''>--- Select ---</option>";
$casestatus = $_POST['txtCaseStatus'];
$selected = 'selected = "selected" ';
while ($row = mysql_fetch_array($result)) {
echo "<option " .($row['CASESTATUSCODE'] == $casestatus? $selected:''). "value='". $row['CASESTATUSCODE'] ."'>" . $row['CASESTATUS'] ."</option>";
}
echo "</select>";
?>
I'm sure that is working because that is the one that i'm using....

Related

How to populate select dropdowns on html using database data

I'm a complete newbie with PHP/html stuff so please bear with me.
I've been trying to populate a select box using data from a myslq database and I can't get it to work, all I have is just a blank textBox.
This is what I have for now:
<select name="cargo">
<?php
require("conectadb.php");
$ok = conecta_db() or die ("Failure");
$sql = mysqli_query($ok, "SELECT descCargo FROM tbcargo");
while ($row = mysqli_fetch_array($sql)){
$c = $row['descCargo'];
echo("<option value=\"$c\">$c</option>");
}
?>
</select>
This is my database structure for now, with all the relevant rows:
Database name: tbcargo
PkCodCargo (primary key, AUTO_INCREMENT)
descCargo (what I want to fill the dropdown with)
I've tried everything I could think of to no avail, unfortunately.
Can someone help to point out exactly what am I doing wrong here?
Thanks in advance!
Update the part of your code to:
<select name= 'cargo'>
<?php
require("conectadb.php");
$ok = conecta_db() or die ("Failure");
$sql = mysqli_query($ok, "SELECT descCargo FROM tbcargo");
while ($rows = $sql->fetch_assoc())
{
echo '<option value="'.$rows['descCargo'].'">'.$rows['descCargo'].'</option>';
}
?>
</select>
I've finally found out the issue.
My file was named .html instead of .php and that's why nothing ever worked.
Hope this is able to help another newbie like myself out there
Cheers!
Here is the solution.
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT descCargo FROM tbcargo";
$result = mysql_query($sql);
echo "<select name='cargo'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'. $row['descCargo'] .'">'.$row['descCargo'] .'</option>';
}
echo "</select>";

How do I store value in my database in a dynamic dropdown list?

This is a dynamic dropdown in PHP/mySQL.
I want to store the name in the database server but the tag outputs the integer value.
If i change the code from <option value="<?php echo $row["id"]; ?>"> to <option value="<?php echo $row["name"]; ?>"> It shows my_sqli_fetch_array expects parameter 1 error.
My objective being to store the corresponding $row["name"] that is being displayed on the dropdown instead of $row["id"].
<?php
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link,"loginsystem");
?>
<form name="form1" action="" method="post">
<table>
<tr>
<td>Select Assembly Line</td>
<td><select id ="assemblylinedd" onChange="change_assemblyline()">
<option>Select</option>
<?php
$i=1;
$res=mysqli_query($link, "SELECT * FROM assemblyline");
$count=mysqli_num_rows($res);
if ($count >0){
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
}
<?php $i++;} }else{
echo "No record Found !";
} ?>
</select></td>
</tr>
Scripting code :
<script type="text/javascript">
function change_assemblyline()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?assemblyline="+document.getElementById("assemblylinedd").value, false);
xmlhttp.send(null);
alert(xmlhttp.responseText);
document.getElementById("devices").innerHTML=xmlhttp.responseText;
}
This is my ajax.php
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link,"loginsystem");
$assemblyline = isset($_GET['assemblyline']) ? $_GET['assemblyline'] : '';
$devices = isset($_GET['devices']) ? $_GET['devices'] : '';
if($assemblyline!="")
{
$res=mysqli_query($link, "SELECT * FROM devices WHERE devices_id=$assemblyline");
echo "<select id='devicesdd' onchange='change_devices()'>";
while($row=mysqli_fetch_array($res))
{
echo "<option value='$row[id]'>";echo $row["name"]; echo "</option>";
}
echo "</select>";
}
Please do ignore onchange_devices() as it follows the same for next consecutive dropdown.
Though, its your requirement to save device name in DB, it is advised to save numeric id.
Reason: Name may change, but, id will persist.
If say your device id:name is 99 : iPhone 6 and you save in DB: iPhone 6, later the name gets changed to iPhone6.
In this scenario if you search records with name iPhone6, clearly, your above record will not show.
If you save numeric id, it will show irrespective of name change.
Coming back to your question:
I cannot write code here. But a pseudo code logic will help (hope so):
Take a hidden field device_name.
On change of drop down, with jQuery, assign value to hidden field.
$("#assemblylinedd option:selected").text();
Now, after submit, you will get device_name in hidden field.
$devices = isset($_GET['device_name']) ? $_GET['device_name'] : '';
Save this to DB.
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link, "loginsystem");
$assemblyline = isset($_GET['assemblyline']) ? $_GET['assemblyline'] : '';
$devices = isset($_GET['devices']) ? $_GET['devices'] : '';
if(!empty(trim($assemblyline)))
{
$res = mysqli_query($link, "SELECT * FROM devices WHERE devices_id = '$assemblyline'");
echo "<select id='devicesdd' onchange='change_devices()'>";
while($row = mysqli_fetch_array($res))
{
echo "<option value='" . $row["id"] . "'>" . $row["name"] . "</option>";
}
echo "</select>";
}
I've added a proper empty check instead of your != "", which didn't previously prevent a single space from being passed.
I've quoted your query value, I would definitely use prepared statements instead of passing values directly.
I've quoted your $row[id].
I've concatenated your string correctly.
Note: It would be preferable to return a JSON array object with the IDs and the names instead of outputting HTML via the AJAX, it would make your code-base much cleaner and adaptable in the future.
Reading Material
empty
trim

PHP echo out data into HTML drop drop down menu

I have a HTML etc.. tags now what I want to achieve is upon a selection of ie. i want to load the related info from database to in a new tag with as many tags.
I am using PHP to do achieve this now at this point if for example i choose option1 then the query behind it retrieves relevant information and stores it in a array, and if I select option2 exactly the same is done.
The next step I made is to create a loop to display the results from array() but I am struggling to come up with the right solution to echo retrieved data into etc. As its not my strongest side.
Hope you understand what I am trying to achieve the below code will clear thing out.
HTML:
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP:
$form = Array();
if(isset($_POST['workshop'])){
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
while($result2 = mysqli_fetch_assoc($query2)){
//The problem I am having is here :/
echo "<select id='Forex' name='Forex' style='display: none'>";
echo "<option value='oko'>.$result[1].</option>";
echo "</select>";
print_r($result2);echo '</br>';
}
}else{
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%'";
$query = mysqli_query($link, $sql);
while($result = mysqli_fetch_assoc($query)){
print_r($result);echo '</br>';
}
}
}
Try this code:
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value='oko'>{$result['course']}</option>";
}
echo "</select>";
echo '</br>';
From the top in your php:
// not seeing uses of the $form I removed it from my answer
if(isset($_POST['workshop'])){
$workshop = $_POST['workshop'];
$lowerWorkshop = strtolower($workshop);
// neither of $_POST['Forex'] nor $_POST['Binary'] are defined in your POST. you could as well remove those lines?
//Retrieve Binary Workshops HERE we can define the sql in a single line:
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%$workshop%' OR course LIKE '&$lowerWorkhop%'";
$query = mysqli_query($link, $sql); // here no need to have two results
// Here lets build our select first, we'll echo it later.
$select = '<select id="$workshop" name="$workshop" style="display: none">';
while($result = mysqli_fetch_assoc($query)){
$select.= '<option value="' . $result['id'] . '">' . $result['course'] . '</option>';
// here I replaced the outer containing quotes around the html by single quotes.
// since you use _fetch_assoc the resulting array will have stroing keys.
// to retrieve them, you have to use quotes around the key, hence the change
}
$select.= '</select>';
}
echo $vSelect;
this will output a select containing one option for each row returned by either of the queries. by the way this particular exemple won't echo anything on screen (since your select display's set to none). but see the source code to retrieve the exemple.

PHP dropdown list with data from a MySQL database

i have been try for PHP dropdown list with data from a MySQL database.
I have attached my code below, am not getting the dropdownlist .Can anyone help
<?php
$conn = mysql_connect('localhost','root','');
mysql_select_db('qsearch',$conn);
$query = "select Category from information";
$result = mysqli_query($query);
echo '<select id="info" name="info">';
echo '<option value="">-select-</option>';
while ($row = mysqli_fetch_assoc($result)){
?>
<option value="<?php echo $row['Category']; ?>"><?php echo $row['Category']; ?> </option>
<?php
}
echo "</select>";
?>
Because half of your functions are from mysql and other from mysqli
$conn = mysql_connect('localhost','root','');
mysql_select_db('qsearch',$conn);
$query = "select Category from information";
$result = mysqli_query($query);
while ($row = mysqli_fetch_assoc($result)){
You need to closely read the documentation first
http://www.php.net/mysqli & http://www.php.net/mysqli_connect

Populating Dropdown HTML Menu with MySQL Query Results

I'm attempting to populate an HTML dropdown menu with the results of a MySQL query. The query is running fine and not throwing any errors, but for some odd reason the results won't display correctly.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'></option>";
}
?>
<select name="cpu"><? echo $option; ?></select>
I'm pretty sure it lies somewhere in the $option .= ... ; but it I can't seem to figure it out.
You are not printing the value to be shown in dropdown
try this
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'>{$row['itemName']}</option>";
}
I saw that you are using short tags here
<select name="cpu"><? echo $option; ?></select>
please make sure you have short tag enabled in php.ini
Two things:
You need to initialize $option and print the value to be shown in the dropdown
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
$option = "";
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'>{$row['itemName']}</option>";
}
?>
<select name="cpu"><? echo $option; ?></select>
Seems you forget to add a value inside <option></option> field you only set value for fetching $_POST[] but not for viewing. :D
Also seeing $option variable to be concatenated seems that you already declared it at first
if not you need to probably declared it first.cause this may result to error undefined variable.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
$option = '';
while($row=mysql_fetch_array($result)) {
$option .= '<option value='.$row['itemName'].'>'. $row['itemName'].'</option>';
}
?>
<select name="cpu"><?php echo $option; ?></select>
Forgot the simplest part:
$aa .= "{$row['itemName']}";
I needed to add the actual label to be displayed between the option tags :)

Categories