Jump to content

Loop an insert


timmah1

Recommended Posts

I need to do an insert for everything in values

 

I have two separate variables

$sport = implode(',', $_POST['sport']);
$package = implode(',', $_POST['package']);

 

Now, I can insert the items into the database like so

sporta,sportb,sportc
packagea,packageb,packagec

 

But now I need to be able to insert each one as it's own row.

Meaning, if sport and package has 2 values separated by a ,

how can I insert these items twice?

 

I've tried a foreach statement, but it doesn't give me anything.

 

Any help would be greatly appreciated.

Thanks in advance

Link to comment
https://forums.phpfreaks.com/topic/137824-loop-an-insert/
Share on other sites

This is what I have been trying

$sport = implode(',', $_POST['sport']);
$package = implode(',', $_POST['package']);


$sports1;
$sports1[$package] = $package;
$sports1[$sport] = $sport;		
foreach( $sports1 as $value){

$sq7 = "INSERT INTO memPack(package, sport, exp, user) VALUES(
			'$value',	
			'$value',										
			'$expDate',
			'$email');";
			mysql_query($sq7)
			or die("Sorry, there was a problem COMPLETING your order ".mysql_error());													
}

It inserts one line for package, and one line for sport

I need to try and get the package inserted, then the sport, package, then sport, not both sports together separated by a comma

Link to comment
https://forums.phpfreaks.com/topic/137824-loop-an-insert/#findComment-720323
Share on other sites

You're using implode (which returns a string) instead of explode, then trying to process that string as thought it is an array (using foreach).

 

$sports = explode(',',$_POST['sport']);
$packages = explode(',',$_POST['package']);
$count = count($sports);
for ($i = 0; $i < $count; $i++) {
   $sport = $sports[$i];
   $package = $packages[$i];
   $sql = "INSERT INTO memPack(package, sport, exp, user) VALUES('$sport','$package','$expDate','$email')";
   mysql_query($sql)
      or die("Sorry, there was a problem COMPLETING your order ".mysql_error());
}

 

And make sure you escape your $_POST vars as well

Link to comment
https://forums.phpfreaks.com/topic/137824-loop-an-insert/#findComment-720331
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.