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);
...........
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 />";
Two problems:
First, your values are not surrounded by '
.
Second, each set ends with a semicolon ;
but it should be comma ,
Third, pointed out in comments, you are looping with a while()
and then again with a foreach()
... surely that's not what you wanted :}
while ($row = sqlsrv_fetch_array($getResults,SQLSRV_FETCH_ASSOC))
{
$sql[] = "('".$row['ReportName']."'),"; // Add apostrophes, change to comma
$test = "INSERT INTO PublishedComments (ReportName) VALUES ".implode(",",$sql) . ';'; // Add semicolon
echo $test;
echo "<br />...........<br />";
}