Sunday, 15 December 2013

How to create mysql connection in php

Leave a Comment
 The example will show how to create connection to MySQL database using "mysql_connect" or "mysqli_connect" . The mysql_connect has been deprecated. Read here for more information.

The  DbUtil Class

<?php

final class DbUtil {
    
    public static $dbHost ;
    public static $dbUser ;
    public static $dbPass ;


    public function __construct() {  
        self::$dbHost = "<host name>";
        self::$dbUser = "<user name db>";
        self::$dbPass = "<pasword db>";
        }

   public static function getDbConnectionMySQL() {     
        return mysql_connect(self::$dbHost, self::$dbUser, self::$dbPass); //Connect to the databasse        
    }
    public static function getDbConnectionMySQLi() {      
        return mysqli_connect(self::$dbHost, self::$dbUser, self::$dbPass); //Connect to the databasse        
    }




?>


How to use Example

1. Create php file name index to test the class
2. copy paste this code and try to run in browser using xamp / any web server install with php

<?php

require_once('DbUtility.php');
$dbClass = new DbUtility();
$db = $dbClass->getDbConnectionMySQLi();
if (mysqli_connect_errno($db)) {
    echo '<br/>Failed to Connect to Database' . mysqli_connect_error();
} else {
    echo '<br/>successfully create connection with "mysqli_connect"';
}

$db1 = $dbClass->getDbConnectionMySQL();
if (mysql_error($db1)) {
    echo '<br/>Failed to Connect to Database' . mysqli_connect_error();
} else {
    echo '<br/>successfully create connection with "mysql_connect"';
}
?>

The Output



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.