Published on: 2005-08-18 - Views: 13168

Digg! del.icio.us Furl reddit spurl bloglines ma.gnolia.com Yahoo MyWeb technorati blogmarks blinklist pixelgroovy Share this tutorial on tutorialicio.us! simpy
If you use PHP in your site you'll probably use a MySQL database too...then you'll need to make your PHP script connect to that database: here you'll find few simple lines that show you how to do it.

We'll even see how to write the code and organize our files in the best way to connect to several databases with minor page-code changes.

Save the following code block in a file named db1config.php
<?php
//the next 4 code lines are used to store your connection data into 4 variables that we will use to connect to the database
$host = 'your_mysql_server'; //it usually is localhost or something like sql.yourdomain.com
$username = 'your_username'; //this it your username for the database
$database = 'your_dbname'; //this is the database name
$password = 'your_password'; //this obviously is your password for the database
?>
Now we'll write a couple of PHP lines that are those which really open the connection using the data in the previous created file; save the following code block in a file named connect.php
<?php
$connect = mysql_connect($host,$username,$password) or die("Error connecting to Database! " . mysql_error());
mysql_select_db($database , $connect) or die("Cannot select database! " . mysql_error());
?>
Now when you want one of your scripts to connect to your database you simply have to put these 2 lines in your page (the page must be saved with .php extension) and your script will be able to conenct to your database.
<?php include 'db1config.php'?>
<?php include 'connect.php'?>
You might wonder why we made this in 2 separated files...well, the answer is really simple. If you have more than one database you can make several config files and then you can connect to the databases simply including one file rather than another:
//this connects to db1
<?php include 'db1config.php'?>
<?php include 'connect.php'?>
//this connects to db2
<?php include 'db2config.php'?>
<?php include 'connect.php'?>
//this connects to db3
<?php include 'db3config.php'?>
<?php include 'connect.php'?>