Skip to content

PHP MySQL Database Connection Class, OOP

Share Button
  <?php 

/**
 *  MySQL Database configuration settings
 *  Database Constants
 *  If constants are defined, CONNECT else, DEFINE CONSTANTS.
 *
 *  Fill Values below with your own DB Credentials
*/

/** MySQL Server - 127.0.0.1 or localhost */
defined("DB_SERVERR") ? null : define("DB_SERVER", "127.0.0.1");

/** MySQL Database to be Connect to */
defined("DB_NAME") ? null: define("DB_NAME", "your_db_name");

/** MySQL database username */
defined("DB_USER") ? null : define ("DB_USER", "your_db_user");

/** MySQL database password */
defined("DB_PASSWORD") ? null : define ("DB_PASSWORD", "your_db_pass");

/** Simple Database Connection Class */
class connToDB{
    
    private $connection;
    
    // Constructor
    function __construct()
    {
        $this->open_connection();
    }
    
    
    // Open MySQL Connection
    public function open_connection() 
    {
        /** Try Connection...*/
        try
        {
                    /** Establish Database Connection with mysqli */
            $this->connection = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
        }
        /** Catch Exception */
        catch(Exception $except)
        {
            die("Unable to connect to Database");
        }
    }
} // class End

/** Instance of a connToDB class */
$connect = new connToDB();

/** Double check if Connection has been established */
if($connect)
    echo "Connected To ".DB_NAME." database";

?>
Share Button