How to get connected with mysql database with the help of php?

| | 1 min read

To connect into MySQL database with the help of PHP based web applications we are in need of mysql_connect or by PDO method. Here i have added a common function which will be useful for the php based websites to connect into the database.

  
    /**
     * Function to connecting database.
     *
     */
    function db_get_connection() {
      static $db;
      try {
        if(!isset($db)) {
          $db = new PDO('mysql:host=hostname;dbname="database name", 'mysql user name', 'mysql user password');
          $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
      } 
      catch(PDOException $ex) {
        echo "An Error occured! " . $ex->getMessage();
      }
      return $db;
    }
  

In the above code i have added a functionality which you can add in to your include files and make an use of it whenever you want to connect with the database you can call the function which you added in your database. If you are not able to conncet to the database it will return the error message.

$db = new PDO('mysql:host=hostname;dbname="database name", 'mysql user name', 'mysql user password');

In this line the connection process is carried out. We have to mention database name, user name and user password of mysql