Is is possible use the LAST_INSERT_ID() in php for-loop. I need to get the last playground PK as a FK in guardian table. Both needs to insert at a same time. Pardon me for not using PDO, i just want to get this thing to work first.
$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); I have also tried this. But the one below outputs the last id, but not the newly inserted 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);
$query = "INSERT INTO playground (parent, children, amount) VALUES ('John','susy','2000');"; if(mysqli_query($con,$query)){ $id = mysqli_insert_id($con); $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_query($con,$query) } }