使用 PHP 将mysqli_insert_id插入单独的表中


Insert the mysqli_insert_id inside separate table using PHP

我想在表1中提交具有AUTO_INCREMENT ID的新注册用户,同时在表2中插入mysqli_insert_id或LAST_INSERT_ID您想称呼它的任何内容。我可以回显 id,但我在我的表2 中需要它。我怎样才能做到这一点?请帮忙!
这是我的代码供参考:

<?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()
  • 在开墙上
  • PBKDF2
  • PBKDF2 on PHP.net
  • PHP 5.5 的password_hash()函数。
  • 兼容包(如果 PHP <5.5)https://github.com/ircmaxell/password_compat/

其他链接:

  • PBKDF2 for PHP

关于列长的重要旁注:

如果您决定使用 password_hash() 或兼容包(如果 PHP <5.5)https://github.com/ircmaxell/password_compat/,请务必注意,如果您当前密码列的长度小于 60,则需要将其更改为该长度(或更高)。手册建议长度为 255。

您需要更改列的长度并使用新的哈希重新开始才能使其生效。否则,MySQL 将以静默方式失败。