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?

3
  • 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. <option>John Smith</option> will yield "John Smith" as its value. Commented Apr 14, 2016 at 15:59
  • Voted to close - there is a NULL or empty record in your db. Commented Apr 14, 2016 at 16:00
  • 1
    Stop using MySQL, start using MySQLi . You will live to enjoy the change :-) Commented Apr 14, 2016 at 16:05

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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>";

    }
}

2 Comments

This will still print an empty option since isset() will return true as the value may be an empty string. You should use !empty() instead
Doh wasn't paying attention. Updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.