title: MySQL prepared statement with bulk insert
body: <p>I have a module which allows admins to add some users (maybe multiple) to a group.</p>
  
  <p><strong>PHP</strong></p>
  
  <pre><code>$user_id  = $_POST["user_id"]; //this can be an array
  $group_id = $_POST["group_id"];
  
  $sql = "INSERT IGNORE INTO users_groups (user_id, group_id) 
          VALUES ($user_id[0],$group_id)";
  
  for ( $i = 1; $i &lt; count($user_id); $i++) 
  {
      $sql .= ", ($user_id[$i],$group_id)"
  }
  </code></pre>
  
  <p>As you can see the sql-query depends on how much users the admin has selected.</p>
  
  <p>How can I use this code with prepared statements because the post-variables come from a user (SQL injections...)</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I have two selectboxes:</p>
  
  <ul>
  <li>one for the user selection (multiple selection is possible -> array): <code>$_POST["user_id"]</code></li>
  <li>one for the group selection (only one selection is possible): <code>$_POST["group_id"]</code></li>
  </ul>
  
  <p>And now I want a prepared SQL statement for inserting <code>user_id</code> and <code>group_id</code> to the many-to-many-table (<code>users_groups</code>). The problem is that the number of values which have to be inserted can change (depending how much users the admin has selected in the selectbox).</p>
  
  <p>I want to change the prepared query depending on how much users the admin has selected.</p>
  
  <p>For example:</p>
  
  <ul>
  <li>the admin selected two users -> sql: <code>INSERT IGNORE INTO users_groups (user_id, group_id) VALUES ($user_id[0],$group_id), ($user_id[1],$group_id)</code></li>
  <li>the admin selected four users -> sql: <code>INSERT IGNORE INTO users_groups (user_id, group_id) VALUES ($user_id[0],$group_id), ($user_id[1],$group_id), ($user_id[2],$group_id), ($user_id[3],$group_id)</code></li>
  </ul>
  
  <p>My question: How can I do this automaticaly and with prepared sql statements because I dont want to have like 10 times <code>if(count($user_id) == number) {...</code>?</p>
  
  <p><strong>UPDATE 2</strong>
  If I would do this manually the code would look like this:</p>
  
  <pre><code>$sql = $db-&gt;prepare("INSERT IGNORE INTO users_groups (user_id, group_id) VALUES (?, ?)"); 
  $sql-&gt;bind_param('ii', $user_id[0], $group_id);
  </code></pre>
  
  <p><strong>UPDATE 3</strong>
  To check whether there are only integers in the post variables:</p>
  
  <pre><code>$user_id = filter_input_array(INPUT_POST, 'user_id', FILTER_SANITIZE_NUMBER_INT);
  $user_id = abs($user_id);
  
  $group_id = filter_input(INPUT_POST, 'group_id', FILTER_SANITIZE_NUMBER_INT);
  $group_id = abs($group_id);
  </code></pre>