php - Insert values in junction table -
i have 3 tables in database:
trips(trip_id(pk), trip_name(unique), user_id(fk)) places(place_id(pk), place_name(unique)) trips_places_asc(trip_id(fk), place_id(fk))
since, many trips can have many places, have 1 junction table above.
now, if user insert places trip, places added places
table , trip associated places in trips_places_asc
table.
so, if write query like:
insert places (place_name) values ('xyz') insert trips (trip_name) values ('mytrip')
then, how store trip_id
, place_id
in junction or association table trips_places_asc
? have fire 2 queries? plz help.
note: there many questions on this one , this one. but, none of them have accepted reply or not answer. so, plz not mark duplicate.
since have place_name
, trip_name
unique as:
insert trips_places_asc ( trip_id, place_id ) values ( (select trip_id trips trip_name = 'mytrip'), (select place_id places place_name = 'xyz') );
or depending comand using insert (php command mean) can homecoming ids after inserts , utilize run insert command it.
it like: (using mysqli* functions )
$query = "insert trips (trip_name) values ('mytrip')"; $mysqli->query($query); $trip_id = $mysqli->insert_id; $query2 = "insert places (place_name) values ('xyz')"; $mysqli->query($query2); $place_id = $mysqli->insert_id; $query3 = "insert trips_places_asc ( trip_id, place_id ) "; $query3 .= " values ($trip_id, $place_id)";
note, i'm doing straight mind, maybe have adjust syntax error or concerned prepared statements.
edit though should add together proper documentation link command: http://php.net/manual/en/mysqli.insert-id.php
php mysql sql database junction-table
No comments:
Post a Comment