简体   繁体   中英

Use prepared statements in PHP to insert into/display from multiple MySQL tables with foreign key

I have two tables: movies and directors . The directors attribute in the movie entity is multi-valued, which is why I created the directors table with movieId as a foreign key that references the id column of the movies table.

Now, if I want to insert movies into my movies table, how do I add all the information for the movies into the movies table, as well as the name of the directors into the directors table at the same time, possibly using transactions? Also, how do I display the information from the movies table with their corresponding directors from the directors table in a HTML5 table using a while loop? I am using PHP with prepared statements.

This is what I have so far, but it's not complete:

mysqli_autocommit($connect, FALSE);
$stmtMov = $connect->prepare("SELECT id, title, plot, rating, releaseDate, language, duration, country, posterUrl, trailerUrl, imdbUrl FROM movies");
$stmtMov->execute();
$resultMov = $stmtMov->get_result();
$rowMov = $resultMov->fetch_assoc();
$movieId = $rowMov['id'];
$stmtDir = $connect->prepare("SELECT movieId, name FROM directors WHERE movieId = ?")
$stmtDir->bind_param("?", $movieId);
$stmtDir->execute();
$resultDir = $stmtDir->get_result();
$rowDir = $resultDir->fetch_assoc();

Any help would be very much appreciated.

Since you haven't added anything about insert, I'll consider only your select part.

The $rowMov will likely result in a rowset, which is nothing more than an array, which each row will have an ID value. What you should do is iterate with your rowset and generate, for every value, a query for directors entity and get the data you want. Something like:

foreach ($rowMov as $movie) {
    $stmt = $connection->prepare("SELECT .... FROM directors WHERE id_movie = ?");
    $stmt->bindParam("?", $movie["ID"]);
    // $execution, binding results, etc.
}

With that done, you'll have an array with directors and an array with movies. If you want to simplify things on your view (considering you're using a MVC pattern), I would associate both arrays, looking for relations of directors["ID_MOVIE"] and movies["ID"] , finally creating an array with both informations like and object.

You've asked two questions,

  • How do I insert into two tables at the same time, and
  • How do I display from two tables

But before I go into that, a bit of database review is in order. I would think that each movie would have one director, while each director might have many movies. I suppose the possibility for co-directors exists, too.

So for the first case, each movie must have a director:

movies
------
movie_id
director_id
title
plot, etc...

In this case, you could simply put the director's name in the movie database, but in order to list movies by director you would have to search by the actual name (and mis-spelling would make things complicated). And directors and movies are two different things, so it's better to have separate tables.

In the second case, you need a join table to have a many-to-many relationship.

movies        director_movie     directors
-------       --------------     --------
movie_id       movie_id          director_id
title          director_id       name

So to answer your questions,

How do you insert into two tables at the same time?

You don't. First insert into whichever table stands on its own-- in the first case, directors . Then you get the last_insert_id from that table (or if the director already exists, search for the director_id). If last_insert_id is squirrely, you may have to search for what you just inserted to get the id.

Then, you take that id value and insert it into the dependent table movies along with the rest of that table's fields.

For the many-to-many case, you would do it in similar steps: 1) insert into movies 2) get the movie_id 3) insert into direcotors 4) get the director_id 5) insert ids into director_movie

How do I display the results

If there is only one director per movie, it's a simple sql query:

SELECT movies.*, directors.name FROM movies, directors where movies.director_id=directors.director_id AND movies.movie_id=?"

If you have multiple directors per movie, you'll have to loop through results:

SELECT * FROM movies WHERE movie_id=? then make another query to list the directors SELECT d.* from directors AS d,director_movie AS dm WHERE dm.director_id=d.director_id AND dm.movie_id=?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM