如何在PHP中保持表单提交后下拉列表中所选项目的值


How to keep the value of selected item of a drop down after form submission in PHP?

我只是在用PHP构建一个简单的搜索页面。我需要知道如何在提交表单时保留下拉列表的select值。当前,该值重置为第一个索引。

我可以在不使用客户端脚本的情况下通过PHP实现这一点吗?

这是代码:

<?php
mysql_connect('localhost','root','');
mysql_select_db('hotel');
$sql = "SELECT * FROM customers";
$result = mysql_query($sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>

<form method="get">
<select name="field" id="field">
<?php
 /*if($field == 'Active')
 'selected="selected"';
 */
 while($rows = mysql_fetch_array($result))
    echo '<option>'.$rows['customer_id'].'</option><br>';
?>

</select>

<?php

if (isset($_GET['Search']) && $_GET['action']=='search')
{


  $sql="SELECT * FROM customers WHERE customer_id=".$_GET['field'];
   $result = mysql_query($sql);
   $row = mysql_fetch_assoc($result);
   echo '<br>Customer Name: '.$row['customer_name'].'<br>';
   echo 'Email Address: '.$row['Email_Addr'].'<br>';
   echo 'Contact No: '.$row['Contact_No'].'<br>';   
}

?>

<input type="hidden" name="action" value="search" />
<br><input type="submit" value="search" name="Search" onclick="" />
</form>
</body>
</html>

通常是这样的。

echo '<option';
if ($_GET['field'] == $rows['customer_id']) echo " selected";
echo '>'.$rows['customer_id'].'</option>';

请不要使用mysql_*函数编写新代码,尤其是在学习时。mysql_*函数正在被弃用,它们将在未来的PHP版本中被删除。请改用mysqli_*或PDO对象。

您可以检查get值是否与select值相同:

while($rows = mysql_fetch_array($result))
    echo '<option value="'.$rows['customer_id'].'" '.($rows['customer_id'] == $_GET['field']?'selected="selected"':'').'>'.$rows['customer_id'].'</option><br>';

打印选择选项时,您可以检查值并将任何数学选项设置为选中,可能如下所示:

while($rows = mysql_fetch_array($result)){
    if(!empty($_GET['field']) && $_GET['field'] == $rows['customer_id']){
        echo '<option selected="selected">'.$rows['customer_id'].'</option><br>';
    }
    else {
        echo '<option>'.$rows['customer_id'].'</option><br>';
    }
}