Sunday 15 December 2013

Select Database in PHP Example

Leave a Comment
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 =)

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.