How to Connect MySQL with PHP
To design dynamic data-driven website with PHP we need to connect with MySQL. This is an extremely important step to establish a connection to the MySQL database. If your script cannot connect to its database, your queries to the database will fail.
Opening a connection to MySQL database from PHP is easy. This can be done with the “mysql_connect†PHP function which helps us open a connection to a MySQL Server and we need to use it as below:
<?php
$dbhost = 'localhost'; //MySQL Host
$dbuser = 'root'; //MySQL User
$dbpass = 'password'; //MySQL Password
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'TestDb'; //MySQL Database to work on
mysql_select_db($dbname);
?>
This is good practice to Connect MySQL with small scale development. While with a large scale development it’s good to use Class an Object Oriented scenario of PHP development.
Connect MySQL with PHP with a Class
Now we will do the same with a PHP class. The piece of code described below will do it for you.
A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object).
<?php
class connect_db {
  function DB() {
    $this->host = "'localhost'"; //MySQL Host
    $this->db = "SourceDB"; //MySQL Database
    $this->user = "SourceUser"; //MySQL User
    $this->pass = " SourcePass"; //MySQL Password
    $this->link = mysql_connect($this->host, $this->user, $this->pass);
    mysql_select_db($this->db);
    register_shutdown_function(array(&$this, 'close'));
  }
 Â
  function query($query) {
    $result = mysql_query($query, $this->link);
    return $result;
  }
 Â
  function close() {
    mysql_close($this->link);
  }
}
?>
Create a new file “connect_db.php†and paste the code to it. To use the above class include “connect_db.php†and create an instance of a class connect_db. To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation.
<?php
require_once("connect_db.php");
$DB = new connect_db;
?>










