Reply to comment

MySQL Database Connection
Submitted by devans on Mon, 2008-07-14 17:14The script that follows provides for an example way to use PHP to connect to a MySQL database through the use of a PHP Function.
The code that follows I will call db.php
<?php
function connect($sql)
{
// The following values should all be adjusted to suit your MySQL install.
$host="localhost";
$user="root";
$pass="password";
$db="users";
if(!($connect=mysql_connect($host,$user,$pass))){
printf("Error connecting to the database");
email_error("Server Connection Error", mysql_error());
}
if(!($dbselect = mysql_select_db($db, $connect))){
printf("<p>Error connecting to the database</p>");
email_error("Database Connection Error", mysql_error());
}
$result=mysql_query($sql);
if (mysql_errno() == 0){
return $result;
}
else {
email_error($sql, mysql_error());
$result = "Null";
}
}
?>
Being the ever vigilant system administrator we want the site to alert us of failed connection errors, which may be hack attempts. To do so we can get the web server to send out via it's predefined mail connector (look in your php.ini file) an email message with the error details. This could very easily be included as part of another file but sometimes it is just easier to have all of your functions reside in one location and include them from there.
<?php
// Begin the function that will send us email alerts following failure
function email_error($reason, $error)
{
$from = "alert@mydomain.com";
$headers = 'MIME-Version: 1.0\n';
$headers.= "Content-type: text/plain; charset=iso-8859-1\n";
$headers.= "X-Priority: 3\n";
$headers.="X-MSMail-Priority: Normal\n";
$headers.="X-Mailer: php\n";
$headers.="From:\"".$from."\"<".$from.">\n";
$sendto = "me@mydomain.com";
$subject = "MyDomain Error Notice";
$time = date("Y-m-d H:m");
$m1 = 'Site Error - Application Functionality Failed At '.$time."\n\n";
$m2 = 'GENERAL ERROR MESSAGE: '."\n".$reason."\n\n";
$m3 = 'MySQL ERROR MESSAGE: '."\n".$error."\n\n";
$m4 = 'Regards,'."\n\n";
$m5 = 'Automatic Pilot';
$message = $m1.$m2.$m3.$m4.$m5;
mail($sendto, $subject, $message, $headers);
die("<p>There was a problem with the database</p>");
}
?>
Then to use the above database connection function (with integrated email alerts) you would call it in a manner like this:
Example.php
<?php
//include the database connection function file db.php
include("include/db.php");
//remember that the connect function relies on the input supplied through the variable $sql.
$sql = "select * from member where username='dave.evans'";
$resultset = connect($sql);
if ($resultset){
// Do something
while($row=mysql_fetch_array($resultset)) {
echo ("Resultset is: ".$row['username']."<br>");}
}
else {
// Do something else or nothing at all
}
?>
That's all there is to it. Enjoy!

RSS Feed

