0

I have the following while loop, which I used to create a drop-list select containing date fetched from database:

$sql = "SELECT name FROM persons";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}

The while loop prints an additional empty line into the drop list, i.e. there is an empty line appearing in the list. How can I avoid that?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
MSMC
  • 141
  • 1
  • 5
  • 16
  • 1
    Minor side-note: If the value is the same as the displayed text, you can omit the `value` attribute - it will default to the displayed text. `` will yield "John Smith" as its value. – Niet the Dark Absol Apr 14 '16 at 15:59
  • Voted to close - there is a `NULL` or `empty` record in your db. – skrilled Apr 14 '16 at 16:00
  • 1
    Stop using MySQL, [start using MySQLi](http://stackoverflow.com/questions/12020227/updating-from-mysql-to-mysqli) . You will live to enjoy the change :-) – Martin Apr 14 '16 at 16:05

3 Answers3

1

Nothing in this code prints an empty option. Are you sure you don't have a record in your database where name is NULL or empty?

Try adding

WHERE name IS NOT NULL and name != ""

to your query

Wojciech Zylinski
  • 1,995
  • 13
  • 19
0

Sounds like you have empty row in your results from the database. You can check the persons table for this or you could fix it in the code by doing something like the following:

$sql = "SELECT name FROM persons";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
    if (!empty($row['name'])) {
        echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";

    }
}
Codar
  • 1
  • 3
0

Just use PHP empty function like this:

$sql = "SELECT name FROM persons";
$result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
         if(!empty($row['name']))
        {
            echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
        }
}
Mahesh Chavda
  • 593
  • 3
  • 9