如何立即从数据库中检索数据,然后进行插入?

时间:2019-03-06 14:24:02

标签: php mysql database

我正在使用以下查询将数据插入表中。现在,我如何能够检索该插入的数据。我已经尝试过这种方式,但是没有用。对此提供帮助。

event_id是事件表中存在的字段,并且会自动递增。

$sql=$con->query("INSERT INTO events 
   (gname,location,date_from,date_to,venue_details,email,participants)VALUES ('$gname','$location','$date_from','$date_to','$venue_details','$email','$participants');");
        $immediate = $con->query("SELECT * FROM events WHERE gname==$gname AND location==$location AND date_from==$date_from AND date_to==$date_to AND venue_details==$venue_details AND email==$email AND participants==$participants;");
        $retrieve = mysqli_fetch_array($immediate);
        $selfid = $retrieve['event_id'];
        $insert = $con->query("INSERT INTO usersregisteredevents (event_id, email) VALUES ($selfid,$email);");'

1 个答案:

答案 0 :(得分:1)

您可以通过获取最后插入的ID来实现

$sql = "INSERT INTO `tmp` (`name`, `data`) VALUES ('somename','somedata');";
if ($con->query($sql) === TRUE) {
    $insertId = $con->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $insertId;
} else {
    echo "Error: " . $sql . "<br>" . $con->error;
}

//Optional if you want this row
$immediate = $con->query("SELECT * FROM events WHERE event_id = $insertId");
$retrieve = mysqli_fetch_array($immediate);

//or you can do another query using just $insertId
$insert = $con->query("INSERT INTO usersregisteredevents (event_id, email) VALUES ($insertId, 'someemail';");

使用此ID,您可以要求DB获取新行,或者仅使用ID在其他表中使用。