I am trying to put rows from my database to a select
this is the code,

<select name='network' id='network'>
        <option selected>None</option>
         <?php
          $query = mysql_query("SELECT * FROM `countries` ");
       while($row=mysql_fetch_array($query))
        {
            echo $row['name'].'<br>';
        }
        ?>
        </select>

Recommended Answers

All 5 Replies

Where are you specifying your connection information? Is this all of the relevant code?

you mean if i have a connection with the db?
Yes because when i try

 <?php
          $query = mysql_query("SELECT * FROM `countries` ");
       while($row=mysql_fetch_array($query))
        {
            echo $row['name'].'<br>';
        }
        ?>

the data are return correctly

OK, so you don't have a problem then? Is there anything going wrong or did you just post a code snippet?
Oh wait, I see. Your <option> isn't displaying correctly is it?

you need to echo the actual option tag as well or you're just printing rows to the page as text.

echo '<option>'. $row['name'] . '</option>'

Are you pulling all the countries from your DB? or are their just select contries in your DB

typically I have an array of states or countries before I call this.

$countries = array("list of all the countries");
$country = "USA";

echo '<select name="country">';
foreach($countries as $key => $value){
    echo '<option value="'.$key.'"';
    echo ($key == $country)?' selected="selected"':'';
    echo '>'.$value.'</option>';
}
echo '</select>

Also if you can see I have used a short hand if statement. It is super useful and saves some lines. If you want I can explain it a little more.

thanks hericles i totally forgot it.... thanks very much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.