$item=array(55,56,57,58);
$qty=array(11,111,1111,11111);
$tax=array(10,10,10,10);
$uprice=array(22,222,2222,22222);
我希望这些数据以单一查询的形式插入表中,格式如下 -
product_id quantity unit_price tax
55 11 22 10
56 111 222 10
57 1111 2222 10
58 11111 22222 10
我的php脚本是这样的,但我无法将数据插入到表中。请帮帮我。
$itm_list=array(" product_id='$item',
quantity='$qty',
unit_price='$tax',
tax_amount='$uprice' ");
foreach($itm_list as $k=>$v){
$q=mysql_query("insert into invoice_items set $v ") or die(mysql_error());
}
答案 0 :(得分:1)
将查询放入php循环中并不好,这可能会降低代码的速度。以下是高效运行的方法..
$item=array(55,56,57,58);
$qty=array(11,111,1111,11111);
$tax=array(10,10,10,10);
$uprice=array(22,222,2222,22222);
$str = '';
for($i=0;$i<count($item);$i++)
{
$str .= '("'.$item[$i].'","'.$qty[$i].'","'.$tax[$i].'","'$uprice[$i].'"),';
}
$str = substr($str,0,-1);
$sql='insert into invoice_items values '.$str;
mysql_query($sql);
答案 1 :(得分:0)
尝试以下方法:
<?php
$item=array(55,56,57,58);
$qty=array(11,111,1111,11111);
$tax=array(10,10,10,10);
$uprice=array(22,222,2222,22222);
$row = array();
foreach($item as $key => $value) {
$row[] = array($value,$qty[$key],$uprice[$key],$tax[$key]);
}
foreach($row as $r) {
$string = "'".implode("', '",$r)."'";
$query = mysql_query("INSERT INTO invoice_items(product_id,quantity,unit_price,tax)VALUES($string)");
}
?>
OR
<?php
foreach ($item as $key => $value):
$v[] = array(" product_id='".$value."',
quantity='".$qty[$key]."',
unit_price='".$tax[$key]."',
tax_amount='".$uprice[$key]."' ");
$fields = implode(',',array_keys($v));
$val = array_values($v);
$values = "'".implode("', '",$val)."'";
$query = mysql_query("INSERT INTO invoice_items($fields)VALUES($values)");
endforeach;
?>
或者您可以查看此链接 https://www.udemy.com/blog/sql-insert-multiple-rows/
答案 2 :(得分:0)
$item=array(55,56,57,58);
$qty=array(11,111,1111,11111);
$tax=array(10,10,10,10);
$uprice=array(22,222,2222,22222);
for($i=0;$i<count($item);$i++)
{
$sql='insert into invoice_items values($item[$i],$qty[$i],$tax[$i],$uprice[$i)';
mysql_query($sql);
}
希望它对你有用。
答案 3 :(得分:0)
试试这个有效:
$dbh=mysql_connect ("host-name", "user","password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("database-name");
$item=array(55,56,57,58);
$qty=array(11,111,1111,11111);
$tax=array(10,10,10,10);
$uprice=array(22,222,2222,22222);
for($i=0;$i<count($tax);$i++)
{
$sql='insert into invoice_items values($item[$i],$qty[$i],$tax[$i],$uprice[$i)';
mysql_query($sql);
}
mysql_close($dbh);
答案 4 :(得分:-2)
尝试这个
<?php
foreach ($item as $key => $value):
$v = array(" product_id='".$value."',
quantity='".$qty[$key]."',
unit_price='".$tax[$key]."',
tax_amount='".$uprice[$key]."' ");
$q=mysql_query("insert into invoice_items set $v ") or die(mysql_error());
endforeach;
&GT;