开发者

How can I efficiently retrieve a large number of database settings as PHP variables?

开发者 https://www.devze.com 2022-12-25 09:20 出处:网络
Currently all of my script\'s settings are located in a PHP file which I \'include\'. I\'m in the process of moving these settings (about 100) to a database table called \'settings\'. However I\'m str

Currently all of my script's settings are located in a PHP file which I 'include'. I'm in the process of moving these settings (about 100) to a database table called 'settings'. However I'm struggling to find an efficient way of retrieving all of them into the file.

The settings table has 3 columns:

  • ID (autoincrements)
  • name
  • value

Two example rows might be:

admin_user            john
admin_email_address   john@example.com  

The only way I can think of retrieving each setting is like this:

$result = mysql_query("SELECT value FROM settings WHERE name = 'admin_user'");
$row = mysql_fetch_array($result);
$admin_user = $row['value'];

$result = mysql_query("SELECT value FROM settings WHERE name = 'admin_email_address'");
$row = mysql_fetch_array($result);
$admi开发者_开发知识库n_email_address = $row['value'];

etc etc

Doing it this way will take up a lot of code and will likely be slow.

Is there a better way?


100 settings? Load them all at once. That will take no time at all. You absolutely do not want to load them one at a time.

$result = mysql_query('SELECT * FROM settings');
$settings = array();
while ($row = mysql_fetch_assoc($result)) {
  $settings[$row['name']] = $row['value'];
}

If you need to compartmentalize these somehow, depending on how you need to do it, you could put a category or something on the table and then just load all the settings in a particular category.

What I would suggest is abstracting this behind an object of some kind:

class Settings {
  private $settings;

  public function __get($name) {
    if (!$this->settings)) {
      $result = mysql_query('SELECT * FROM settings');
      $this->settings = array();
      while ($row = mysql_fetch_assoc($result)) {
        $this->settings[$row['name']] = $row['value'];
      }
    }
    return $this->settings[$name];
  }
}

This way the settings aren't loaded until you try and access one:

$settings = new Settings;
echo $settings->admin_name; // now they're loaded


Well I seem to have figured it out:

$settings = mysql_query("SELECT * FROM settings");

while ($row = mysql_fetch_assoc($settings)) {
eval('global $' . $row['name'] . ';');
eval('$' . $row['name'] . ' = "' . $row['value'] . '";');
}

It works although I wasn't keen on using eval(), but I think it's the only way.

I'm now wondering whether many hosts have eval() disabled. Any thoughts?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号