无法使用 PHP 将 passwordHash 发送到 MySQL table

Not able to send passwordHash to MySQL table with PHP

我正在使用以下代码

$q = $connection->prepare("INSERT INTO users (firstName, lastName, email, passwordHash) VALUES (?,?,?,?)");

$q->bind_param('ssss', $firstName, $lastName, $email, $passwordHash);

$firstName = trim($_POST['firstName']); 
$lastName = trim($_POST['lastName']); 
$email = trim($_POST['email']); 
//$passwordHash = 'y$Q0Z2OTSOjLqXA3XWscvDxO70GfY0LdQrJ/oUfxty4APU763D0iuJW'; 
$passwordHash = password_hash($_POST['password'], PASSWORD_DEFAULT); 
echo $passwordHash;
$q->execute();
$q->close();

当我使用注释掉的行时,语句会执行并更新 table。当我使用未注释掉的 passwordHash 时,数据库未更新。我需要做些什么来为 INSERT 制作散列 suitable 吗?在 PHP 文档中,password_hash() 中的 return 是一个字符串。

首先,正如我在评论中所述,您应该定义变量 "first",然后是 prepare/execute。你现在所做的可能会产生不利影响,所以它只是 "good practice".

$firstName = trim($_POST['firstName']); 
$lastName = trim($_POST['lastName']); 
$email = trim($_POST['email']); 
//$passwordHash = 'y$Q0Z2OTSOjLqXA3XWscvDxO70GfY0LdQrJ/oUfxty4APU763D0iuJW'; 
$passwordHash = password_hash($_POST['password'], PASSWORD_DEFAULT); 
echo $passwordHash;

$q = $connection->prepare("INSERT INTO users (firstName, lastName, email, passwordHash) VALUES (?,?,?,?)");

$q->bind_param('ssss', $firstName, $lastName, $email, $passwordHash);


if($q->execute()){
   echo "Success!";
} else {
   echo "Error: ". mysqli_error($connection);
}
$q->close();

注意:如果password_hash()由于版本不支持而无法在您的服务器上使用,您将需要为其使用密码兼容包,如手册中所示。

(PHP 5 >= 5.5.0, PHP 7)

用户贡献的注释:

There is a compatibility pack available for PHP versions 5.3.7 and later, so you don't have to wait on version 5.5 for using this function. It comes in form of a single php file: https://github.com/ircmaxell/password_compat

在我打字的时候,我注意到 来自你:

it was running on 5.4, just updated it to use 5.5 will see if this helps. I think the hashing should be working as it does echo a hash?

完全就是这样。 - password_hash() 无法在 PHP 5.4 上使用。参见上面关于密码兼容包的内容。

还要确保密码列的长度足以容纳哈希值。说明书建议255,小于60有问题;太短了。

使用错误处理:(我将其包含在对您的执行的轻微编辑中)。