Select Database in PHP Example

This post is a extended from previous post. Read previous here

This example show how to select database schema / name in database MySQL :

The DbUtil Class

<?php

final class DbUtility {
   
    public static $dbHost ;
    public static $dbUser ;
    public static $dbPass ;
    public static $dbDatabase ;

    public function __construct() { 
        self::$dbHost = "localhost:3306";
        self::$dbUser = "custinfosys";
        self::$dbPass = "P@ssw0rd";
        self::$dbDatabase = "customerinfosys"; // database
    }

    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        
    }
   
    public static function setDatabaseMySQL($db){             
        mysql_select_db($db,self::$dbDatabase) or die("Couldn't select the database.");
    }
   
    public static function setDatabaseMySQLi($db){             
        mysqli_select_db($db,self::$dbDatabase) or die("Couldn't select the database.");
    }   
   

}
?>


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"';
    $dbClass->setDatabaseMySQLi($db);
    echo '<br/>successfully set database with "mysqli_select_db"';
}

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

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

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example