Supporting many web sites with one database

April 19, 2008

If you are restricted by the web hosting company about how many databases you can create, there is a trick you can use to get the maximum out of that ‘single’ database. The answer is to use a prefix with tables. The secret is to use the key every time you refer the tables.

Creating an include file

Apart from saving the prefix I use this file to save connection information as well. I also create the database connection here. So everytime I need database access to a file, I just include the file with:

  1. <?php
  2. require_once("inc_dbaccess.php");
  3. ?>

What’s in it

Since I use mySql for most of my apps, I use ‘pconnect’ instead of ‘connect’. This single step improves database access when used online. Go here for more info on connection pooling. ‘$db’ helps in many places. I used it many with ‘mysql_affected_rows’ to check successful execution of an SQL statement. $client variable is used here incase you do not wish to use the key/value pair system to save configuration information. But that is completely optional.

  1. <?php
  2. $url="localhost"; //you may need to change this
  3. $database="dbnamehere";
  4. $dbprefix = "sls_"; //use something that reminds you of the project
  5. $username="root";
  6. $password="";
  7. $client="client name here"; //this way you could use
  8.          the same app for many clients.
  9. $db=mysql_pconnect($url,$username,$password); //pconnect honours
  10.          connection pooling
  11. @mysql_select_db($database) or die( "Unable to select database");
  12. ?>

Usage

Here’s an example using the ‘dbprefix’ technique.

  1. <?php
  2. require_once("inc_dbaccess.php");
  3. $query = "SELECT category FROM ".$dbprefix."config WHERE metaKey=$metaKey";
  4. $result = mysql_query($query);
  5. if($tmp) { echo “db command successful”; }
  6. ?>

Conclusion

As you notice this include file has many uses; such as:

  1. Multiple applications using the same database
  2. Being able to check the status of SQL execution
  3. If you do not use key/value techniques for configuration management, this file can be used to save configuration information.

Downloads

PHP dbaccess library

Test file

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • BlinkList
  • Furl
  • Reddit
  • Technorati
  • Fleck
  • YahooMyWeb
  • Netscape
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
Rate this article (152 views)
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5 out of 5)
Loading ... Loading ...
Print This Post Print This Post   Email This Post Email This Post

Got something to say?