defining a globalize database connection string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
beckbapegeneral
Forum Newbie
Posts: 19
Joined: Mon May 08, 2006 8:59 pm

defining a globalize database connection string

Post by beckbapegeneral »

hi, can anyone of you teach me how to define a globalize database connection string so that i can just call it from any files instead of having to define a new connection string everytime. and also where do i define the global database connection string at?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

No matter what, the database will have to be connected to, by the script, on each page request needing the database. If you include() a script that creates the connection for you it can be more simple as far as remembering to start it up.
beckbapegeneral
Forum Newbie
Posts: 19
Joined: Mon May 08, 2006 8:59 pm

Post by beckbapegeneral »

thanks moderMonkey :D
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Post by dibyendrah »

Create the file dbconfig.php

Code: Select all

<?php
define("HOST", "HOST_NAME");
define("PORT", 3306);
define("USER", "USER_NAME");
define("PASS", "PASSWORD");
define("DB", "DATABASE_NAME");
?>
After that whichever page needs the connection, just include the dbconfig.php

Code: Select all

include("path/to/dbconfig.php");
$conn = mysql_connect(HOST, USER, PASS, DB, PORT);  //<- This will use the Global Constants
Cheers,
Dibyendra
beckbapegeneral
Forum Newbie
Posts: 19
Joined: Mon May 08, 2006 8:59 pm

Post by beckbapegeneral »

thanks alot :D
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Because all of my apps rely on a database connection, I usually develop a DB functions class (PHP4) and instantiate the db object at the end of the class. If the connection is not good, I set the script to die.

I then include this class as an include in a common file and include the common file at the beginning of each page, so that on every page, regardless of where it is in the site, will load, instantiate and check the db connection, dying on failure or continuing upon success.
User avatar
dibyendrah
Forum Contributor
Posts: 491
Joined: Wed Oct 19, 2005 5:14 am
Location: Nepal
Contact:

Post by dibyendrah »

Alternate option is to use ADOdb Database Abstraction Library for PHP (and Python) for MySQL .

http://adodb.sourceforge.net/

Dibyendra
Post Reply