Jump to content

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
https://forums.phpfreaks.com/topic/272910-explode-and-add-to-db/
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));
}

Edited by scootstah
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.