Jump to content

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/295156-php-session-variables/
Share on other sites

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');
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.