Jump to content

PHP Session variables


King0r12

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

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.