Jump to content

Select category (from MySql) in dropdown box


eevan79

Recommended Posts

I wrote script where user can select categories from dropdown box. But when is $_GET['id'] he can select all categories, and when $_GET['id'] have value he can see current category (from id). I want to have selected current category (where $_GET['id'] have value), but also he can change category.

 

Something like this:

001xcw.jpg

 

and where we have  $_GET['id'] :

002zfd.jpg

Here is my code:

if(empty($_GET['id']))
{
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}    
echo '</select><br />';    }
else
{
echo '<select name="topic_cat">';
$result2 = mysql_query("SELECT cat_id, cat_name, cat_description FROM categories WHERE cat_id = " .mysql_real_escape_string($_GET['id']) . "");
$row = mysql_fetch_assoc($result2);
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
echo '</select><br />';
}

echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
   $selected = (isset($GET_['id'] && $row['cat_id'] == $_GET['id'])? " selected=selected" : NULL;
   echo '<option value="' . $row['cat_id'] . '"'.$selected.'>' . $row['cat_name'] . '</option>';
}
echo '</select><br />';

 

Look at this code logically:

Whether you have an id parameter or not you want every category, the only difference is you want that category specified to be selected already. We can do this with a simple if statement during a generic loop.

 

-cb-

 

Yes, I tried in one loop but without success, and thats why my code is like above.

Anyway, I tried your script and getting following error:

[b]Parse error[/b]:  syntax error, unexpected T_BOOLEAN_AND, expecting ',' or ')' in [b]create_topic.php[/b] on line [b]45[/b]

 

This this line:

$selected = (isset($GET_['id'] && $row['cat_id'] == $_GET['id'])? " selected=selected" : NULL;

 

You put the parenthesis in the wrong place. Look at that line of code, what it does, what it is asking.

 

I'm sure you can figure it out. The php Manual can give you information on specific functions like so:

php.net/isset

 

-cb-

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.