This is my standard approach to db connectin. I create a connection file called conn.php and place it outside the root folder (something like /myconfig/conn.php). Then i include this file into any file i need that has db access ... see code below.
This code does manage to fail a little more gracefully than others and will send out an email notification to you so that you can see what crashed and why.
Placing the code into a function will also make it more secure and simpler to call. There is some basic security in the file. The first time this is run, it will likely fail and present a message saying
"piss off, hackers".
Above that there is the line 'server is:' and some name, likely the website name (yourdomain.com / yourdomain.ca, whatever)copy the name and paste it back into the conn.php where it currently says 'localhost'...if no error comes up then the code is fine...then comment out the echo line.
Its easy to add further checks to prevent inclusion by other users. Sessions is one.
<?php
//conn.php
bastien koert
Aug 2004
www.bastienkoert.net
this domain -- this check may take a little configuration to get the correct host name
use this the first time to get the host name...then comment it out or delete to complete the security check */
//echo "server is : ".$_SERVER['SERVER_NAME']."<br>";
if (($_SERVER['SERVER_NAME']!="localhost")){
echo "piss off, hackers!";
die();
}
function conn($sql)
{
$host = "myhost"; /* change these to match your situation */
$user = "myusername";
$pass = "mypassword";
$db = "mydb";
if (!($conn=mysql_connect($host, $user, $pass))) {
printf("Error connecting to DB");
email_error("connection",mysql_error());
}
if (!($db3=mysql_select_db($dbname,$conn))){
printf("<p>Error connecting to DB");
email_error("Connection Error",mysql_error());
}
$result = mysql_query($sql);
if (mysql_errno() == 0){
return $result;
}else{
email_error($sql,mysql_error());
$result = 'Null';
}
}//end function