Getting value from populated drop down list - php

I have populated a drop down list from the database but i dont think the value is being set to the name the user chooses from the drop down as when the form is selected, no value is added to the database.
At the moment, it shows all the names from that table. As i said, i want the value to be the name the user chooses so that when the form is submitted it is added to the database and can be fetched on another page.
<select name="category">
<?php
$sql = mysql_query("SELECT category_Name FROM category");
while ($row = mysql_fetch_array($sql)){
echo '<option value="'.$category_Name.'">' . $row['category_Name'] . "</option>";
}
?>

echo '<option value="'.$category_Name.'">' . $row['category_Name'] . "</option>";
// ^ this var is never set
should be
echo '<option value="'.$row['category_Name'].'">' . $row['category_Name'] . "</option>";
// ^ change this
or you can just have it like this
echo '<option>' . $row['category_Name'] . "</option>";
If value is not set, it just takes the value of the display name.

Related

Passing selected variables in PHP?

I want to send some information from one php file to another.
I've read about the use of $_SESSION and $_POST, but they're giving me some problems.
My code looks something like this:
<form action="booking.php" method="post">
<select name="bookingflight">
<?php
$query = "SELECT Flight, Name
FROM Airport";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "<option value=\"". $row['Flight'] . ',' . $row['name'] . "\">" . $row['Flight'] . ' ' . $row['name'] . "</option>";
}
?>
</select></p>
<input type="submit" value="book flight"/>
</form>
This gives me a dropbox list of all the flights, along with the name of the flights.
If I select an element it's stored in $_POST["bookingflight"] which I can access in booking.php, which is fine.
However, it's given as a string, while I should be able to handle flight and name separately.
Ideally, I'd have two variables, one for flight and one for name, which I can access in booking.php.
How should I do this? With $_SESSION I don't even know how to assign a selected item from the list to a variable.
Alternate Solution: If Flight is unique data
while($row = mysql_fetch_array($result)) {
$flight=$row['Flight'];
$name=$row['Name'];
echo "<option value='$flight'>$flight $name</option>";
}
PHP : booking.php
<?php
$flight=$_POST['bookingflight'];
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Flight,Name FROM Airport WHERE Flight='$flight'");
$row = mysqli_fetch_array($result);
$name= $row['Name'] ; // Here you get Name of selected Flight
mysqli_close($con);
?>
Or
If your Airport table contains any unique data/id , you can pass that data as option value too
You started this the wrong way...
Give your Airport table a unique primary key (named id, INT, auto-increment) and pass that as a value in generated options:
echo "<option value=\"". $row['id'] ."\">" . $row['Flight'] . ' ' . $row['name'] . "</option>";
Now when you POST your form you get that ID value in booking.php.
Because every flight has a unique ID you can just issue another query and you get your result as an array there:
$query = "SELECT Flight, Name FROM Airport WHERE id = $id";
Put this in your booking.php...
if($_POST)
{
$values = $_POST['bookingflight'];
$val= explode(',',$values);
$_SESSION['flightnumber'] = $val[0];
$_SESSION['flightname'] = $val[1];
}

How to Populate Dropdown List's text and value from MySQL?

I am using mysqli to query a database table to obtain the value for a dropdownlist. However, I also want to retrieve the corresponding description and load that into the option text. My query is as follows:
<?php
$query=('SELECT restaurantid,location from restaurant');
$result = mysqli_query($mysqli,$query);
echo '<select name="ddlStore">';
while($row=$mysqli->fetch_array($result))
{
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">';
'</option>';
}
echo '</select>';
?>
How do I revise the above so that the location field is populating in the dropdownlist's option text?
Updated code:
<?php
$query=('SELECT restaurantid,location from restaurant');
$result = mysqli_query($mysqli,$query);
echo '<select name="ddlStore">';
while($row=$mysqli->fetch_array($result))
{
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' .
htmlspecialchars($row['location']) .
'</option>';
}
echo '</select>';
?>
The above still does not display the locations as dropdownlist option text values.
Update #2:
When viewing the page, the dropdownlist doesn't show the values from the database table. Using IE Developer Tools, I see a script error in the while statement:
Call to undefined method mysqli::fetch_array()
Is there a more optimal way to structure the mysqli_fetch_array statement?
Change to...
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' . htmlspecialchars($row['location']) . '</option>';
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' . htmlspecialchars($row['location']) . '</option>';
But what have you tried so far?
Try this way (more info here)
$result = $mysqli->query($query)
while($row = $result->fetch_assoc()) {
}

Pre-filling select tags from array

I've got this array:
$profession_type = array(
'Professional Engineers',
'Accountants',
'Insurance Professionals',
'Attorneys',
'Certified Hazardous Materials Managers',
'Safety Professional',
'Industrial Hygienists',
'IT Professionals',
'Human Resource'
);
I am display the contents of the array as the options for the select tag:
<select name="profession_type[]">
<option value=""></option>
EOL;
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
print <<<EOL
</select>
I've never pre-filled a drop down box with dynamic values. The values in $profession_type will change frequently (and will eventually be driven from a table in the db), so I can't do hard code it.
EDIT: Sorry my question was unclear.
The user will select a value from a previous screen (say it's called id) and hit submit.
Before the HTML is rendered to the screen, PHP makes a stored procedure call based on the id they selected.
The values that the stored procedures returns will prefill the "profession_type[]" form field.
I would like the <option value='accountants' selected>Accountants</option> if the stored procedure returns "Accountants" for the value of "profession_type" based on the id.
Is that more clear? Sorry.
Any suggestions?
How about this:
print '<select name="profession_type">';
print '<option value=""></option>';
foreach ($profession_type as $p)
{
if ($p == $chosen_profession)
print "<option value='" . $p . "' selected='selected'>" . $p . "</option>";
else
print "<option value='" . $p . "'>" . $p . "</option>";
}
print '</select>';
This goes in your .php file:
<!-- some HTML here -->
<?php
$profession_type = [result_from_database_query] ?>
<!-- more HTML here -->
<select name="profession_type">
<?php
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
?>
</select>

Method for initializing selectmenu to certain value?

I have a screen that shows users a list of players and the grades users have given them. By clicking on a button, they can select from a list of players and grade these players themselves.
I want to streamline this process by allowing users to simply click on a player name where it goes to the grading page with the select menu already initialized to the player's name that they just clicked on.
Is there a way to initialize a select menu to a certain value?
Here is the mySQL query:
$query = #mysql_query('SELECT person.firstname, person.lastname, person.id FROM person inner join player ON player.person_id=person.id WHERE player.team_id=' . $homeid . ' ORDER BY lastname asc');
And the code that creates the select menu:
<select name='id'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";
}
?>
</select>
of course ,,, The option you want to be selected should contain the attribute selected
if //bla bla this is the one
echo "<option selected=\"selected\" value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";
else
echo "<option value=" . $temp['id'] . ">" . htmlspecialchars($temp['firstname']) . " " . htmlspecialchars($temp['lastname']) . "</option>";
if (currentId == $temp['id']) <option selected>...</option>
else <option>...</option>
If you have a value called $id you can:
echo '<option value="'.$temp['id'].'" '.($temp['id'] == $id ? 'selected="selected"' : '').'>'.htmlspecialchars($temp['firstname']).' '.htmlspecialchars($temp['lastname']).'</option>';
Difference:
($temp['id'] == $id ? 'selected="selected"' : '')
The selected attribute on a preselects this value upon loading the page.
I Hope understood your question.

PHP MySQL Drop Down Box Populate Selected Value

I have read tutorials about how to populate an entire Drop down list with MySQL, but the problem I am running into is that I only want to grab the one from the database and have that be the selected one. So I would have like a drop down with three items (Item1, Item2, Item3) in the database its stored in a column called itemschoice which has a value of 'Item2'. How do I go about getting item2 to be selected when I load the drop down box?
In your <option> element add the selected attribute for the value that is in itemschoice.
Crude example using a made up function to get the choice:
$choice = get_items_choice();
$results = mysqli_query($sql);
echo '<select name="whatever">';
while($row = mysqli_fetch_array($results)) {
if ($row['choice'] === $choice) {
echo '<option value="' . $choice . '" selected="selected" />';
} else {
echo '<option value="' . $choice . '" />';
}
}
echo '</select>';
This is just an example, don't copy & paste this without adding some kind of error verification!

Categories