Jump to content

Dynamically populating a drop down list via PHP


colafran

Recommended Posts

I am new to PHP, bear with me :)

 

I am looking to populate a drop down list by doing a MySQL query using PHP. I found a code example, but it does not seem to work, can anyone tell me if there is something wrong with it? The posting I saw was from 2005, so I am wondering if the code is incompatible with PHP5?

 

Before you ask, I know that my database query is working, I cut and pasted it from another script that is working.

 

Another thing, the drop down does show 5 spaces, which it should be because the sql query is returning only 5 records, but the spaces are blank.

 

 

This is the exact code I have:

 

 

<?php

// Connect and select a database

mysql_connect("localhost", "root", "");

mysql_select_db("addressBook");

 

// Run a query

$result = mysql_query("SELECT * FROM colleague");

?>

 

<!- HTML form opening tags -->

<form action="action" method="post">

<select name="option">

 

<?php

//for each row we get from mysql, echo a form input

while ($row = mysql_fetch_array($result)) {

echo "<option value=\"$row[value]\">$row[title]</option>\n";

}

?>

 

<!- HTML form closing tags -->

</select>

<input type="submit">

</form>

 

Try running this code and see what you get:

 

<?php
// Connect and select a database
mysql_connect("localhost", "root", "");
mysql_select_db("addressBook");

// Run a query
$result = mysql_query("SELECT * FROM colleague");

if (mysql_num_rows($result) > 0){

   echo '<form action="action" method="post">'
            .'<select name="option">';

   //for each row we get from mysql, echo a form input
   while ($row = mysql_fetch_array($result)) {
      echo "<option value='{$row['value']}'>{$row['title']}</option>\n";
   }
   
   echo '</select>'
       .'<input type="submit">'
       .'</form>';
   
} else {
   echo "No results found"
}
   
?>

 

Also, make sure the rows "value" and "title" exist in the database. It sounds like it's returning the results, but there are no such rows.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.