I have two tables: movies and genres, and a junction table movieOfGenre for many-to-many relationships between the movies and genres tables. Now, when I am using transactions to insert movies and genres into my database using PHP, genres were being created twice even if there was a duplicate. Then I updated the code with ...ON DUPLICATE KEY UPDATE... and now if there is an existing genre with the same name, the auto_increment ID of the existing genre is being updated when I use this transaction query:
mysqli_autocommit($connect, false);
$query_success = true;
$stmt = $connect->prepare("INSERT INTO movies (id, title, plot, rating, releaseDate, duration, language, country, posterUrl, trailerUrl) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssssss", $defaultId, $title, $plot, $rating, $releaseDate, $duration, $language, $country, $poster, $trailer);
if (!$stmt->execute()) {
$query_success = false;
}
$movieId = mysqli_insert_id($connect);
$stmt->close();
foreach ($genres as $genre) {
$stmt = $connect->prepare("INSERT INTO genres (id, name) VALUES (?, ?) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID()");
$stmt->bind_param("ss", $defaultId, $genre);
if (!$stmt->execute()) {
$query_success = false;
}
$genreId = mysqli_insert_id($connect);
$stmt->close();
$stmt = $connect->prepare("INSERT INTO movieofgenre (movieId, genreId) VALUES (?, ?)");
$stmt->bind_param("ii", $movieId, $genreId);
if (!$stmt->execute()) {
$query_success = false;
}
$stmt->close();
}
if ($query_success) {
mysqli_commit($connect);
} else { ?>
alert('Error adding movie.');
<?php mysqli_rollback($connect);
}
How do I write the query so that if during insertion there is an existing row with the same genre.name, it returns the ID of the existing row without updating it?
Thanks in advance.
selectafter you inserted it instead of querying for mysqli_insert_id). Btw, it is a bad idea to update the id (e.g. because all entries inmovieofgenrefor that genre will become useless or have to be updated).