在提交HTML表单后,$ _POST superglobal不包含预期的数据

时间:2014-05-11 02:05:34

标签: php html forms

<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
$username = $_POST['username'];
print ($username);
?>
</head>
<body>

<form name ="form1" method ="POST" action = "allNewPractice.php">
<input type = "text" value ="username">
<input type = "submit" name = "submit1" value = "login">
</form>
</body>
</html>

正如您可能知道的那样,这个文件的名称是&#34; allNewPractice.php&#34;我用  localhost / allNewPractice.php直接通过我的浏览器访问它,而不是通过记事本++的运行。 它没有任何作用;它应该打印我在文本框中输入的信息到页面但页面没有。当我点击登录按钮时页面只刷新,显示原始文本框和登录按钮,但不显示什么我进入了。 我从http://www.homeandlearn.co.uk/php/php4p6.html获得了教程 我究竟做错了什么? 我的电脑有问题吗?

3 个答案:

答案 0 :(得分:2)

学习基本的HTML表单:

<input type = "text" value ="username">

没有名字的输入不提交任何内容。它应该是

<input type="text" name="username" value="somevalue" />
                   ^^^^^^^^^^^^^^^----must be present.

答案 1 :(得分:0)

首先,您需要在输入框中添加name属性,如下所示:

<input type = "text" value ="username" name="username">

当您致电$_POST['username']时,它会引用名称属性,而不是值。

其次,在发布任何内容之前,您要设置$username的值。这将导致错误undefined variable: username,因为首次加载页面时$_POST['username']不存在。在您提交表单之后,它才会有价值。因此,您需要先检查表单是否已提交:

if (isset($_POST['submit1'])) {
    // Process data from form
}

以下是您的计划的完整且有效的版本:

<?php
    if (isset($_POST['submit1'])) {
        $username = $_POST['username'];
        print ($username);
    }
?>
<html>
    <head>
        <title>A BASIC HTML FORM</title>
    </head>
    <body>

        <form name ="form1" method ="POST" action = "allNewPractice.php">
            <input type = "text" value ="username" name="username">
            <input type = "submit" name = "submit1" value = "login">
        </form>

    </body>
</html>

答案 2 :(得分:0)

试试这个。我个人似乎没有使用post方法,但它的工作原理

<html>
<head>
<title>A BASIC HTML FORM</title>   

<?PHP
if ($_GET['username']) {
$user = $_GET['username'];
echo $user;
}else{
echo "no text";
}
?>
</head>
<body>

<form method ="GET" action = "allNewPractice.php">
<input id="username" name="username" type="text" placeholder="username">
<input type = "submit" id = "submit" value = "login">

</form>
</body>
</html>