我有一个公司名称数组,我将每个公司名称作为单独的记录插入。下面是代码
<input type="text" name="company_name[]">
$company_name = $_POST['company_name'];
if($company_name)
{
foreach($company_name as $company)
{
$mycompany[] = $company;
}
}
$val="('".implode("'), ('",$mycompany)."')";
$sql = "INSERT INTO `table`
(`company_name`) VALUES ".$val."";
上面的查询看起来像这样,它成功地在表中插入了2条记录。
INSERT INTO `table` (`company_name`) VALUES ('DELL'), ('IBM')
现在的问题是,每个company_name都有一个我想要插入每个记录的company_code,并且有第三个值让我们假设order_num我也想插入但是order_num在所有记录中应该是相同的,我需要查询下面
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89'), ('123','IBM','bxc90')
答案 0 :(得分:1)
好的,最后你努力创造一些可以理解的东西
1)此代码绝对没用:
$company_name = $_POST['company_name'];
if($company_name)
{
foreach($company_name as $company)
{
$mycompany[] = $company;
}
}
因为$ mycompany与$ company_name完全相同
2)获取“非常复杂”的查询
foreach($_POST['company_name'] as $key => $value)
{
$name = mysql_real_escape_string($value);
$code = mysql_real_escape_string($_POST['company_code'][$key]);
$mycompany[] = "(123,'$name','$code')";
}
$sql = "INSERT INTO `table` (order_num,company_name,company_code) VALUES ";
$sql .= implode(",",$mycompany);
答案 1 :(得分:0)
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','DELL','axc89');
INSERT INTO `table` (`order_num`,`company_name`,`company_code`) VALUES ('123','IBM','bxc90');
您可以使用数组
$arrray_to_be_inserted=array
(
[0]=>array('123','DELL','axc89'),
[1]=>array('123','IBM','bxc90')
);
答案 2 :(得分:0)
不要将值传递给foreach中的新变量,而是尝试以$ key和$ value的形式访问,试试这个并看看它是否可以帮助你
<?php
$company_name = array("DEL","IBM");
$company_code = array("1","2");
$order_num = array("4","5");
if($company_name)
{
foreach($company_name as $key => $value)
{
$mycompany[] = $value;
$mycompanycode[] = $company_code[$key];
$myordernum[] = $order_num[$key];
}
}
&GT;
确保名称及其值彼此对应。