我想在 table1 中提交具有 AUTO_INCREMENT id 的新注册用户,同时在 table2 中插入 mysqli_insert_id 或 LAST_INSERT_ID 任何你想调用的内容。我可以回显 id,但我需要在 table2 中使用它。我怎样才能做到这一点?请帮忙!
这是我的代码供引用:
<?php
if(isset($_POST['submit'])) {
require 'connect.php';
$sql = "INSERT INTO table1 (username, password)
VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
if (mysqli_query($con, $sql)) {
$last_id = mysqli_insert_id($con);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
mysqli_close($con);
}
?>
最佳答案
使用来自(成功的)查询的最后插入的 id 的变量插入到另一个表中。
这是一个粗略的草图,因为我们不知道您的第二个表的数据库架构是什么,而且非常不清楚,因此您需要完成(填写)其余部分。
if (mysqli_query($con, $sql)) {
$last_id = mysqli_insert_id($con);
echo "New record created successfully. Last inserted ID is: " . $last_id;
$sql = mysqli_query($con, "INSERT INTO table2 (col) VALUES ('$last_id')")
or die(mysqli_error($con));
}
密码
我还注意到您可能以明文形式存储密码。不建议这样做。
使用以下之一:
- CRYPT_BLOWFISH
-
crypt()
-
bcrypt()
-
scrypt()
- On OPENWALL
- PBKDF2
- PBKDF2 on PHP.net
- PHP 5.5
password_hash()
功能。 - 兼容包(如果 PHP < 5.5)https://github.com/ircmaxell/password_compat/
其他链接:
关于列长度的重要旁注:
如果您决定使用 password_hash()
或兼容包(如果 PHP < 5.5)https://github.com/ircmaxell/password_compat/ ,重要的是要注意,如果您当前的密码列的长度低于 60,则需要将其更改为该值(或更高)。手册建议长度为 255。
您需要更改列的长度并使用新的散列重新开始才能生效。否则,MySQL 将无提示地失败。
关于php - 使用 PHP 将 mysqli_insert_id 插入单独的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830331/