编程语言
首页 > 编程语言> > 使用PHP在表格中插入多行

使用PHP在表格中插入多行

作者:互联网

我正在尝试使用PHP和HTML from将多个行插入MySQL DB.我知道基本的PHP,并在不同的论坛上搜索了许多示例,并创建了一个脚本,但是它似乎不起作用.任何人都可以帮忙.这是我的脚本:

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";
}

解决方法:

MySQL可以在一个查询中插入多行.我将您的代码尽可能地靠近原始代码.请记住,如果您有大量数据,这可能会创建一个大型查询,该查询可能大于MySQL所接受的查询.

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

标签:php,mysql,multiple-records
来源: https://codeday.me/bug/20191012/1899400.html