简体   繁体   中英

Get the last 2 autoincrement ID

I managed to get the last ID for the last insert query but nor for the second one. How Can I achieve this? I need both to populate the join table

$query="INSERT INTO  $dbname.Product (Description, ***, **, **, **) VALUES ('$des','$**', '$**', '$**', '$**')";
        $result = mysqli_query($conn,$query);
        $id =  mysqli_insert_id($conn);
        $query2 = "INSERT INTO  $dbname.Classification (**, **, **) VALUES ('$**', '$**', '$***')";     

        $result2 = mysqli_query($conn,$query2); 
        $id2 =  mysqli_insert_id($conn);
        echo $id;
        echo $id2;   //print the same ID as $id2

If you evaluate that there are no risk for two products to be created by two different user within the same second, you could use a query like this one.

INSERT INTO $dbname.myTable (id_product, id_classification) VALUES((SELECT id_product FROM $dbname.Product ORDER BY id_product DESC LIMIT 1), (SELECT id_classification FROM $dbname.Classification  ORDER BY id_classification DESC LIMIT 1));

If lot of people can create products at the same and the risk of conflicts are high, then I'd used a stored procedure and I'd stored the value of the last inserted id in a variable after each query.

DELIMITER //

CREATE PROCEDURE createProduct(
[your paramters],
dbName AS VARCHAR(50)
) 
BEGIN

    DECLARE idProduct INT(10) UNSIGNED;
    DECLARE idClassification INT(10) UNSIGNED;

    DECLARE EXIT HANDLER FROM SQLEXCEPTION BEGIN
        ROLLBACK;
        RESIGNAL;
    END;

    START TRANSACTION;

    INSERT INTO  dbname.Product (Description, ***, **, **, **) VALUES ('$des','$**', '$**', '$**', '$**');

    SET idProduct = LAST_INSERTED_ID();

    INSERT INTO dbname.Classification (**, **, **) VALUES ('$**', '$**', '$***');

    SET idClassification = LAST_INSERTED_ID();

    INSERT INTO $dbname.myTable (id_product, id_classification) VALUES (idProduct, idClassification);

    COMMIT;

END//

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM