Jump to content

explode and add to db


bravo14

Recommended Posts

Hi Guys

 

I have the code below to explode a value split by '.' I then want to add each item to a database.

 


$club_id=mysql_insert_id();
   foreach($_POST['age'] as $value)
echo $value;
   //explode $value to insert into allocations
   $allocations=explode(".",$value);
   //insert into allocations

   $number = count($allocations);
   for ($i=0; $i<=$number; $i++) {
            // store a single item number and quantity in local variables
            $itno = $number[$i];
            $alloc = $allocations[$i];
print_r($allocations);
            if ($allocations[$i] <> '') {
                $add_allocations=mysql_query("INSERT INTO `allocations` (`club_id`,`group`) VALUES('$club_id','$alloc')") or die(mysql_error());
                }
                }

 

This is the error I am getting

 

1.3.Array ( [0] => 3 [1] => ) Array ( [0] => 3 [1] => ) Notice: Undefined offset: 2 in /home/sites/kidzlinkz.co.uk/public_html/add-link.php on line 90 Array ( [0] => 3 [1] => )

 

Can someone explain how I explode an array and then add those separate values to a database.

Link to comment
Share on other sites

You can simply use foreach here.

 

Also, you should construct a multi-row INSERT query, instead of running a query in a loop. Try this out:

$club_id=mysql_insert_id();
$insert = array();
foreach($_POST['age'] as $value)
{
   //explode $value to insert into allocations
   $allocations=explode(".",$value);

   foreach($allocations as $allocation)
   {
       if (!empty($allocation)) {
           $insert[] = "('$club_id', '$allocation')";
       }
   }
}

if (!empty($insert)) {
   mysql_query("INSERT INTO allocations (club_id, group) VALUES " . implode($insert));
}

Link to comment
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.