Monday, 24 July 2017

php - How do I fetch the generated foreign key created in MySQL to be used in Insert Function




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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...