I am running the following PHP, as I want to insert data from a form into 2 tables: EventLocation and Events (EventLocationID is the foreign key in the table Events).
First I run an INSERT query to insert into EventLocation. As EventLocationID is auto-incremented, it generates the next ID without me having to enter anything. My question is how should I fetch this unique ID to be used in the next INSERT query to insert into events?
Note that the first query inserts fine, but the second query gives me an error
PHP:
require '../dbh.inc.php';
$Event_Name = $_POST['Event_Name'];
$Event_Date = $_POST['Event_Date'];
$Street_1 = $_POST['Street_1'];
$Street_2 = $_POST['Street_2'];
$City = $_POST['City'];
$Start_Time = $_POST['Start_Time'];
$End_Time = $_POST['End_Time'];
$Zipcode = $_POST['Zipcode'];
$query = "INSERT INTO EventLocation (Street_1, Street_2, City, Zipcode) VALUES ('$Street_1', '$Street_2', '$City', '$Zipcode')";
$queryexecution = mysqli_query($conn, $query);
if(!$queryexecution){
echo "damn, there was an error inserting into Event Location";
}
else {
echo "Event Location was added!";
}
$querytwo = "SELECT EventLocationID from EventLocation where Street_1 = '$Street_1';";
$querytwoexecution = mysqli_query($conn, $querytwo);
while ($displayname = mysqli_fetch_assoc($querytwoexecution)){
echo "".$displayname['EventLocationID']."
";
}
$secinsert = "INSERT INTO events (Event_Name, Event_Date, Start_Time, End_Time, EventLocationID) VALUES ('$Event_Name','$Event_Date','$Start_Time','$End_Time', '$displayname')";
$secqueryexecution = mysqli_query($conn, $secinsert);
if(!$secqueryexecution){
echo "damn, there was an error inserting into Events";
}
else {
echo "Event data was added!";
}
?>
I am curious to know if I could just use an Inner Join function to make it more efficient; I tried before but to no success?
Answer
You can just use mysqli_insert_id
:
$displayname = mysqli_insert_id($link);
this will fetch the last auto_incremented id
value from the current connection.
No comments:
Post a Comment