Connecting to your MySQL Database from a Php page using PDO (PHP Data Objects)


In order to connect to a MySQL DB from Php, you need to frame the connection string and






    //set off all error for security purposes

    //define some contstant
    define( "DB_DSN", "mysql:host=localhost;dbname=<myDBName>" );
    define( "DB_USERNAME", "root" );
    define( "DB_PASSWORD", "<myrootpasswordhere>" );

    define( "CLS_PATH", "class" );

    //include the classes
    include_once( CLS_PATH . "/DBClass.php" );





class DBClass {
    public function Connect_mysqlDB(){
        try {
            $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
            $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            echo ‘Connected Successfully’
        catch(PDOException $e) {
            echo ‘ERROR: ‘ . $e->getMessage();





There are other deprecated options to make connections to MySQL from PHP

  • the mysql is the historical API
  • the mysqli is a new version of the historical API,
  • PDO_MySQL, is the MySQL for PDO, PDO has been introduced in PHP, the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code(if you don’t use specific RDBM function in your queries), also object oriented


php – What is difference between mysql,mysqli and pdo? – Stack Overflow


    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.