将自动增量ID传递给第二个查询

时间:2016-12-08 09:41:08

标签: php mysql sql mysqli

目前我有两个查询,其中第一个有自动增量ID。我想将此ID传递给我的第二个查询。但无法弄清楚如何做到这一点。我使用了'mysqli_insert_id',但它返回了数据库。

这是我的代码:

$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
$last_id = mysqli_insert_id($con);
second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";

为了避免混淆:我想将第一个查询的id插入到另一个表中,它只是一个整数。

希望有人可以帮助我!

3 个答案:

答案 0 :(得分:1)

像这样更改你的代码

    $query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
    mysqli_query($con, $query);
    $last_id = mysqli_insert_id($con);
    $second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";
    mysqli_query($con, $second_query);

答案 1 :(得分:1)

会以这种方式运作

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
mysqli_query($link, $query);

printf ("New Record has id %d.\n", mysqli_insert_id($link));
$last_id = mysqli_insert_id($link);

second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";
mysqli_query($link, $second_query);


/* close connection */
mysqli_close($link);
?>

参考this

答案 2 :(得分:1)

假设您正在执行查询,

1。您可以使用Mysql的函数:LAST_INSERT_ID()

示例:

SELECT LAST_INSERT_ID();

2。您可以使用PHP的函数mysqli_insert_id

示例:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
//.. some code
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
mysqli_query($link, $query);
printf ("New Record has id %d.\n", mysqli_insert_id($link));