How to add a blank selection to a PHP dropdown query? - php

In the dropdown created, it auto selects the first employee name from the list. And when a different employee is selected, the page refreshes with the first employee on the list selected again. Is there a way to make the default selection a blank?
$sql = "SELECT name FROM employee";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) { unset($name); $name = $row['name'];
echo '<option value="'.$name.'">'.$name.'</option>'; }

add default value, like:
while ($row = $result->fetch_assoc()) { unset($name); $name = $row['name'];
echo '<option value="'.$name.'"'.($isDefaultValue ? "selected":"").'>'.$name.'</option>'; }
you need to create $isDefaultValue variable which determines if given record is default, or if you want to create first blank entry use:
echo '<option value="-1" selected>This is only default value, pick real one!</option>';
and then check in your controller if user picked 'default' -1 value or real one

Related

store the id of a row on the option selected list from mysql

I'm echoing a list of attributes of a row from a table into an option list for the user to pick from which later would be used to be inserted into another table. What I'm trying to do is, to store the 'id' of that row -not using the foreign key- separately, but the 'id' I keep getting is the 'id' of the last row on the list. Here is a snippet to my code:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'database');
$result = mysqli_query($conn, "SELECT * FROM myTable WHERE region = '{$thisRegion}' ");
//$result .= " ");
while ($row = mysqli_fetch_assoc($result))
{
$selected = (isset($_POST['list']) && $_POST['list'] == $row['id']) ? 'selected' : '';
echo "<option value='$row[streetAddress] $row[apt] $row[city] $row[zip] $row[_state] $row[country]' $selected >$row[city] $row[zip] $row[_state] $row[country] $row[streetAddress] $row[apt]</option>";
$thisId= $row['id'];
$_SESSION["thisId"] = $thisId;
}
?>
</select>
Your problem it's on the code
while ($row = mysqli_fetch_assoc($result))
{
...
$thisId= $row['id'];
$_SESSION["thisId"] = $thisId;
}
That code means that on each iteration, $_SESSION["thisId"] will be replaced with the id of the current row, making it so that at the end of the loop only the last row's ID will be there.
The way I think to do this would be to add the id to the option, and print the row just as display.
echo "<option value='{$row['id']}'> {$row['apt']} {$row['city']}... </option>";
Then, the receiving page could read
$selectedRowId = $_GET['optionKey']
I hope that helps, you should read more about php and forms moving forward as it will make your coding easier. Here is one basic tutorial http://www.w3schools.com/php/php_forms.asp

Default value for select element from PHP

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>';
}

Dropdown menu not displaying change when I change product

I want to access the value selected by user for further processing.
Hence I am using post method to pass the values of whole form.
But GET to access cust_id so that I can reflect change in
further parts of my form. Hence I had to post the following line:
<select id='fullname' onChange="window.location='sp_menu.php?product='+this.value" name='fullname'>
outside php code. But now, once I select some option from dropdown menu, URL changes accordingly, but dropdown menu does not reflects the change
<?php
$query = "SELECT Cust_id, Cust_Name, Cust_City FROM Customers";
$result = mysql_query($query);
?>
<select id='fullname' onChange="window.location='sp_menu.php?product='+this.value" name='fullname'>
<?php
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['Cust_id'].'">'.$row['Cust_Name'].','.$row['Cust_City'].'</option>';
}
echo '</select>';
?>
How can I, in the same form, access the address of the particular customer id from database when user selects customer name from this dropdown menu?
I think you mean when you change dropdown, the value is not retained, it obviously won't be because your page is being refresh, you need to GET the value from url and put a selected attribute to have that value selected.
Do it this way:
<?php
$query = "SELECT Cust_id,Cust_Name,Cust_City FROM Customers" ;
$result = mysql_query($query);
//checking if GET variable is set, if yes, get the value
$selected_option = (isset($_GET['product'])) ? $_GET['product'] : '';
//we will store all the dropdown html code in a variable and display it later
$select = "<select id='fullname' onChange=\"window.location='sp_menu.php?product='+this.value\" name='fullname'>";
while($row = mysql_fetch_assoc( $result )) {
//checking if the cust_id matches the GET value,
//if yes, add a selected attribute
$selected = ($selected_option==$row['Cust_id'])?'selected':'';
echo '<option value="'.$row['Cust_id'].'"'. $selected. '>' . $row['Cust_Name'] .' , '.$row['Cust_City']. '</option>';
}
$select .= '</select>';
//display the dropdown
echo $select;
?>

Save in the database values of dropdown

I'm making a dropdown, and I want when the user select one values, save to the database.
This is my code:
$query = mysql_query("SELECT name FROM store_locator_bundes");
echo '<select name="bundesland-dropdown">';
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';
And the conditional
if($_POST[$criteria['submit']['name']]) {
// here I am lost, I have to insert the values of the dropdown to store_locator and the field bundes_id
}
Thanks for you help ;)
You want
$_POST['bundesland-dropdown']; // You want the <select> not the <options>'s name
Then for the insert:
if (isset($_POST['bundesland-dropdown'])){
//mysqli/PDO/whatever database method of insertion you want here
}

Showing current value in DB in a drop down box

this is my code which populates a drop down menu, all working perfectly, but when editing a database record, i want the first value in the drop down to be what is currently in the database, how would i do this?
<li class="odd"><label class="field-title">Background <em>*</em>:</label> <label><select class="txtbox-middle" name="background" />
<?php
$bgResult = mysql_query("SELECT * FROM `backgrounds`");
while($bgRow = mysql_fetch_array($bgResult)){
echo '<option value="'.$bgRow['name'].'">'.$bgRow['name'].'</option>';
}
?>
</select></li>
You would set the selected="selected" attribute on the relevant <option>. Presumably there would be some sort of check in your while loop, checking against the variable that contains the current value.
You can do like:
$counter = 1;
while($bgRow = mysql_fetch_array($bgResult)){
if ($counter === 1)
{
echo '<option value="'.$bgRow['name'].'" selected="selected">'.$bgRow['name'].'</option>';
}
else
{
echo '<option value="'.$bgRow['name'].'">'.$bgRow['name'].'</option>';
}
$counter++;
}
As can be seen I have added selected="selected" for you so it will work automatically for you :)
Correct me if I'm wrong, I believe that you have another database table which holds the selected background (e.g. users table with background field), you need to do a query to get the background from the other table and add selected="selected" attribute to the option tag of the background, please check the code below (hope it helps):
<?php
$result = mysql_query("SELECT `background` FROM `users` LIMIT 1");
$myBg = mysql_fetch_array($result, MYSQL_ASSOC);
$bgResult = mysql_query("SELECT * FROM `backgrounds`");
while($bgRow = mysql_fetch_array($bgResult)){
if($myBg['background'] == $bgRow['name'])
echo '<option value="'.$bgRow['name'].'" selected="selected">'.$bgRow['name'].'</option>';
else
echo '<option value="'.$bgRow['name'].'">'.$bgRow['name'].'</option>';
}
?>

Categories