Thursday, June 30, 2011

How To Connect PHP with MySQL Database

There are many ways to compose the code for connecting php to mysql. I wrote one of those as alternative to be used for testing connection to database or use it as prerequisite to execute any SQL code.
<?php

class MySQL{
    public $host;
    public $username;
    public $password;
    public $dbname;
    private $link;

    public function __construct($host, $username, $password, $dbname){
        $this->connect($host, $username, $password, $dbname);
    }

    // connect to database.
    public function connect($host, $username, $password, $dbname) {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
        $this->dbname = $dbname;
        $this->link = mysql_connect($this->host, $this->username, $this->password);
        if(!$this->link) {
            die("Failed to connect database '".$this->dbname."': ".mysql_error().".");
        }
        mysql_select_db($this->dbname, $this->link) or die ("There is no database '".$this->dbname."'.");
        echo "Connection successful to database '".$this->dbname."'.";
    }
 
    // close database connection
    public function closeConnection(){
        if(isset ($this->link)){
            mysql_close($this->link);
            unset ($this->link);
            echo "Closing database connection successful.";
        }else{
            echo "Closing database connection failed.";
        }
    }
}

// connect to database and save the connection.
$host = "localhost";
$username = "root";
$password = "";
$databasename = "mydb";
@$mysql = new MySQL($host, $username, $password, $databasename);
$mysql->closeConnection();

?>
The code above is used to test connection to database. If you want to use it with other php file, make sure to put all 'echo' contained line of code and '$mysql->closeConnection();' into comment (use //... or /*...*/), Then use 'require_once' command in the beginning of each php file.
<?php

require_once 'MySQL.php';

// your lines of code

?>

No comments:

Post a Comment