Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

mysql - 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";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...