在PHP中提交表单后,如何保留下拉列表中选定项的值?

在PHP中提交表单后,如何保留下拉列表中选定项的值?,php,html,Php,Html,我正在用PHP构建一个简单的搜索页面。我需要知道如何在提交表单时保留下拉列表的selecte值。当前,该值重置为第一个索引 我可以通过PHP而不使用客户端脚本吗 代码如下: <?php mysql_connect('localhost','root',''); mysql_select_db('hotel'); $sql = "SELECT * FROM customers"; $result = mysql_query($sql); ?> <!DOCTYPE htm

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

我可以通过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>';
echo'.$rows['customer_id'].';

请不要使用
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\u fetch\u array($result))
回显'.$rows['customer_id'].
';
打印选择选项时,您可以检查值并将任何匹配选项设置为“已选择”,可能如下所示:

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>';
    }
}
while($rows=mysql\u fetch\u array($result)){
如果(!empty($\u GET['field'])&&&$\u GET['field']==$rows['customer\u id']){
回显'.$rows['customer_id'].
'; } 否则{ 回显'.$rows['customer_id'].
'; } }