使用单个sql语句将数组和非数组值插入数据库

时间:2016-10-25 13:44:06

标签: php mysql arrays

我有这个,工作,代码,用于将数组插入数据库:

$c = array_map(function ($reqNo,$officer,$product,$quantity){return "'$reqNo','$officer','$product','$quantity'";} , $reqNo,$officer,$product,$quantity);

if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR) VALUES (".implode('),(', $c).")"))

现在,问题是我还希望使用相同的sql insert语句将数组旁边的数组值插入到同一个数据库表中。到目前为止我的代码是什么,

if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR,Iuse,Designation,QtyA,QtyA1,QtyI,Rdate,Rtime,bar) VALUES (".implode('),(', $c).",'replacement','ICTU','-1','-1','-1',CURDATE(),CURTIME(),'1' )"))

这是我得到的错误:

Column count doesn't match value count at row 1

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:0)

我确实找到了解决方法,但不确定这是不是正确的方式......这就是我怎么做的:

//first, i got the length of the array
for($i=0;$i<count($product);$i++){}

//i used array_fill() to duplicate the single values into the length of the array
$new_usage = array_fill(0,$i,$usage);
$new_designation = array_fill(0,$i,$designation);
$QtyA = array_fill(0,$i,"-1");
$QtyA1 = array_fill(0,$i,"-1");
$QtyI = array_fill(0,$i,"-1");
$date = array_fill(0,$i,date("Y-m-d"));
$time = array_fill(0,$i,date("H:i:s"));
$bar = array_fill(0,$i,"1");

//then i put the above new arrays into array_map(), together with the original array
$c = array_map(function ($reqNo,$officer,$product,$quantity,$new_usage,$new_designation,$QtyA,$QtyA1,$QtyI,$date,$time,$bar){return "'$reqNo','$officer','$product','$quantity','$new_usage','$new_designation','$QtyA','$QtyA1','$QtyI','$date','$time','$bar'";} , $reqNo,$officer,$product,$quantity,$new_usage,$new_designation,$QtyA,$QtyA1,$QtyI,$date,$time,$bar);

//from there, i imploded the array_map into the sql insert statement
if(!$insert = mysql_query("INSERT INTO request (RNO,UID,PID,QtyR,Iuse,Designation,QtyA,QtyA1,QtyI,Rdate,Rtime,bar) VALUES (".implode('),(', $c).")")){
...

我仍然不知道这是否是正确的方法,但总而言之,它确实有效。