termlim
termlim

Reputation: 1165

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

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

Upvotes: 0

Views: 122

Answers (1)

bestestefan
bestestefan

Reputation: 871

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

Upvotes: 1

Related Questions