我正在做php表单,而else语句只是输出

时间:2016-09-22 15:20:31

标签: php forms if-statement

这里是代码 - 我不知道问题在哪里......

我的表格:

  <form action="process1.php" method="post" >   
    first name : <input type="text" name="first name" value="" />
    password : <input type="password" name="pasword" value= "" />
    <br/>
    <input type="submit" name="submit" value="submit" />
    </form>

process1.php

    <?php
    $users = array("abhishek","alan" ); # was doing to limit the users  
    if (firstname == $users ){
        $firstname = $_post['firstname'];
        $password  = $_post[ 'password'];
        echo "$firstname" . "and". "$password"; 
    }else { 
        echo "access denied";
    } 
     ?>

即使我输入abhishek或alan,输出显示access denied

Notice: Use of undefined constant firstname -  
assumed 'firstname' in F:\wamp\www\php_sandbox\process1.php on line 9     
access denied

2 个答案:

答案 0 :(得分:0)

在您的表单中,您将输入命名为“名字”,但在您的php中,您将其搜索为“firstname”(空格)。

另外,将$ _post更改为$ _POST;和你的if子句,你需要将$添加到名字,并声明它。

表格

<form action="process1.php" method="post" >   
    first name : <input type="text" name="firstname" value="" />
    password : <input type="password" name="password" value= "" />
    <br/>
    <input type="submit" name="submit" value="submit" />
</form>

PHP

<?php
$firstname = $_POST['firstname'];
$users = array("abhishek","alan" ); # was doing to limit the users
if (in_array($firstname,$users) )
{
 $password  = $_POST['password'];
 echo "$firstname" . " and ". "$password";
}else {
 echo "access denied";
}
?>

答案 1 :(得分:0)

我知道我不应该因为这么低的质量而回答这个问题 - 但是向别人解释(一次又一次)也许有帮助

错误Notice: Use of undefined constant firstname - assumed 'firstname'无法更清楚,firstname不是变量。你的意思是$firstname,但你也想在使用它之前从POST数据中定义它。

参见逐行评论:

$users = array("abhishek", "alan"); // Creates an array
if (firstname /* "firstname" */ == $users) { // You're comparing a string to an array
    $firstname = $_post['firstname']; // You're defining the variable after you've used it, assuming corrected above
    $password  = $_post[ 'password'];
    echo "$firstname" . "and". "$password"; // Here you're concatenating three strings needlessly
}else { 
    echo "access denied";
} 

这是更有效的代码,LbL:

解释道
$users = array("abhishek", "alan"); // Define array
$firstname = $_POST['firstname']; // Create $firstname from POSTed data
$password  = $_POST[ 'password']; // Create $password from POSTed data
if (!empty($firstname) && in_array($firstname, $users))
{ // Check if $firstname has a value, and also is IN the array
    echo "$firstname and $password";  // Variables are automatically placed in double quoted strings
} else {
    echo "access denied";
}

您还需要更正HTML输入字段以使用正确的名称:

first name : <input type="text" name="firstname" value="" />
password : <input type="password" name="password" value= "" />

我建议在继续阅读之前阅读更多关于PHP /编程的内容,因为如果你在此基础上建立一个非常不安全的系统。