title: Create a Dynamic insert statement - PHP - Mysql
body: <p>I have a form which has multiple drop downs (16) <code>speed[]</code> and some other fields</p>
  
  <p>The data from the dropdown boxes has to be inserted into a Mysql  table</p>
  
  <p>What I did is I took the count <code>count($_POST["speed"]);</code>and then loop through until the end of the speed array.</p>
  
  <p><strong>The problem is:</strong></p>
  
  <ol>
  <li><p>If Anyone of the dropdown is not selected it returns "-1", if used `($_POST["speed"][$i]!="-1")for that but it does not compare and goes into the IF loop</p></li>
  <li><p>The Insert Query is not a valid not sure how to append the extra <code>commas</code></p></li>
  </ol>
  
  <p><strong>$sql when printed</strong></p>
  
  <pre><code>INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ('name', '', ''-1''800''-1''-1''200''-1''-1''-1''-1''-1''-1''-1''-1''-1''-1''200'', '208')
  </code></pre>
  
  <p><strong>My PHP code</strong></p>
  
  <pre><code> $itemCount = count($_POST["speed"]);
          $itemValues=0;
          $query = "INSERT INTO mytablename (w_name,wtype,speed1,speed2, speed3, speed4, speed5, speed6, speed7, speed8, speed9, speed10, speed11, speed12, speed13, speed14, speed15, speed16, coach_id) VALUES ";
          $bldSpltString="";
          $queryValue = "";
          for($i=0;$i&lt;$itemCount;$i++) {
              if(($_POST["speed"][$i]!="-1") || !empty($_POST["speed"][$i])) {
  
                  $bldSpltString .= "'" .  $_POST["speed"][$i] ."'";
              }
          }
          $queryValue .= "('" . $wkout . "', '" . $wtype . "', '" . $bldSpltString . "', '" .$_SESSION['id']."')";
  
          $sql = $query.$queryValue;
          echo $sql;
          exit;
  </code></pre>