...

View Full Version : Dynamically filled select form



blueuniverse
07-23-2008, 07:05 PM
I have a piece of code


$result = mysql_query("SELECT * FROM category")
or die(mysql_error());

echo "<select name='catid' id='catid'>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<option value='".$row['id']."'>";
echo $row['category'];
echo "</option>";
echo "\n";

This is fine for an upload form (where I've got it from) but not for an edit form. I need it to haev selected=selected by the option that matches my category id.

Just for reference the outputted html of the above is


<select name='catid' id='catid'><option value='1'>Cat1</option>
<option value='2'>Cat2</option>
<option value='3'>Cat3</option>
<option value='4'>Cat4</option>
</select>

My script is getting the recordid and calling it $id

It's then doing a sql select


$sql = "SELECT * FROM library WHERE id=$id";


I want it to grab the catid from this (catid being a field in the table) and then add selected=selected in the initial code I posted.

Thanks in advance,
Ed

Fumigator
07-23-2008, 07:35 PM
Do you have the correct value in $id at the time you build your <select> tag? If so, simply add "if" statements to each iteration of your loop to check $id against what's just been selected from your category table and if it matches, echo the selected="selected" text.

A popular way to do this is to use the ternary form of an "if" statement:



echo "<option value='".$row['id']."' " .($row['id'] == $id ? "selected='selected'" : "") . ">";


http://us.php.net/ternary (page down a bit)

scoop_987
07-23-2008, 10:08 PM
erm... do you have the cat id in the url as the query string?

otherwise it would be as simple as:



$result = mysql_query("SELECT * FROM category")
or die(mysql_error());

echo "<select name='catid' id='catid'>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
if($_GET['cat_id'] == $row['id']){
echo "<option value=\"".$row['id']."\" selected=\"selected\">";
}else{
echo "<option value=\"".$row['id']."\">";
}
echo "<option value='".$row['id']."'>";
echo $row['category'];
echo "</option>";
echo "\n";
}

oesxyl
07-23-2008, 10:22 PM
if you want the result as $row['xxxxxx'] you must use mysql_fetch_assoc instead of mysql_fetch_array

regards

Iszak
07-23-2008, 10:29 PM
oesxyl no you don't have to use mysql_fetch_assoc compared to mysql_fetch_array... you can add a parameter to use number or association or both and by default array is both If I recall. So he doesn't need to use mysql_fetch_assoc compared to mysql_fetch_array.

http://www.php.net/mysql_fetch_array - Should check it out oesxyl.

Edit: I might add that it is faster but by no means MUST he use it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum