-2

I need the solution on making an option "selected" on some conditions given by $_GET[]. The idea is.

<?
$sql_id="select * from stock order by id asc";
$result_id=mysql_db_query($dbname,$sql_id);
while($rec_id=mysql_fetch-array($result_id)){
  $_id=$rec_id['id'];
  $_title=$rec_id['title'];
if($_GET['id']==$_id){
  echo "<option value=\"$_id\" selected>$_title</option>";
}else{//I need this option selected where id='2'
  echo "<option value=\"$_id\">$_title</option>";
}
?>

The question is : I also need the empty($_GET['id'])=2 as well. Then the conditions would be

  1. Select an option when $_GET['id']==$_id
  2. Select an option from mysql (where stock.id='2') when $_GET['id']==""
4

3 回答 3

0

我现在知道...

<?
//let's test the $_GET['id'] value first
if(!$_GET['id']){
    $_id="2";//if no $_GET['id'] then $_id==2
}elseif(isset($_GET['id'])){
    $_id=$_GET['id'];
}

$sql_id="select * from stock order by id asc";
$result_id=mysql_db_query($dbname,$sql_id);
while($rec_id=mysql_fetch-array($result_id)){
  $_id=$rec_id['id'];
  $_title=$rec_id['title'];
if($_GET['id']==$_id){
  echo "<option value=\"$_id\" selected>$_title</option>";
}else{//I need this option selected where id='2'
  echo "<option value=\"$_id\">$_title</option>";
}
?>

问题解决了!非常感谢您的帮助!

于 2012-09-20T08:56:20.460 回答
0

不知道我是否理解正确,但你为什么不试试这样的:

if($_GET['id']==$_id){
  echo "<option value=\"$_id\" selected>$_title</option>";
}
else if (($_GET['id']=="") && ($_id==2)){//I need this option selected where id='2'
  echo "<option value=\"$_id\">$_title</option>";
}
于 2012-09-20T08:43:06.563 回答
0
<?php
    $query = "SELECT * from `".$dbname."`.`stock` ORDER BY `id` ASC";
    $result_id = mysql_query($query);
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    while($rec_id = mysql_fetch_array($result_id)){
        $sel = '';
        if($rec_id['id'] == $id){
            $sel = " selected='selected'";
        }
        if(!$id && $rec_id['id'] == 2){
            $sel = " selected='selected'";
        }
        echo "<option value='".$rec_id['id']."'".$sel.">".$rec_id['title']."</option>";
    }
?>
于 2012-09-20T08:47:54.303 回答