tags:

views:

24

answers:

2

hello - just trying to add some setting for the admin in a database entry.

i've saved;

array('aviva'=>'aviva','teacher'=>'teacher');

into the field 'fullPara' but can't seem to get it back into an array? Just spits it out as a string and i've tried eval but not sure where to go from here?

echo $userTypes['fullPara']; // spits out array('aviva'=>'aviva','teacher'=>'teacher');

any pointers welcome!

best, Dan

+4  A: 

You want to look into the serialize() and unserialize() functions PHP offers.

Here is an example:

$array = array('1', '3', '4');
$s_array = serialize($array);
// insert that into the db.


// later on when fetching.
$array = unserialize($array_from_db); 
print_r($array); // viola

EDIT

I do NOT recommend this but here is how you would convert it to an array using eval:

eval("\$array = " . $data_from_Db);
print_r($array);

Should get you what you were after.

Brad F Jacobs
Probably the most foolproof way of *storing* an array. It's barely human-readable, though, so let PHP handle editing it (ie: Don't try "fixing" something with phpMyAdmin).
cHao
hey premiso - problem is the array strings already exist as array('aviva'=>'aviva','teacher'=>'teacher'); Basically we'll be adding typing them into phpmyadmin, seqlpro etc.
daniel Crabbe
@daniel: Ewwww. About the only way that's gonna be easily retrievable as an array is using `eval` -- and then you're opening yourself up to all kinds of crap.
cHao
Bad practice. You should really convert it to the serialization. To get it back the only way I would know how would be to either try and utilize this function http://www.php.net/manual/en/function.print-r.php#93529 , create your own routine or use eval, which I would highly **NOT RECOMMEND** using eval given that it can be potentially harmful to your system if bad / unchecked data is passed to it. Better to convert your items to use the proper methods that PHP offer.
Brad F Jacobs
+2  A: 

If you already have a string of "array('aviva'=>'aviva','teacher'=>'teacher'); " and you wish to turn it into an array, this should work...

$str = "array('aviva'=>'aviva','teacher'=>'teacher');"; 
eval("\$foo = $str");
var_dump($foo);

It's really not the best way of doing it though.

Cags
cheers cags - that works. Just wondering why its not the best way? Its just that all the arrays already exist as strings in the db so would take a bit of time to build an admin that indexes on insert...
daniel Crabbe
Since they already exist as strings then there's really not a good way around it. But it's a massive security risk running eval on your server. I guess this is restricted if you never allow write access to your database from your application. In the future if you wish to store an array in a database, I strongly recommend using serialisation as mentioned by premiso.
Cags
great - thanks all!
daniel Crabbe