How to create mysql connection in php

 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 =)

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example