spyda46
spyda46

Reputation: 19

php array mysql insert

This foreach loop only inserts one (the last value in the array) record, the array contains about 20 values. Can someone please help I can;t seem to work this one out

foreach ($array as $key => $value) {


 $sql = " INSERT INTO table3 (date, header, header2) VALUES (CURRENT_DATE(), '".$key."', '".$value."') " ;

 }

Upvotes: 0

Views: 61

Answers (3)

himeshc_IB
himeshc_IB

Reputation: 863

Try this optimized way as it will reduce your database operation and boost execution speed..

$sql = " INSERT INTO table3 (date, header, header2) VALUES ";
foreach ($array as $key => $value) {
 $sql .= "(`".CURRENT_DATE()"`, `".$key."`, `".$value."`),";
}
$sql = trim($sql ,',');
$mysqli->query($conn, $sql);

Upvotes: 2

shubham715
shubham715

Reputation: 3302

Try this

foreach ($array as $key => $value) {


 $sql = " INSERT INTO table3 (date, header, header2) VALUES (CURRENT_DATE(), '".$key."', '".$value."') " ;
 $sqlquery = mysqli_query($conn, $sql); //$conn is your connection variable 
 }

Upvotes: 2

jogoe
jogoe

Reputation: 324

Thats because you only define $sql, which is just a string, but don't actually execute the sql-statement.

You have to move the execution of your sql-statement into the loop for this to work.

e.g.:

foreach ($array as $key => $value) {

 $sql = " INSERT INTO table3 (date, header, header2) VALUES (CURRENT_DATE(), '".$key."', '".$value."') " ;
 $mysqli->query($sql);

 }

Upvotes: 2

Related Questions