gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:09:08 26 4
gpt4 key购买 nike

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

$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 插入语句将数组值与数组一起插入到同一个数据库表中。这是迄今为止我的代码,

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

关于如何解决这个问题有什么想法吗?

最佳答案

我确实找到了解决方法,但不确定这是否是正确的方法..我是这样做的:

//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).")")){
...

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

关于php - 使用单个 sql 语句将数组和非数组值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40241697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com