Link to home
Start Free TrialLog in
Avatar of Sim1980
Sim1980

asked on

PHP printf to display drop down list

Hi all.

I have the code below that populates a drop down list with the values from the Lot field in my table. I want to insert a blank as the first entry and then the values for the Lot field. Any idea how I can do this?

Example:

<blank>
Lot1
Lot2
Lot3

Currently it displays like this:
Lot1
Lot2
Lot3

Again, I want to be able to add a <blank> entry first, or even a message like "Choose a lot".

Thank you in advance!

foreach ($data1 as $row){
  printf("<option>%s</option>", html_escape($row['Lot']));
 
}

Open in new window

Avatar of Gary
Gary
Flag of Ireland image

Why not...

echo "<option></option";
foreach ($data1 as $row){
  printf("<option>%s</option>", html_escape($row['Lot']));
} 

Open in new window

Avatar of Sim1980
Sim1980

ASKER

That didn't work.
Avatar of Sim1980

ASKER

I tried

printf("<option selected></option><option>%s</option>", html_escape($row['Lot']));

Open in new window


But that puts a blank before EVERY $row['Lot']. I just want it once in the first drowndown box row.
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sim1980

ASKER

That was it! Thanks.
printf("<option selected></option>");
foreach ($data1 as $row){
 printf("<option>%s</option>", html_escape($row['Lot']));
}

Open in new window

No points, just pointing out a slight typo in Gary's code - missing closing >

echo "<option></option>";
foreach ($data1 as $row){
  printf("<option>%s</option>", html_escape($row['Lot']));
}

Open in new window

There's no reason why it wouldn't work, so if it doesn't, show use the HTML output you do get (and don't forget to wrap the whole thing in a SELECT)
:o/
p.s.
You don't need selected - the first option will always be selected unless you specify another option with selected.