title: update database rows using foreach loop
body: <p>I have a table in my database is called "books_term",</p>
  
  <p>when I submit a book, book and its categories store in this table.
  some of my books have multiple categories, so I decided to store each category as a new row + book_id </p>
  
  <p>for example : </p>
  
  <pre><code>id             category_id            book_id
   1                   23                 14
   2                   45                 14
   3                   30                 14
  </code></pre>
  
  <p>this is "books_term" table structure, as you can see, book number 14 has three categories (23,45,30)</p>
  
  <p>everything works fine until I decided to update the book in the admin panel of my cms.</p>
  
  <p>the question is: how can I update this books category?
  and how can I update book categories if the book exists in "books_term" otherwise insert?
  should I use <code>foreach</code> loop for this purpose?</p>
  
  <p>this is my php code and it does not work correctly, </p>
  
  <pre><code>   $values = $_POST['category'];
     $myid = $_POST['bookid'];
     foreach($values as $value) {
       $check = "SELECT * FROM books_term WHERE book_id = '$myid'";
       $checkresult = mysqli_query($connection,$check);
       if(mysqli_num_rows($checkresult) &gt; 0){
          $update_query = "UPDATE books_term SET category_id = '$value' WHERE book_id = '$myid'";
          mysqli_query($connection,$update_query);
          echo 'updated';
       }else{
          $insert_query = "INSERT INTO books_term (category_id,book_id) VALUES ('$value','$myid')";
          mysqli_query($connection,$insert_query);
          echo 'inserted';
      }
  }
  </code></pre>
  
  <p>in the edit page, when I select multiple categories and click on the update button, it just set last selected category to book_id 14,  like in the picture below: </p>
  
  <p><a href="https://i.stack.imgur.com/5Gzyk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Gzyk.png" alt="enter image description here"></a></p>