为了简单起见,我在这里只使用了3个字段,但它应该适用于更大的表单。我试图检查表单是否提交,验证输入,如果输入缺失或无效,显示错误消息,并保持在字段中任何用户已经输入。我使用两个具有相同键的数组,因此我可以检测输入并设置相同键的相关错误。
我的代码是:<!DOCTYPE html>
<html>
<head><meta content="text/html; charset=utf-8" http-equiv="Content-Type" /><title>Test2</title></head>
<body>
<?php
$input = array("name"=>"", "phone"=>"", "email"=>"");
$error = array("name"=>"", "phone"=>"", "email"=>"");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach ($input as $key => &$value) {
$value = test_input($_POST[$key]);
$pregMatch = "'W";
if ($key == "phone") {
$pregMatch = "/^[0-9() ]*$/";
}
elseif ($key == "email") {
$pregMatch = "/([.'-]+'@[.'-]+'.[.'-]+)/";
}
if (in_array($key, array("name", "phone", "email"))) {
if (empty($_POST[$key])) {
$error($key) = $key . " is required"; /* LINE 27 */
}
} /* end if in_array */
if (!preg_match($pregMatch, $value)) {
$error($key) = "Invalid " . $key; /* LINE 32 */
}
} /* end foreach */
} /* end check if form is submitted */
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form name="form1" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ;?>">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="<?php echo $input('name'); ?>"> /* LINE 49 */
<span><?php echo $error('name'); ?></span> /* LINE 50 */
<label for="phone"><span class="red">*</span>Phone</label>
<input type="text" name="phone" id="phone" value="<?php echo $input('phone'); ?>">
<span> <?php echo $error("phone"); ?></span>
<label class="label" for="email"><span class="red">*</span>Email</label>
<input type="text" name="email" id="email" value="<?php echo $input('email'); ?>">
<span><?php echo $error("email"); ?></span>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
出现了三个问题:
1 -致命错误:不能在写上下文中使用函数返回值在…public_html/test2.php第27行。删除了27中的第32行。
2 -如果我注释掉第27和32行,代码将在第49行停止。我的意思是只有文本"Name"会出现。什么之后。没有名为"name"的文本字段,没有电话或电子邮件文本和字段。
3 -如果我在第49行注释掉php代码,我得到:致命错误:函数名必须是第50行…public_html/test2.php中的字符串。这是由第50行php代码引起的。
注意:我已经标记了代码中的行。
我是php新手,如果您能提供任何帮助,我将不胜感激。
使用方括号访问数组键/值。正则括号用于函数:
$error[$key] = $key . " is required"; /* LINE 27 */
第32行也一样。再往下,同样的问题:
<input type="text" name="name" id="name" value="<?php echo $input['name']; ?>"> /* LINE 49 */
<span><?php echo $error['name']; ?></span> /* LINE 50 */
您使用方括号作为$error($key)
,必须更改为$error[$key]
第二个问题在html部分。
您使用的是<span><?php echo $error('name'); ?></span> /* LINE 50 */
必须改为<span><?php echo $error['name']; ?></span> /* LINE 50 */
您在line 53
和line 56
上重复相同的错误