0

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."') " ;

 }
6
  • Because you don't have executed query inside the loop Commented Oct 18, 2016 at 12:51
  • You are overriding the $sql variable on every loop. Try using .= Commented Oct 18, 2016 at 12:52
  • because u r executing your query outside the loop, you need to execute query inside the loop Commented Oct 18, 2016 at 12:52
  • Technically, that loop doesn't insert any records. Commented Oct 18, 2016 at 12:54
  • @IanS In that case, it will require a semicolon at the end of each mysql statement Commented Oct 18, 2016 at 12:55

3 Answers 3

2

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 
 }
Sign up to request clarification or add additional context in comments.

5 Comments

but you can optimize it, you can use one query instead of multiple @spyda46
don't forget to accept answer if its helpful for you. :)
its an example of that what he miss in his code. :)
the only problem I am still having is the end value, is inserted twice - any ideas ?
@spyda46 remember to remove your sql-execution after the loop. Thats probably why it inserts the last one twice. :)
2

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);

 }

Comments

2

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);

3 Comments

best way, execute query at once.
this gives me -- PHP Parse error: syntax error, unexpected T_FOREACH
try to get it to work, but the above gives -- PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.