duanliang1019 2018-07-20 13:57
浏览 30
已采纳

PHP - 从数组中插入多行会产生无效输出

I am trying to insert multiple rows from an array by creating an INSERT STATEMENT using the implode function. I am unable to figure out why I am getting more than 2 INSERT STATEMENT rows as there are only 2 rows.

I have also looked at this link, but still no joy insert multiple rows via a php array into mysql

Please help !

Below is my code:

while ($row = sqlsrv_fetch_array($getResults,SQLSRV_FETCH_ASSOC))
{
    foreach ($row as $v) {
        $sql[] = "(".$row['ReportName'].");";   
    }
    $test = "INSERT INTO PublishedComments (ReportName) VALUES ".implode(",",$sql);
    echo $test;
    echo "<br />...........<br />";
}

The output is the following:

INSERT INTO PublishedComments (ReportName) VALUES (Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);
...........
INSERT INTO PublishedComments (ReportName) VALUES (Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);,(Report Sales Per Order Method Type);
...........
  • 写回答

2条回答 默认 最新

  • dqh1984 2018-07-20 14:12
    关注

    You might want to take out the insert query out of the while loop, if you are trying to insert whole rows as a batch insert Also remove the foreach and the ";" at the end of "('".$row['ReportName']."');";

    while ($row = sqlsrv_fetch_array($getResults,SQLSRV_FETCH_ASSOC))
    {
    
        $sql[] = "('".$row['ReportName']."')"; 
    }
    $test = "INSERT INTO PublishedComments (ReportName) VALUES ".implode(",",$sql) . ';'; // Add semicolon
    echo $test;
    echo "<br />...........<br />";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法