Can I store a string into a single field in mySQL that I can echo in PHP, that also declares variables?
I have a .php page that has variables, each associated with dozens of different search criteria. I thought it would be easiest to just jam all the variables into the database as one gigantic string.
Then I thought it would be even EASIER to jam the variables and their declarations with them as one giant string.
So what I mean is, instead of just this:
Stewie
101
Green
I would instead like to have this as one big blob in the database:
$user_name = 'Stewie';
$pants_size = '101';
$favorite_eggs = 'Green';
That way, I would be able to VERY easily capture and extract a large amount of user preference data without having to do much in the way of arrays. After all, I have to change the page often enough that altering arrays would be a headache.
If I could do this, I could simply and it would be able to simply redeclare all the variables all at once, and I wouldn't have to think about it any more.
The records don't need to be searchable, just extractable with the variable declaration (like $var='value'; with the quotemarks and all).
What I investigated so far is as follows:
- A javascript option. Yes, I know it would be possible to do some elaborate stuff with javascript, but it is far more complicated than my "one big variable that I want to echo, but magically also declare variables in" method. If I do this, I may as well do arrays.
- An array option. This involves implode / explode stuff in .php, and is what I fear I will have to wind up choosing before too much longer. However, I would rather do it the one-step method I envision instead, if possible.
- A 'store each variable separately in its own field in the database' option. This is horrible, because the fields change (and are added to) often enough that it would drive me batty. I would far sooner do the array option, because it's just a few little user preferences.
Any help at all would be appreciated, even if it is to tell me, "This isn't possible. I recommend [XYZ]."
Thanks!
EDIT: dave e has a great solution below for retrieving such data, via eval. But I am still a bit stumped as to how to get th开发者_运维问答at data into the database to begin with. Storing >100 variables and their declarations ($variable_name='value') with the same ease is a bit perplexing!
Make an aray of options like this:
$option_array['user_name'] = 'Stewie';
$option_array['pants_size'] = '101';
Use serialize to store the data
$stored_string = serialize($option_array);
when you get back data from db unserialize it $option_araay = unserialize($option_array);
!
Using a comment from http://www.php.net/manual/en/function.get-defined-vars.php#73608
Use this slightly adapted function
/**
* @desc works out the variables in the current scope(from where function was
* called). Returns a serialized version of an array with variable name
* as key and vaiable value as value
* @param $varList: variables returned by get_defined_vars() in desired scope.
* $excludeList: variables to be excluded from the list.
* @return string
*/
function get_refined_vars($varList, $excludeList) {
$temp1 = array_values(array_diff(array_keys($varList), $excludeList));
$temp2 = array();
while (list($key, $value) = each($temp1)) {
global $$value;
$temp2[$value] = $$value;
}
return serialize($temp2);
}
Then create the exclude list array
$excludeList = array('GLOBALS', '_FILES', '_COOKIE', '_POST', '_GET', 'excludeList');
Define your variables
$user_name = 'Stewie';
$pants_size = '101';
$favorite_eggs = 'Green';
Now get all your define variables into a serialzied string
//get all variables defined in current scope
$varList = get_defined_vars();
// refine the list, serialized.
$storeThis = get_refined_vars($varList, $excludeList);
Store the $storeThis value in your mysql table
When you get the string out of mysql...
extract(unserialize($someStringFromDatabaseResult));
echo $user_name;
echo $pants_size;
echo $favorite_eggs'
try this:
$data = array();
$data['user_name'] = 'Stewie';
$data['pants_size'] = '101';
$data['favorite_eggs'] = 'Green';
$one_big_string = serialize($data);
// store $one_big_string in your database.
$one_big_string_from_db // <= string from db
extract(unserialize($one_big_string_from_db));
// All array keys will become local variables.
I think if you want to do something like that, you should store all prefs into an array and store the array into the db. Have a look at serialize
: serialize() on php.net
You should look at PHP eval ( http://php.net/manual/en/function.eval.php ) , This can covert text from a DB into literal PHP. However you are opening yourself up to a lot of potential security issues if used incorrectly.
An example :
$code = get_whatever_from_DB();
$code = "
$user_name = 'Stewie';
$pants_size = '101';
$favorite_eggs = 'Green';
";
eval('?>' . $code . '<?');
Use an array for your user data like this:
$USER['name'] = 'Stewie';
$USER['size'] = 101;
$USER['eggs'] = 'Green';
then:
mysql_query('UPDATE users SET data="'.serialize($USER).'" WHERE id='.$uid);
And to fetch:
$q = mysql_query('SELECT data FROM users WHERE id='.$uid);
if($r=mysql_fetch_object($q)) $USER = unserialize($r->data);
else echo 'Error no such user id: '. $uid;
I'm using the JSON format to store settings in one of my projects, and it works great. Here is my class for working with the JSON:
<?php
/**
* Settings getter and setter
*/
class Settings
{
private $settings;
function __construct($rawSettings)
{
$this->settings = json_decode($rawSettings);
}
// returns the serialized settings object, so we can save it someware
protected function Serialized()
{
return json_encode($this->settings);
}
// return the setting, or null if it is not set
public function Get($setting)
{
if (isset($this->settings->$setting)) return $this->settings->$setting;
else return null;
}
public function Set($setting, $value)
{
$this->settings->$setting = $value;
}
}
?>
Fetch the settings from the DB and pass them to the constructor,
$settings = new Settings($jsonStringFromDB);
Use the Set method to set new values,
$settings->Set('name','Stewie');
$settings->Set('pant_size','101');
$settings->Set('favorite_eggs','Green');
Use the Get method to get values,
echo $settings->Get('name');
And when storing to DB, just use $settings->Serialized();
Now the settings is stored in a format not unique to PHP, might be a good thing sometime, who knows.
精彩评论