Insert multiple data into the database at once

I have this code that allows me to insert some dates that I selected in the database, now this one inserts only one value, not all, it seems to stop at the first value.

Could you tell me what I am doing wrong?

Thanks!

$job_id=$_REQUEST['job_id']; $dates = explode(",", $_POST['altField']); foreach($dates as $date){ $sql="INSERT INTO date (job_id,date) VALUES('$job_id','$date')"; mysql_query($sql); } 
+4
source share
3 answers
 $job_id=$_REQUEST['job_id']; $dates = explode(",", $_POST['altField']); foreach($dates as $date){ $values .= '("'.$job_id.'","'.$date.'"),'; } $sql="INSERT INTO date (job_id,date) VALUES " . substr($values, 0, -1); mysql_query($sql); 

Insertions can have multiple sets of values, so you just need to set the values ​​in foreach, and then outside it, execute the query. you can also do it this way and get the same result

 $job_id=$_REQUEST['job_id']; $dates = explode(",", $_POST['altField']); foreach($dates as $date){ $values[] = '("'.$job_id.'","'.$date.'")'; } $sql="INSERT INTO date (job_id,date) VALUES " . implode(',',$values); mysql_query($sql); 

REMINDER

ALWAYS sanitize your entrances. Failure to do so could result in SQL injection and cause serious problems for you. Take a look at this. Also mysql is not supported and it is suggested to switch to MySqli or PDO.

0
source
 $job_id=$_REQUEST['job_id']; $dates = explode(",", $_POST['altField']); $values_arr = array(); foreach ($dates as $date) { $values_arr[] = "('" . $job_id . "','" . $date . "')"; } $values = implode(", ", $values_arr); $sql="INSERT INTO date (job_id,date) VALUES $values"; mysql_query($sql); 
+1
source

to try:

 $sql = "INSERT INTO date SET job_id='".$job_id."', date='".$date."'"; mysql_query($sql); 
-1
source

All Articles