否则if语句的一部分总是在if(mysql_num_rows($ result)> 0){

时间:2014-10-20 12:12:15

标签: php mysql forms if-statement login

我创建了一个登录表单无法让它工作。

我的select语句是正确的(适用于数据库),$ query的echo解析了以下内容(例如)

SELECT * FROM users WHERE email = 'test@test.com' AND password = password

但是在它下面的if语句中,它总是处理'以下代码

else
 {
 echo "Your login is invalid";
 echo $_POST['username'];
}

完整代码位于

之下
<?php
require_once __DIR__ . ('/../config/init.php');
?>
<!DOCTYPE html>
<html>
<head>
<?php 
    include INCLUDES . 'head_tags.php';
?>
</head>
<body>
<div class='container'>
    <?php
        include INCLUDES . 'header.php';
        include INCLUDES . 'nav.php';
    ?>
    <div class='two-thirds column'>
        <h2>Login</h2>
            <form action='#' method='post'>

            <div>
                <label for="username">Username (E-email address):</label>
                <input type='text' id="username" name='username' placeholder='Username' autocomplete='on' required>
                <label for="password">Password:</label>
                <input type='password' id='password' name='password' placeholder='Password' autocomplete='on' required>
            </div>
            <div>
                <?php
                    if($_POST){

                        $connection = mysql_connect($db['hostname'], $db['username'], $db['password']) or die(mysql_error());
                        mysql_select_db($db['database'], $connection) or die(mysql_error());

                        /*Echo's to check correct data is being used
                        echo $_POST['username'];
                        echo $_POST['password'];*/

                        $email = mysql_real_escape_string($_POST['username']);
                        $query = "SELECT * FROM users WHERE email = '$email' AND password = ".$_POST['password']."";


                        echo $query;

                        $result = mysql_query($query) or die('Query failed: ' . mysql_error() . "<br />\n$query");

                        if (mysql_num_rows($result) > 0) { 
                            echo "You have successfully logged on";
                            }
                        else
                            {
                            echo "Your login is invalid";
                            echo $_POST['username'];
                            }

                    }

                ?>  
            </div>
            <input type='submit' value='submit'>
        </form>
    </div>
</div>
<?php
    include INCLUDES . 'footer.php';
?>

由于

1 个答案:

答案 0 :(得分:0)

密码缺少引号。

$query = "SELECT * FROM users WHERE email = '" . $email . "' AND password = '" . $_POST['password'] . "'";

Real_escape_string()也必须用于密码,当然,你必须哈希密码,现在你的查询不受SQL注入的保护。