GOAL :尝试确保没有任何字段留空,包括单选按钮设置和下拉列表。任何人吗?
HTML
<form action="add_p_c.php" method="post">
Professor<input type="radio" name="addType" /> Course<input type="radio" name="addType" />
<br><br>Name: <input type="text" name="name" /><br>
Department: <select name="deptName"><option>Department 1</option> <option>Department 2</option></select>
Email: <input type="text" name="email" /><br>
<input type="submit" name="submit" />
</form>
** PHP(add_p_c.php)**
<?php
if (isset($_POST['submit'])) {
if (empty($selected_radio)){ echo "You need to select a prof or course";} else(return;)
$selected_radio = $_POST['addType'];
if (empty($course_prof_name)){ echo "You need to enter a name";} else(return;)
$course_prof_name = $_POST['name'];
if (empty($select_dep)){ echo "You select a dept";} else(return;)
$select_dep = $_POST['deptName'];
$email = $_POST['email'] = "myemail@email.com";
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
return;
}
else {
echo "<span color='red;'>Invalid email address.</span>";
}
}
?>
答案 0 :(得分:0)
您可以使用if (empty($variable)) {
,请记住,任何评估为false的内容(包括数字0)都会被捕获。
答案 1 :(得分:0)
按字面意思检查:
if($_POST['foo'] === ""){
答案 2 :(得分:0)
为了安全起见,您应该添加某些内容以提高安全性,因为如果您对数据库执行任何查询,则可以获得SQL注入。试试这个:
<?php
if(isset($_POST['submit']){
$_POST['name']= trim(strip_tags(addslashes($string)));
$_POST['deptName']= trim(strip_tags(addslashes($string)));
$_POST['email']= trim(strip_tags(addslashes($string)));
/* I can't remember if it should be '' or NULL, but some simple testing will let you know which it is*/
if($_POST['addType'] != ''){
if($_POST['name'] != ''){
if($_POST['deptName'] != ''){
if($_POST['email']) != ''){
$selected_radio = $_POST['addType'];
$course_prof_name = $_POST['name'];
$select_dep = $_POST['deptName'];
$email = $_POST['email'] = "myemail@email.com";
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
return;
}
else {
echo "<span color='red;'>Invalid email address.</span>";
}
}
else{
// email wasn't set
}
}
else{
//deptName wasn't set
}
}
else{
//name wasn't set
}
}
else{
// add type wasn't set
}
}
?>
答案 3 :(得分:0)
如果您要使用特别大的表单,可能需要查看使用数组和for循环。当我构建了30个字段数组时,嵌套一系列if语句变得非常笨拙,非常快。
我建议你写一个像
这样的快速功能function validatePost($checkValues)
{
foreach($checkValues as $value)
{
$checked = 0;
foreach($_POST as $key => $value)
{
if($key == $checkValues)
{
$checked = 1;
if(empty($value))
{
return false;
}
}
}
if($checked == 0)
{
return false;
}
}
}
请记住,这不包括任何正则表达式检查,但您可以在中间的foreach循环中添加它。然后在你的代码中排成行,你可以调用该函数:
$checkValues = array('addType', 'deptName', 'email', 'name')
$return = validatePost($checkValues);
if($return == false)
{
echo "<span color='red;'>Please fill out entire form.</span>"
}
else
{
return;
}
显然,您可以添加功能以使其更加详细,但这是一个非常基本的验证,可以扩展。