Page 233 - Open Soource Technologies 304.indd
P. 233
Open Source Technologies
Notes It’s a common practice to place the routine of opening a database connection in a separate file.
Then everytime you want to open a connection just include the file. Usually the host, user,
password and database name are also separated in a configuration file.
An example of config.php that stores the connection configuration and opendb.php that opens
the connection are:
Source code:
config.phps , opendb.phps
<?php
// This is an example of config.php
$dbhost = ‘localhost’;
$dbuser = ‘root’;
$dbpass = ‘password’;
$dbname = ‘phpcake’;
?>
<?php
// This is an example opendb.php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (‘Error connecting to mysql’);
mysql_select_db($dbname);
?>
So now you can open a connection to mysql like this:
<?php
include ‘config.php’;
include ‘opendb.php’;
// ... do something like insert or select, etc
?>
14.1.2 Closing the Connection
The connection opened in a script will be closed as soon as the execution of the script ends.
But it’s better if you close it explicitly by calling mysql_close() function. You could also put this
function call in a file named closedb.php.
Source code: closedb.phps
<?php
// an example of closedb.php
// it does nothing but closing
// a mysql database connection
mysql_close($conn);
?>
228 LOVELY PROFESSIONAL UNIVERSITY