Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

Php Programming Code Examples

Php > Errors and Logging Code Examples

DB Connection Function with error handling and email failure notices

DB Connection Function with error handling and email failure notices <?php //conn.php /* 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 function email_error($reason, $error) { $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 = "[email protected]"; $subject = "Db error notification"; $time = date("Y-m-d H:m"); $message = "Application db interface failed at $time.\n\n Operation : $reason\n\n MySQL Error: $error \n\n User: ".$_SESSION['username']."\n\n Regards, System"; mail($sendto, $subject, $message, $headers); die("<p>There was a problem with the database"); } ?> To use this file, you include it and then simply call the function CODE FOR IMPLEMENTAION IN ASSOCIATED FILES //include conn file require("config/conn.php"); //more of your code $sql = "select * from tableName [where][group by][order by]"; // get the regular listing results $result = connect($sql); if ($result){ //show the results }else{ //handle failure in some way } ?>