PHP无法识别何时按下提交按钮?

时间:2017-03-13 22:27:29

标签: php

我只是学习PHP基础知识,我需要创建一个博客。我已经按照了一些教程,但是当我按下我用HTML创建的登录表单时,我似乎无法识别PHP。

<?php
session_start(); //keep a session open so no need to relogin
if(isset($_POST['submit'])){ //check to see if submit button is pressed
    $user = $_POST['username'];
    $pwrd = $_POST['pwrd'];
    //add database connection
    include('./includes/db_connect.php');
    if(empty($user) || empty($pwrd)){
        echo 'Please ensure both password and username fields are filled.';
    }else{
        $pwrd = md5($pwrd);
        $query = $db->query("SELECT user_id, username FROM user WHERE username='$user' AND password = '$pwrd'"); //grab username and password from table
        if($query->num_rows ===1) {
            while ($row = $query->fetch_object()) {
                $_SESSION['user_id'] = $row->user_id;
            }
            header('Location : index.php'); //redirt user to index.php
            exit();
        }else{
            echo 'Wrong credentials';
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
</head>
<body>

<div id="container">
    <form action="login.php" method="post">
        <p>
            <label>Username</label><input type="text" name="username" />
        </p>
        <p>
            <label>Password</label><input type="password" name="pwrd" />
        </p>
        <input type="submit" value="LogIn" />
    </form>
</div>
</body>
</html>

当我在用户名和密码都为空时按下登录时我没有得到任何内容而是&#39;请确保填写密码和用户名字段。&#39;

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:-1)

您正在使用if(isset($_POST['submit'])){进行核对,但名为submit的表单中没有字段。

请尝试使用if ($_SERVER['REQUEST_METHOD'] === 'POST') {。 或者将submit按钮重命名为submit [或其他内容,但请记住修复支票]

答案 1 :(得分:-2)

$ _ POST数据来自&#39; name =&#34; ...&#34;&#39;项目。不输入=&#34; ...&#34;。请注意,只是检查POST是否存在是一种冒险的做法,因为页面上可以有多个表单,所以我总是使用显式检查所需的表单字段来触发表单处理程序。

<?php
session_start(); //keep a session open so no need to relogin
if(isset($_POST['username'])){ //check to see if submit button is pressed
    $user = $_POST['username'];
    $pwrd = $_POST['pwrd'];
    //add database connection
    include('./includes/db_connect.php');
    if(empty($user) || empty($pwrd)){
        echo 'Please ensure both password and username fields are filled.';
    }else{
        $pwrd = md5($pwrd);
        $query = $db->query("SELECT user_id, username FROM user WHERE username='$user' AND password = '$pwrd'"); //grab username and password from table
        if($query->num_rows ===1) {
            while ($row = $query->fetch_object()) {
                $_SESSION['user_id'] = $row->user_id;
            }
            header('Location : index.php'); //redirt user to index.php
            exit();
        }else{
            echo 'Wrong credentials';
        }
    }
}
?>