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>

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.