Saving configuration information using key value pairs

Print pagePDF pageEmail page

There are times when you need to save configuration information for a project. I get this requirement time and again. Since most of my projects are database driven, I decided to use a database table dedicated to save this config info. I also developed few functions to read and set these settings.

Setting up the database

First here’s the table structure. Pretty simple though it has 3 fields (ie: columns) per record. The ‘metaId’ field is set to auto increment. So that every time I add a new record I don’t have to worry about setting a record id. ‘metaKey’ hold the name of the variable, or the ‘key’ and ‘metaValue’ hold the value of the variable. In order to understand the ‘table_prefix’ best practice, please go here. It will explain the meaning of ‘$dbprefix’ and ‘$db’variables.

Although I thought 50 characters are enough for a variable (and its value), you may need to increase/decrease that depending on your scenario. ‘int’ will make sure we will never run-out of variables; ie: it allows 65,536 key/value pairs ! You may need to index this with metaKey, but I didn’t because this only has 3 fields total.

Creating a new config variable

You can provide a metaValue at the time of creating a metaKey. If you do not provide one, 0 will be used.

Reading a config variable

I believe the code is self explanatory. I use plain vanilla db access code. With the LIMIT clause I only read 1 record. Although this is an extra precaution, I take care of this under ‘creating new config variable’. You need to make sure the variable $metakey is wrapped in inverted commas.

Changing the value of a config variable

Here’s a sample test file

This file first creates a key named ‘version’ with a default value ‘3.2’. Then value is changed to ‘3.3’ and is read and echoed to screen. This uses two include files. First one being database config file. Read here for more info.

Conclusion

The code can be further optimized, eg: doing away with the ‘$tmp’ variable, but then again the objective of keeping that is purely to do with usability.

I keep these functions under a file named ‘inc_functions.php’ and include it in all files, as below:

There also times where you do not want to use a database to save configuration information. XML would be the next best option. Let’s see how.

Downloads

SQL file, PHP function library and Test file

Share

3 thoughts on “Saving configuration information using key value pairs

  1. Hi can you also show how to use XML for the same purpose please. I am still not clear about XML under PHP.

    Thanks

  2. Cool idea indeed. Saves disk space, I used a text file for the same purpose. But things like file locks etc… made think of a better way to handle config info. You showed the perfect solution.

    Thanks for sharing.

Leave a Reply

Your email address will not be published. Required fields are marked *