kevibu kevibu - 8 days ago 5
SQL Question

php foreach statement to insert data into sql only inserting last line

I'm trying to use a foreach statement in PHP to insert data from an array into a SQL database. The array can vary from 40 to 80 lines of data. I'm using the following code:

foreach ($racelap as $lap){
$sql = "insert into laps (RaceID,Lap,time,Temp,Humidity) ";
$sql .= "values ($RaceID,'$lap[0]','$lap[1]',$lap[2],'$lap[3]')";

The code doesn't give me an error, but it only adds the last line of data, and ignores all other data.

The solution is probably simple, but I can't find it myself unfortunately.


Try this, use your query with insert multiple rows using a single SQL INSERT statement something like this :

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )


$sql = "insert into laps (RaceID,Lap,time,Temp,Humidity) values  ";
foreach ($racelap as $lap){
     $sql .= "($RaceID,'$lap[0]','$lap[1]',$lap[2],'$lap[3]') ,";
$sql =rtrim($sql,",");