我在PHP中验证表单选择列表(下拉列表)时遇到了一个奇怪的问题。在我的HTML中,当我使用0(零)作为<option>
值并在PHP中,检查传入值是否等于0然后不提交表单,那么表单即使我也没有提交选择其他<option>
值,例如“德里”而不是0.这是我的HTML和PHP代码,可以更好地解释你:
HTML
<form name="form1" method="get" action="">
<table width="50%" border="0" align="center">
<tr>
<th><label for="selcity">City:</label></th>
<td><select name="selcity" id="selcity">
<option value="0">Select Your City</option>
<option value="Chandigarh" <?php if($city == "Chandigarh") echo "selected='selected'"; ?> >Chandigarh</option>
<option value="Delhi" <?php if($city == "Delhi") echo "selected='selected'"; ?> >Delhi</option>
<option value="Shimla" <?php if($city == "Shimla") echo "selected='selected'"; ?> >Shimla</option>
</select></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="btnsubmit" value="Submit" /></td>
</tr>
</table>
</form>
PHP
<?php
// Default form values
$city = NULL;
if(isset($_GET['btnsubmit']))
{
$city = $_GET['selcity'];
$errors = array();
if($city == 0)
{
$errors[] = "Please select your city.";
}
if(count($errors) == 0)
{
// Do some mysql queries for saving data in table
echo "You are registered.";
}
else
{
$error_list = "<div id='error'><strong>There are following errors with this form:</strong><ul>";
foreach($errors as $error)
{
$error_list .= "<li>" . $error . "</li>";
}
$error_list .= "</ul></div>";
echo $error_list;
}
}
?>
但是,当我将HTML代码更改为
时<option value="">Select Your City</option>
和PHP代码
if($city == "")
{
$errors[] = "Please select your city.";
}
然后问题就解决了。为什么呢?