我正在创建一个PHP表单验证函数。其思想是,如果用户没有填写必需的字段(例如,如果称为"name"的$_POST
变量为空),则会向用户发出警告。
这个函数似乎不起作用,但是:
function addError($x) {
if (!$_POST["$x"]) {
$error.="Please enter your $x";
}
}
echo $error;
我已经将问题隔离到将参数$x
传递到$_POST
,即这一行:
if (!$_POST["$x"]) {
具体来说,$_POST["$x"]
。这是传递参数的正确方式/语法吗?
谢谢!
你的代码应该像-
$error = '';
function addError($x, $error) {
if (!$x) { // Check for the data
$error.="Please enter your $x"; // Concatenate the errors
}
return $error; // return the error
}
echo addError($_POST[$x], $error); // Pass the data to check & the error variable
试试这个.....
<form method="post">
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
<?php
$x=$_POST["name"];
function addError($x)
{
if ($x==null)
{
$error="Please enter your name";
}
else
{
$error='';
}
return $error;
}
echo addError($x);
?>
试试这个:-
$error = "";
function addError($x)
{
global $error;
if ("" == $_POST['"'.$x.'"'])
{
$error.="Please enter your".$x;
}
}
addError("name");
echo $error;
我参考了上面两个答案并为这个问题编写了一些代码。我测试过了。您可能会对编码有一些想法。下面是我测试过的代码。
PHP部分
<?php
function check_error($x){
$error = "";
if(isset($_POST[$x]) && $_POST[$x] == ""){
$error = "Please Enter Data";
}
return $error;
}
echo check_error('txt_name');
?>
HTML部分
<!DOCTYPE html>
<html>
<head>
<title> Testing </title>
</head>
<body>
<h1> Testing </h1>
<hr/>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="text" name="txt_name" value="" placeholder="Your name" />
<input type="Submit" name="btn_submit" value="Submit" />
</form>
</body>
</html>
设置$error
为全局变量