View Full Version : dynamic list box

01-10-2006, 06:03 PM
hi, i want to add a list box to a form so that users can select a category. The categories are held in a database with two fields, catid, and category.

How can i populate the list so users select the category name, but when it enters the choice it enters the catid...?

Thanks in Advance.

01-10-2006, 06:40 PM
Basically all you need to do is a while() statement in PHP t o go through the categories and output them in the form of a list. Maybe something like:

// MySQL connection a and query above...

$num = mysql_num_rows($result);

echo "<select name=\"category\">\n";

for($i=0; $i<=$num; $i++) {

$catid = mysql_result($result, $i, "catid");
$category = mysql_result($result, $i, "category");

if(isset($catid) && isset($category)) {
echo "<option value=\"" . $catid . "\"> " . $category ."\n";


echo "</select>";

Velox Letum
01-10-2006, 06:46 PM
// Connect to MySQL
$link = mysql_connect('localhost', 'username', 'password');

// Select DB

// Retrieve category data
$query = mysql_query('SELECT * FROM categories');

// Select box preamble
$select = '<select name="category">' . "\n";

// Populate options
while ($row = mysql_fetch_assoc($query) {
$select .= '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>' . "\n";

// Close select tag
$select .= '</select>' . "\n";

echo $select; // Print select box

Now select is populated with the categories, and the value of each category option will be its id.

Aha, Element beat me to the punch while I was writing the code. Either will work.

01-10-2006, 06:50 PM
Aha, Element beat me to the punch while I was writing the code. Either will work.

Haha, speed typing, baby. :thumbsup:

I would probably use Velox code. Mine may run slower. Velox will print the select values all at once, where as depending on where it is int he document and their connection a user might not be able to even use the select box until each category is finnished loading.