Search code examples
phpmysqlmultiple-records

Inserting multiple rows in a table using PHP


I am trying to insert multiple rows into MySQL DB using PHP and HTML from. I know basic PHP and searched many examples on different forums and created one script however it doesn't seem working. Can anybody help with this. Here is my script:

include_once 'include.php';

foreach($_POST['vsr'] as $row=>$vsr) {
   $vsr=mysql_real_escape_string($vsr);
   $ofice=mysql_real_escape_string($_POST['ofice'][$row]);
   $date=mysql_real_escape_string($_POST['date'][$row]);
   $type=mysql_real_escape_string($_POST['type'][$row]);
   $qty=mysql_real_escape_string($_POST['qty'][$row]);
   $uprice=mysql_real_escape_string($_POST['uprice'][$row]);
   $tprice=mysql_real_escape_string($_POST['tprice'][$row]);
}

$sql .= "INSERT INTO maint_track (`vsr`, `ofice`, `date`, `type`, `qty`, `uprice`,
`tprice`) VALUES ('$vsr','$ofice','$date','$type','$qty','$uprice','$tprice')";

$result = mysql_query($sql, $con);

if (!$result) {
   die('Error: ' . mysql_error());
} else {
   echo "$row record added";
}

Solution

  • MySQL can insert multiple rows in a single query. I left your code as close as possible to the original. Keep in mind that if you have a lot of data, this could create a large query that could be larger than what MySQL will accept.

    include_once 'include.php';
    
    $parts = array();    
    foreach($_POST['vsr'] as $row=>$vsr) {
       $vsr=mysql_real_escape_string($vsr);
       $ofice=mysql_real_escape_string($_POST['ofice'][$row]);
       $date=mysql_real_escape_string($_POST['date'][$row]);
       $type=mysql_real_escape_string($_POST['type'][$row]);
       $qty=mysql_real_escape_string($_POST['qty'][$row]);
       $uprice=mysql_real_escape_string($_POST['uprice'][$row]);
       $tprice=mysql_real_escape_string($_POST['tprice'][$row]);
    
       $parts[] = "('$vsr','$ofice','$date','$type','$qty','$uprice','$tprice')";
    }
    
    $sql = "INSERT INTO maint_track (`vsr`, `ofice`, `date`, `type`, `qty`, `uprice`,
    `tprice`) VALUES " . implode(', ', $parts);
    
    $result = mysql_query($sql, $con);