King0r12 Posted March 7, 2015 Share Posted March 7, 2015 Hi just a quick one. I have data stored in session variables and the data is for example $_SESSION['name'] = item1, item2, item3 $_SESSION['type'] = a, b, c $_SESSION['color'] = blue, green, black What I'm trying to do now is get them into a DB like below. ID | NAME | TYPE | COLOR 01 | item1 | a | blue 02 | item2 | b | green 03 | item3 | c | black I believe I have to explode them but it hasn't worked. Can someone please send me on the right path. Cheers. Quote Link to comment Share on other sites More sharing options...
Ch0cu3r Posted March 7, 2015 Share Posted March 7, 2015 If your data is a comma delimited list then yes you would need to use explode. You would look over the arrays to get the data you require. Example code $names = explode(', ', $_SESSION['name']); $types = explode(', ', $_SESSION['type']); $colors = explode(', ', $_SESSION['color']); $value_pairs = array(); for($i = 0; $i < count($names); $i++) { // generate pairs of values for insert query $value_pairs[] = "('$names[$i]', '$types[$i]', '$colors[$i]')"; } // add the generated pairs of values to the insert query $sql = 'INSERT INTO table (name, type, color) VALUES ' . implode(', ', $value_pairs)'; mysql_query($sql); However you really should reconsider how your data is stored in the session you should not use comma debilitated lists ideally you should group the data in an array. Example when adding an item to the session $_SESSION[] = array('name' => 'item1', 'type' => 'a', 'color' => 'blue'); Quote Link to comment 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.