开发者

How to print-down list with selected value from database?

Im trying to print drop-down list with a selected value from database. result3 - I choose the 'company name' value from the database which are in the same row as $id2. I need that value to be selected. result2 - I choose all companys names.

result3 = mysql_query("SELECT company.company_id开发者_如何学Go,customer.company_id, customer.customer_id, company.name 
FROM company INNER JOIN customer ON customer.company_id=company.company_id  WHERE customer_id='$id2'") or die(mysql_error());
$row3 = mysql_fetch_assoc($result3);
$result2 = mysql_query("SELECT company_id, name FROM company") or die(mysql_error());
  if(mysql_num_rows($result2) > 0)
  {
    while($row2 = mysql_fetch_assoc($result2))
    {
    echo'<option selected="'.$row3['name'].'" value="'.$row2['company_id'].'">'.$row2['name'].'</option>';
    }
  }

The problem with my code is that every time selected value is last in the list.

I looked at my source code and there is everything all right.

Here is the source code and it is how i needed to be. (but my code returns selected value as 'Facebook' - the last on the list)

<select name="operation">
<option selected="Google" value="1">Microsoft</option>
<option selected="Google" value="2">IBM</option>
<option selected="Google" value="3">Google</option>
<option selected="Google" value="4">Lexy</option>
<option selected="Google" value="5">Facebook</option>   
</select>


The selected attribute should only be applied to a single option in the list.

<option selected="selected">

should cause that single option to be selected.

So in your while loop you need an if statement something like this:

 while($row2 = mysql_fetch_assoc($result2))
 {
     if($row2['name'] == $row3['name']){
          $selected = "selected='selected'";
     }else{
          $selected = "";
     }
     echo'<option ' . $selected . ' value="'.$row2['company_id'].'">'.$row2['name'].'</option>';
}

This way only the value that you want selected will be selected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜