sleepypanda
sleepypanda

Reputation: 89

dropdown box has extra blank spaces/vaues

I am grabbing some values from my database and putting them in a dropdown select box. For some reason, there is a blank value after each option, which is weird as my database doesn't contain any blank fields.

<select id="school" name="school_name">
            <option value=0> Choose</option>
            <?php

            $con = mysqli_connect("localhost", "root", "****") or die("error".mysqli_error());
            mysqli_select_db($con, "newprojectdb") or die("error in database".mysqli_error());

            $sql="SELECT school_id, school_name FROM schools";
            $result=mysqli_query($con, $sql);

            while($row= mysqli_fetch_array($result)){
                $school_name=$row["school_name"];
                echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';
            }
            mysqli_close ($con);
            ?>
        </select>

Upvotes: 0

Views: 1678

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

The reason why you are getting a blank space between each value is because of the last <OPTION> which the closing / was missing and should have been closed like this </OPTION>

I also noticed you escaped the single quotes for

echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';
                    ^^            ^^                  ^ missing the / slash

which would not have echo'ed the value in HTML source but the variable itself $school_name

Sidenote: Variables are not parsed properly when set inside single quotes which is what you were doing in escaping the single quotes.

Example:

<OPTION VALUE='$school_name'>

Change it to:

echo '<OPTION VALUE="'.$school_name.'">'.$school_name.'</OPTION>';

and it will work.

You can also do it this way: (escaping the double quotes for VALUE instead).

echo "<OPTION VALUE=\"$school_name\">".$school_name."</OPTION>";

Footnotes

For cleaner and more readable HTML, use a concatenated . "\n" at the end like this:

echo "<OPTION VALUE=\"$school_name\">".$school_name."</OPTION>" . "\n";

which will produce something like:

<OPTION VALUE="St-Alexander">St-Alexander</OPTION>
<OPTION VALUE="St-Peter">St-Peter</OPTION>
<OPTION VALUE="St-John">St-John</OPTION>

instead of

<OPTION VALUE="St-Alexander">St-Alexander</OPTION><OPTION VALUE="St-Peter">St-Peter</OPTION><OPTION VALUE="St-John">St-John</OPTION>

Upvotes: 5

Gunaratnam
Gunaratnam

Reputation: 1

Pleae find changes you need. Thanks

CHANGE

echo '<OPTION VALUE=\'$school_name\'>'.$school_name.'<OPTION>';

TO

echo "<option value=\"$school_name\"> $school_name </option>";

Upvotes: 0

Related Questions