MySQL的LAST_INSERT_ID无法通过PHP工作

时间:2018-07-10 15:25:28

标签: php mysql transactions last-insert-id multi-query

我尝试了两种方法来完成这项工作:

multi_query:

$sql = "START TRANSACTION; INSERT INTO songs (title, disco, deleted) VALUES ('".$titol."', '".$codi."', '0'); SET @last_id = LAST_INSERT_ID(); INSERT INTO lyrics (`lyricsOri`, `lyricsTra`, `song`, `deleted`) VALUES ('".$lyricsO."', '".$lyricsT."', @last_id, 0); COMMIT;";

connection()->multi_query($sql);

和交易:

    connection()->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);
    connection()->query("START TRANSACTION;");
    connection()->query("INSERT INTO songs (title, disco, deleted) VALUES ('".$titol."', '".$codi."', '0');");
    connection()->query("SET @last_id = LAST_INSERT_ID();");
    connection()->query("INSERT INTO lyrics (`lyricsOri`, `lyricsTra`, `song`, `deleted`) VALUES ('".$lyricsO."', '".$lyricsT."', @last_id, 0);");
    connection()->query("COMMIT;");
    connection()->commit();
    connection()->close();

所有记录均记录良好,但歌词表上的歌曲列除外,其值为 NULL

有人可以帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

此多个查询一个接一个地执行,因此LAST_NSERT_ID()适用于任何情况。

您可以结合使用这两种技术来达到所需的目的:

        connection()->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);
        connection()->query("START TRANSACTION;");
        connection()->multi_query("INSERT INTO songs (title, disco, deleted) VALUES ('".$titol."', '".$codi."', '0');SET @last_id = LAST_INSERT_ID();INSERT INTO lyrics (`lyricsOri`, `lyricsTra`, `song`, `deleted`) VALUES ('".$lyricsO."', '".$lyricsT."', @last_id, 0);");
        connection()->query("COMMIT;");
        connection()->commit();
        connection()->close();

现在,在相同的查询执行流中声明并使用了var,以便可以正常工作。

干杯!