I’m learning PHP and MySQL and I’m creating a movies website for learning purposes.
I want to insert variables and arrays containing movie info into a database but in different tables.
This is what I have right now:
include('inc/connection.php'); $conn = dbConnect(); // create SQL $sql = 'INSERT INTO movies (movieid, title, year, runtime, plot) VALUES(?, ?, ?, ?, ?)'; // initialize prepared statement $stmt = $conn->stmt_init(); if ($stmt->prepare($sql)) { // bind parameters and execute statment $stmt->bind_param('isiis', $movieid, $title, $year, $runtime, $plot); $stmt->execute(); }
This insert the variables into the movies table.
But I also need to insert (at the same time) the genres of the movie, the actors, languages, etc… they are in arrays and go into different tables (and maybe also in different rows). For example the array containing the genres (Action, Crime, Drama) genres in the genres table, and the actors in the actors table and so on… I then will use many-to-many and one-to-many tables to display the info.
Can someone explain to me how to do this?? I need to connect to the database multiple times?? I need loops? I’m really new to PHP and MySQLi so please try to explain as much as you can.
Thanks.
INSERTsupports only one table at a time, so you’ll certainly have to execute multipleINSERTstatements if you have complex data that goes into multiple tables.If you’ve inserted a specific
$movieidvalue tomoviesthen you know what value you need to insert to the rows of the other tables, to satisfy referential integrity (pseudocode follows, not fully functional example):If your
moviestable uses anAUTO_INCREMENTprimary key, then you can get the value generated during the firstINSERTeither by calling $mysqli->insert_id(), or by using the builtin functionLAST_INSERT_ID().Note that
LAST_INSERT_ID()reports the most recent auto-generated value during your current session, so if you insert to another table that uses an auto primary key, the value changes. But the value reported is stable during your sessions; it does not change if another client session is doing inserts concurrently.