Skip to content

PHP MySQL Connection With PDO

Share Button

<?php

/**
*
*  MySQL Connection with PDO
*  Fill Values below with your own MySQL Database Credentials
*
*   if constants are defined:       CONNECT
*   if constants are NOT defined:   DEFINE CONSTANTS
*   NOTE: It’s a good practice to keep Constants in separate file with appropriate permissions
*      
**/

/** server - 127.0.0.1 or localhost */
defined("DB_SERVERR") ? null : define("DB_SERVER", "127.0.0.1");
/** MySQL database */
defined("DB_NAME") ? null: define("DB_NAME", "your_db_name");
/** MySQL username */
defined("DB_USER") ? null : define ("DB_USER", "your_username");
/** MySQL password */
defined("DB_PASSWORD") ? null : define ("DB_PASSWORD", "your_password");
/* MySQL host & database name parameters */
defined("MYSQL_HOST_AND_DBNAME") ? null : define ("MYSQL_HOST_AND_DBNAME", "mysql:host=".DB_SERVER.";"."dbname=".DB_NAME);
class MySQL_PDO_CONN{

private $connection;

// Constructor
function __construct()
{
$this->open_connection();
}

/* Open MySQL Connection */
public function open_connection()
{

/* Try connection */
try {
$connection = new PDO(MYSQL_HOST_AND_DBNAME, DB_USER, DB_PASSWORD);

/* echo connection message */
echo 'Connected to Database<br/>';

/* Close connection */
$db = null;
}

/* Catch Exception*/
catch(PDOException $e)
{
echo $e->getMessage();
}

}
}// class End
/** Instance of a MySQL_PDO_CONN class 
*   Notice that there's no need to call open_connection() method as it
*   was already called in constructor
*/
$connect = new MySQL_PDO_CONN();

?>

Share Button