使用PHP在表格中插入多行 [英] Inserting multiple rows in a table using PHP

查看:127
本文介绍了使用PHP在表格中插入多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP和HTML from将多个行插入MySQL DB.我知道基本的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";
}

推荐答案

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

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

这篇关于使用PHP在表格中插入多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆