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

 

Index.php

<?php
    include_once("config.php");
?>

 

Config.php

<?php
    //set off all error for security purposes
    error_reporting(E_ALL);
   

    //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" );

?>

 

DBClass.php

<?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();
        }
    }

    Connect_mysqlDB();

?>

 

 

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

Reference:

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

    Leave a Reply

    Your email address will not be published. Required fields are marked *