是否可以在php for-loop中使用LAST_INSERT_ID()?

时间:2018-04-25 11:09:18

标签: php mysql mysqli-multi-query

是否可以在php for-loop中使用LAST_INSERT_ID()。我需要在playground表中将最后一个guardian PK作为FK。两者都需要同时插入。请原谅我没有使用PDO,我只想先让这件事工作。

$query = "INSERT INTO playground (parent, children, amount) VALUES ('John','susy','2000');";

$levelarray = array ("One", "Two", "Three");
for ($i = 0; $i < count($levelarray); $i++) {
    $level = $levelarray[$i];
    $query .= "INSERT INTO guardian (playgroundid, level) VALUES (LAST_INSERT_ID(),'$level');";
}
mysqli_multi_query($con, $query);

我也试过这个。但是下面的那个输出最后一个id,而不是新插入的id。

$query = "INSERT INTO playground (parent, children, amount) VALUES ('John','Susy','2000');";

$sql = "SELECT playground_id AS playgroundid FROM playground ORDER BY playground_id DESC LIMIT 1";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
$playId = $row['playgroundid'];

$levelarray = array ("One", "Two", "Three");
for ($i = 0; $i < count($levelarray); $i++) {
    $level = $levelarray[$i];
    $query .= "INSERT INTO guardian (playgroundid, level) VALUES ('$playId','$level');";
}
mysqli_multi_query($con, $query);

2 个答案:

答案 0 :(得分:3)

您需要使用mysqli_insert_id()

获取最后插入的ID

然后将其用于下一个查询: -

$query = "INSERT INTO playground (parent, children, amount) VALUES ('John','susy','2000');"; 

if(mysqli_query($con,$query)){ 
    $id = mysqli_insert_id($con);  //get last inserted id
    $levelarray = array ("One", "Two", "Three"); 
    for ($i = 0; $i < count($levelarray); $i++) { 
        $level = $levelarray[$i]; 
        $query = "INSERT INTO guardian (playgroundid, level) VALUES ($id,'$level');"; 
        mysqli_query($con,$query) ;
    } 
}

或者您仍然可以使用下面的mysqli_multi_query(): -

$query = "INSERT INTO playground (parent, children, amount) VALUES ('John','susy','2000');"; 

if(mysqli_query($con,$query)){ 
    $id = mysqli_insert_id($con);  //get last inserted id
    $query1 = '';
    $levelarray = array ("One", "Two", "Three"); 
    for ($i = 0; $i < count($levelarray); $i++) { 
        $level = $levelarray[$i]; 
        $query1 .= "INSERT INTO guardian (playgroundid, level) VALUES ($id,'$level');"; 
    } 
     mysqli_multi_query($con, $query1);
}

注意: - 您的查询对SQL INJECTION是敞开的。所以尽量使用prepared statement来阻止它。

答案 1 :(得分:2)

不,这不会奏效。第一个监护人将获得操场的身份,接下来的两个将获得前卫士的身份。

使用mysqli_insert_id()来获取id并将其保存为for循环之外的变量。