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);
$admin_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.
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:
This way the settings aren’t loaded until you try and access one: