Forum Moderators: coopster & phranque

Message Too Old, No Replies

Storing hash in database.

Comma separated like key,value,key,value,key,value...

         

Dabrowski

12:38 am on Feb 23, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



ok, I have some data that I want to store in a database. Basically it's session parameters.

I don't want to use fixed columns becuase the data won't need to be searched or anything like that, and because I'll use it for all sorts of different data over the whole site.

I want to convert the hash into a comma separated list so I can just store it as text, and convert it back again when I read the session data.

Example hash:
$h -> {user} = 53;
$h -> {screen_name} = "Bob";
$h -> {choice} = 7;

Would be stored as:
user,53,screen_name,Bob,choice,7

I'm not bothered about accommodating for array values, or infact strings containing commas as I don't think I'll have any. If I have I'll just escape them or something.

phranque

2:51 am on Feb 23, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



you can access a hash in list context, so maybe something like this would work:
$csl = join (',', (%h));

adwatson

7:37 pm on Feb 25, 2008 (gmt 0)

10+ Year Member



I'd recommend using something other than a comma as your delimiter, since a comma may be part of the data being stored - perhaps a string like "<>" or possible a tab - or something else that's unlikely to be in data. Then just split on those characters to pull the data out.

maximillianos

9:16 pm on Feb 29, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Are you using Java or PHP? You can use a function called "serialize()" to serialize your session data, then when you pull it out, you can "unserialize()" it to restore it.

Dabrowski

11:03 am on Mar 3, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Are you using Java or PHP?

No, I'm using Perl, hence posting in the Perl forum. I will try Phranque's suggestion this week I have some time to work on it.

Dabrowski

3:04 pm on Mar 4, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That worked a treat Phranque thankyou.

It even works in reverse:
( %$h) = split( /,/, $string);

Ta.

phranque

12:50 pm on Mar 5, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



quite welcome.
and as you noticed i missed the extra dollar sign in your context...