2015-08-27 42 views
1

我正在爲PHP表單驗證創建一個函數。這個想法是,如果用戶沒有填寫必填字段(例如,如果名稱爲「name」的$_POST爲空),則用戶將被警告。

這個功能似乎並不不過工作,:

function addError($x) { 
    if (!$_POST["$x"]) { 
     $error.="Please enter your $x"; 
    } 
} 

echo $error; 

我已經分離出的問題,下至說法$x的傳球爲$_POST,即這條線:

if (!$_POST["$x"]) { 

具體而言,$_POST["$x"]。這是傳遞參數的正確方式/語法嗎?

謝謝!

+0

'$ error'將走出'scope'的。 –

回答

0

使$error成爲全局變量。

2

您的代碼應該是這樣的 -

$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 
0

試試這個.....

<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); 
?> 
0

試試這個: -

$error = ""; 
function addError($x) 
{ 
    global $error; 
    if ("" == $_POST['"'.$x.'"']) 
    { 
     $error.="Please enter your".$x; 
    } 
} 
addError("name"); 
echo $error; 
0

我上面兩個答案引用並寫一些代碼爲這個問題。它在我測試時有效。你可能會對你的編碼有一些想法。 這是我的測試代碼。

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>