如何查询查询确认

时间:2014-10-04 12:43:05

标签: php html mysql

我尝试制作登录脚本,但我停止了输入值的验证。这是我的html代码表单login.php:

<form method="post" action="loginpro.php">
Username:
<input id="field" type="text" name="username" required>
User email:
<input id="field" type="text" name="email" requerid>
Password:
<input id="field" type="password" name="password" required>
<input id="button" type="submit" value="Log in">
</form>

这是我的loginpro.php文件:

<?php if(isset($_POST['username']) && $_POST['username'] !== '' && isset($_POST['email']) && $_POST['email'] !== '' && isset($_POST['username']) && $_POST['username'] !== ''){
require("../admin/libsec/connect.php"); 
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_passoword = hash('sha384', $password);
$query = "SELECT * FROM user WHERE username = '{$username}' AND email = '{$email}' AND password  '{$hashed_passoword}';";
$result = mysqli_query($con,$query);
// How to check if is query good so i can set session or if is not good to redirect to another page?
}
?>

2 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用num_rows()查看您的查询是否产生了行:

<?php 
session_start();
if(
    (isset($_POST['username']) && $_POST['username'] !== '') && 
    (isset($_POST['email']) && $_POST['email'] !== '') && 
    (isset($_POST['username']) && $_POST['username'] !== '')
){

    require("../admin/libsec/connect.php"); 
    $username = $con->real_escape_string($_POST['username']);
    $email = $con->real_escape_string($_POST['email']);
    $password = $con->real_escape_string($_POST['password']);
    $hashed_passoword = hash('sha384', $password);
    $query = "SELECT * FROM user WHERE username = '{$username}' AND email = '{$email}' AND password = '{$hashed_passoword}';    ";
    $result = mysqli_query($con,$query) or die(mysqli_error($con));
    // How to check if is query good so i can set session or if is not good to redirect to another page?

    if(mysqli_num_rows($result) > 0) {
        // user found
        $_SESSION['logged_in'] = true;
        header('Location: home.php');
    } else {
        // redirect the user back to login
        header('Location: login.php');
    }
}

?>

旁注:顺便说一句,既然您正在使用mysqli,为什么不使用预先准备好的语句。

答案 1 :(得分:0)

假设您的用户名是唯一的,您将返回一个或没有结果行。 如果你没有得到,凭证是错误的,如果你的结果有一行他们是对的。

不要使用字符串连接来创建SQL查询!这是一个很大的安全风险。哈比看看Prepared Statements而不是。