bravo14 Posted January 9, 2013 Share Posted January 9, 2013 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. Quote Link to comment https://forums.phpfreaks.com/topic/272910-explode-and-add-to-db/ Share on other sites More sharing options...
scootstah Posted January 9, 2013 Share Posted January 9, 2013 (edited) 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 January 9, 2013 by scootstah Quote Link to comment https://forums.phpfreaks.com/topic/272910-explode-and-add-to-db/#findComment-1404509 Share on other sites More sharing options...
Barand Posted January 9, 2013 Share Posted January 9, 2013 On the last line implode($insert) should be implode(',', $insert) Quote Link to comment https://forums.phpfreaks.com/topic/272910-explode-and-add-to-db/#findComment-1404513 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.