Note that there are some explanatory texts on larger screens.

plurals
  1. POForeach not inserting in fields of MySQL
    primarykey
    data
    text
    <p>I have a database with authors, books, subjects, publishers etc.</p> <p>In one of my forms I insert all of the book information and one of the informations are which authors (from the database) wrote the specific book. </p> <p>I have a many-to-many relationship between the author table and the book table with the table between them named <code>book_author</code>. What I do in the book form is insert the authors IDs chosen from a <code>select multiple</code> in php into the <code>book_author</code> table along with the ISBN of the book so every book_ISBN with author_ID combination will be unique in that table (even though I have not set the combination as a primary key because I have no more information in that table).</p> <p>The problem is that my foreach statement will insert in the database only once and also if I have many authors chosen (more than 2 usually) it will not insert anything at all.</p> <p>EDIT: The authors are displayed properly in the <code>select multiple</code></p> <p>I have checked with <code>var_dump()</code> and the array has the correct IDs, example after selecting 2 authors:</p> <p><code>array(2) { [0]=&gt; string(1) "3" [1]=&gt; string(1) "2" }</code></p> <p>I have even checked if each query is produced correctly, same example:</p> <p><code>string(77) "INSERT INTO book_author (book_ISBN, author_ID) VALUES ('87979695faae','3')"</code></p> <p><code>string(77) "INSERT INTO book_author (book_ISBN, author_ID) VALUES ('87979695faae','2')"</code></p> <p>But the problem insists and I have no idea what to do, here is my code:</p> <pre><code>if (!isset($_POST["authors"])){ header("Location: addBook.php"); exit; } var_dump($_POST["authors"]); $authors = $_POST["authors"]; foreach ($authors as $author) { $sqlAuthor = "INSERT INTO book_author (book_ISBN, author_ID) VALUES ('$isbn','$author')"; var_dump($sqlAuthor); mysql_query($sqlAuthor); } </code></pre> <p>My suspicion would be this <code>mysql_query($sqlAuthor);</code> but I'm not sure...</p> <p>EDIT: I used the <code>die</code> function as instructed and this is the error I got </p> <pre><code>Cannot add or update a child row: a foreign key constraint fails (`library`.`book_author`, CONSTRAINT `FK_written1` FOREIGN KEY (`book_ISBN`) REFERENCES `book` (`book_ISBN`)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload