使用mysqli_escape_string函数获取错误 [英] Getting an error using mysqli_escape_string function

查看:40
本文介绍了使用mysqli_escape_string函数获取错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码,在 mysqli_escape_string($ hash)); 的最后一行出现错误:

I get an error on the last line on mysqli_escape_string($hash)); by using the following code:

$hash = md5( rand(0,1000) );
$stmt = $mysqli->prepare("INSERT INTO users (username, password, hash) VALUES (?, ?, mysqli_escape_string($hash))");
$password = md5($password);
$stmt->bind_param('ss', $username, $password, mysqli_escape_string($hash));

它说 mysqli_escape_string($ hash))是一个非对象.但是,仅使用 $ hash 对此也无济于事

It says, that the mysqli_escape_string($hash)) is a non-object. But using only $hash instead doesn't help either

有人可以帮忙吗?

推荐答案

您的代码有太多错误,将很难通过解决现有问题来提供解决方案.

There are far too many things wrong with your code and will be extremely difficult to provide a solution by fixing what you have now.

首先,不再认为MD5可以安全地用于密码存储.

Firstly, MD5 is no longer considered safe to use for password storage.

咨询:

此外,您没有正确使用准备好的语句.

Plus, you're not using prepared statements correctly.

正如我所说的, mysqli_escape_string()函数需要将数据库连接作为第一个参数传递:

As I stated, the mysqli_escape_string() function requires a database connection be passed as the first parameter:

帮自己一个忙并使用它,这是ircmaxell的回答之一 https://stackoverflow.com/a/29778421/

Do yourself a favor and use this, one of ircmaxell's answers https://stackoverflow.com/a/29778421/

从他的回答中拉出来:

只需使用一个库.严重地.它们存在是有原因的.

Just use a library. Seriously. They exist for a reason.

不要自己做.如果您要创建自己的盐,请您做错了.您应该使用一个可以为您处理的库.

Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.

$dbh = new PDO(...);

$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);

$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);

并且在登录时:

$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
    if (password_verify($_POST['password'], $users[0]->password) {
        // valid login
    } else {
        // invalid password
    }
} else {
    // invalid username
}

这篇关于使用mysqli_escape_string函数获取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆