Merging two insert queries with Transaction. However I need to grab the first insert's row ID

StackOverflow https://stackoverflow.com/questions/12870843

  •  07-07-2021
  •  | 
  •  

Domanda

$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')");

The above is old code. The below is my new:

$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;");

How can I grab the first insert row ID and use it for the second insert?

È stato utile?

Soluzione

use LAST_INSERT_ID()

...

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

...

or how about creating 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 ;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top