Using a variable for your MySQL database

So, I’m working on a site making a bunch of changes.  I need to change the name of a database and well, to make a long story short, it’s called by name throughout all the files.  So I thought I’d do a quick post on how to use a variable name in place of the MySQL database name.  I had to figure it out myself, and had a hard time finding anywhere how to do it, although it’s not that difficult.

First off, you should have a config file that’s being called from every page in your site.  This way you can define some variables that you’ll be able to access throughout your site.  This is pretty common and is in fact the case on the site I’m working on.

Your config file should look something like this:

<?php

$dbhost = 'localhost';
$dbuser = 'mrcool';
$dbpass = 'coolpassword';
$dbname = 'database_name';

$dbh = mysql_connect($dbhost,$dbuser,$dbpass)
or die (mysql_error());

$setts['sitename'] = "My Super Cool Site";
$setts['siteurl'] = "http://www.mysupercoolsite.com/";
$setts['email'] = "me@mysupercoolsite.com";
$setts['default_theme'] = "CoolTheme";
$setts['db_name'] = $dbname;

?>

This covers the basics and allows you to do a lot of cool things with your site.  Anywhere you need to put the base url, you can just use $setts['siteurl'] instead and it makes your whole site portable.  And, as the point of this post, you can use $setts['db_name'] in place of the actual name anywhere you need to.  You can even go one more and name all your tables as variables here, so they can be changed in one spot and affect the whole site.

Ok, last part here.  How to use the variable in place of the name:

Take:

$query = mysql_query(“INSERT INTO database_name.tblName (first, second, third) VALUES
(‘First Value’,'Second Value’,'Third Value’)”) or die(mysql_error());

And instead use:

$query = mysql_query(“INSERT INTO ” . $setts['db_name'] . “.tblName (first, second, third) VALUES
(‘First Value’,'Second Value’,'Third Value’)”) or die(mysql_error());

It’s just simple concatenation.  You have to close the quotes with ” then use the . as the connector, put in your variable name and then another . to add the rest which needs to have the quotes started again.

Hope that helps someone :)

This entry was posted in MySQL, PHP, Techy and tagged , , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Tony says:

    11?
    Yes, the devT of hard coding a file name in the code. and Hey, it stopped working. All I did was change the name.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>