title: MySQL PHP Insert into Two Tables Transaction
body: <p>I'm trying to insert into two different tables and it works without the foreach statements but I can't seem to figure out where I'm going wrong once I add the foreach... Here is the SQL/PHP query:    </p>
  
  <pre><code>$con=mysqli_connect($GLOBALS['db_host'],$GLOBALS['db_name'],$GLOBALS['db_password'],$GLOBALS['db_user']);
  
  
  if (!$con) {
      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();
  }   
  mysqli_autocommit($con, FALSE);
  
  $i = 0;
  $end = count($_POST['category_id']);    
  $end2 = count($_POST['benefit_id']);
  
  
  $sql="INSERT INTO store_locator_category_map (id,category_id)
  VALUES ";
  foreach ($_POST['category_id'] as $category_id) {
          if(++$i === $end) { 
          $sql .="('".$id."', '".$category_id."');";
          } else  $sql .="('".$id."', '".$category_id."'), ";
      }           
  mysqli_query($con, $sql);
  
  $sql2="INSERT INTO store_locator_benefit_map (id,benefit_id)
  VALUES ";
  foreach ($_POST['benefit_id'] as $benefit_id) {
          if(++$i === $end2) { 
          $sql2 .="('".$id."', '".$benefit_id."');";
          } else  $sql2 .="('".$id."', '".$benefit_id."'), ";
      }
  
  mysqli_query($con, $sql2);
  
  if (!mysqli_commit($con)) {
      print("Transaction commit failed\n");
      exit();
  }
  
  mysqli_close($con);         
  </code></pre>