MSMC
MSMC

Reputation: 141

While loop print additional empty line

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?

Upvotes: 0

Views: 350

Answers (3)

Codar
Codar

Reputation: 1

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

    }
}

Upvotes: 0

Mahesh Chavda
Mahesh Chavda

Reputation: 593

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

Upvotes: 0

Wojciech Zylinski
Wojciech Zylinski

Reputation: 2035

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

Upvotes: 1

Related Questions