0
$db->query("INSERT into `users` (username, password, email)
    VALUES ('$username', '$hashpassword', '$email')");

$userid = mysqli_insert_id($db->link);

$db->query("INSERT into `users logins` (userid, token, ip)
    VALUES ('$userid', '$token', '$ip')");

以上是旧代码。以下是我的新作品:

$db->query("BEGIN TRANSACTION;
INSERT into `users` (username, password, email)
VALUES ('$username', '$hashpassword', '$email');

[here I need to get the row ID of the above insert]

INSERT into `users logins` (userid, token, ip)
VALUES ('$userid', '$token', '$ip')
COMMIT;");

如何获取第一个插入行 ID 并将其用于第二个插入?

4

1 回答 1

1

采用LAST_INSERT_ID()

...

INSERT into `users logins` (userid, token, ip)
VALUES (LAST_INSERT_ID(), '$token', '$ip')

...

或者如何创建Stored Procedure

DELIMITER $$
CREATE Procedure InsertRecord
(
    IN _userName VARCHAR(50),
    IN _passWord VARCHAR(50),
    IN _email VARCHAR(50),  
    IN _token VARCHAR(50),
    IN _ip VARCHAR(50)
)
BEGIN
    DECLARE Last_ID INT;

    INSERT into `users` (username, password, email)
    VALUES (_userName, _passWord, _email);

    SET Last_ID = LAST_INSERT_ID();

    INSERT into `users logins` (userid, token, ip)
    VALUES (LAST_INSERT_ID(), _token, _ip);

    SELECT Last_ID;
END $$
DELIMITER ;
于 2012-10-13T07:07:12.747 回答