php格式的表单提交



我的if(isset($_POST['submit']))代码有点问题。我想要的是在单击表单的提交按钮后运行processForm()函数。问题是,当我包含if(isset($_POST['submit']))函数时,当我单击提交按钮时,processFunction()根本不会运行。但当我包含了if( !isset($_POST['submit']))时,processForm()函数会运行。。。为什么会这样,你能帮我解决这个问题吗?

<html>
<head>
<title>Membership Form</title>
<style type="text/css">
.error { background: #d33; color: white; padding: 0.2em; }
</style>
</head>
<body>
<?php 
if ( isset($_POST["submit"])) { //if submit input has value
processForm();//calls the processForm function
}
function processForm(){ 
$compulsaryForm = array("firstName" , "lastName", "password" , "passwordRetype");
$missingFields = array();
foreach ($compulsaryForm as $input) { //loop
if (!isset($_POST[$input])) {
$missingFields[] = $input;
} // forget the else part cause we mainly want to avoid the warning msg
}
if ($missingFields) {
echo "<p>there are missingFields</p>";
}
}
?>
<form action="htmlForms2.php" method="post">
*name:<input type="text" name="firstName"> <br><br>
*last name: <input type="text" name="lastName"> <br><br>
*password<input type="password" name="password"> <br><br>
*retype password<input type="password" name="passwordRetype"><br><br>
male:<input type="radio" name="sex"><br>
female:<input type="radio" name="sex"><br>
favourite food:<select name = "favourite">
<option value="select">select</option>
<option value="rice">rice</option>
<option value="beans">beans</option>
</select><br>
do you want to recieve news letter?<input type="checkbox" name="newsLetter"><br>
Any comments? :<input type="text" name="comments"><br>
<input type="reset" name="reset">
<input type="submit" name="submit" value="submit">
</form>

您的代码在"提交"字段验证方面看起来不错。看起来不太好的是这些线条:

$compulsaryForm = array("firstName" , "lastName", "password" , "passwordRetype");
$missingFields = array();
foreach ($compulsaryForm as $input) { //loop
if (!isset($_POST[$input])) {
...

您正在验证的所有输入都将在提交中发送,因此isset(...)将是true,它们可能为空,但它们肯定会存在。因此,在服务器端或发送表单之前验证您的空性,或者在这两个地方都验证更好,它应该可以工作;(

// Use: count($_POST[$input]) < 5, In case you want to validate the text length 
if ( !isset($_POST[$input]) || empty($_POST[$input]) || count($_POST[$input]) < 5 { 

最新更新