为什么我的代码没有插入某些表?

时间:2015-02-22 05:51:26

标签: php sql mysqli

我想在每个表中为刚注册的用户创建一行,id必须与users表中的一行相同。我试图使用$mysqli->insert_id方法,但它没有用。代码只有INSERT INTO我的用户表...有人能告诉我我的代码有问题并解释$mysqli->insert_id吗? :(

感谢。

PHP代码

<?php
include_once("../init.php");

if (isset($_POST)) {
$username       = trim($_POST['username']);
$password       = crypt(trim($_POST['password']), 'st');
$email          = trim($_POST['email']);
$email_code     = md5($username + microtime());
$insert_stmt = $mysqli->prepare("INSERT INTO users (username, password, email, email_code, created) VALUES (?, ?, ?, ?, NOW())");
$insert_stmt->bind_param('ssss', $username, $password, $email, $email_code);
        if (! $insert_stmt->execute()) {
                header('Location: ../error.php?err=Registration failure: INSERT');
        } else {
            $whatajoke = $insert_stmt->insert_id;   
            $mysqli->query("INSERT INTO login_attempts (id) VALUES ('$whatajoke')");
            $mysqli->query("INSERT INTO personal_detail (id, username) VALUES ('$whatajoke', '$username')");
            $mysqli->query("INSERT INTO ip (id) VALUES ('$whatajoke')");
            //email('htmlemail.php');
            header('Location: ../register_success.php');
        }
}
$mysqli->close();
?>

1 个答案:

答案 0 :(得分:1)

insert_id仅在执行插入查询后才有意义。您之前使用过它。另一个条件是您的表具有自动增量列。

工作原理:PHP将查询发送到mysql,mysql插入行并为自动递增的id列分配值。如果您需要此ID以便稍后在代码中引用新记录,则使用insert_id