Categories
MySQL PHP

Loading configuration data from a MySQL into PHP constants

The following code will take the contents of the first row of a configuration table and create a constant for each attribute stored in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// ----------------------------- LOAD CONFIGURATION DATA FROM DATABASE -----------------------------
// Each data element in first row is placed in a constant using attribute name as constant name
// The array_slice function eliminates the first attribute in the row, 'id', which is the primary
//   key and not relevant for our purposes.
$result = mysql_query("SELECT * FROM configuration WHERE id = '1'") or die(__LINE__." SELECT Error: ".mysql_error());
if($result != false and mysql_num_rows($result)) {
    foreach(array_slice(mysql_fetch_assoc($result), 1) as $key => $val) {
        if(!defined($key)) {
            define(strtoupper($key), $val);
        } else {
            user_error("'$key' already defined.");
        }
    }
}
// ---------------------------- /load configuration data from database -----------------------------

Leave a Reply