How can I effectively get a large number of database settings as PHP variables?

Currently, all my script settings are in a PHP file, which I 'include'. I move these settings (about 100) to a database table called “settings”. However, I am struggling to find an efficient way to extract all of them into a file.

The settings table contains 3 columns:

  • ID (auto increment)
  • name
  • value

Two examples could be:

admin_user            john
admin_email_address   john@example.com  

The only way I can find each parameter is as follows:

$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);
$admin_email_address = $row['value'];

etc.

Running this method will take a lot of code and will probably be slow.

Is there a better way?

+3
2

100 ? . . .

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

- , , , - , .

- :

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];
  }
}

, , :

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

, , , :

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

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

, eval(), , .

, eval(). ?

+1

Source: https://habr.com/ru/post/1738849/


All Articles