PDO connection properly

Discussion in 'PHP' started by piropeator, Feb 11, 2016.

  1. #1
    How is the correct form to set up a PDO Connection class properly?
     
    piropeator, Feb 11, 2016 IP
  2. malky66

    malky66 Acclaimed Member

    Messages:
    3,997
    Likes Received:
    2,248
    Best Answers:
    88
    Trophy Points:
    515
    #2
    malky66, Feb 12, 2016 IP
  3. piropeator

    piropeator Well-Known Member

    Messages:
    194
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    121
    #3
    Can you explain me:
    Case 1
    ====
    <?php
    class ConexionDB extends PDO {
        public function __construct () {
            try {
                    parent:: __construct('mysql:host=localhost;dbname=test;charset=utf8', 'root', 'keys');
                    parent:: setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                } catch (PDOException $err) {
                        die ('There is a Error in DB');
            }
        }
    
        function __destruct(){
        }
    }
    ?>
    PHP:
    In other file.php
    $query = "SELECT * FROM prueba";
           $BD = new ConexionDB();
           $recordSet = $BD->prepare($query);
           $recordSet->execute();
    PHP:
    Case 2
    ====
    class connect_pdo
    {
        protected $dbh;
        public function __construct()
        {
            try {
                $con = new PDO('mysql:host='.$db_host.'; dbname='.$db_name, $db_user, $user_pw); 
                $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
                $con->exec("SET CHARACTER SET utf8");
            }
            catch (PDOException $err) { 
                echo "harmless error message if the connection fails";
                $err->getMessage() . "<br/>";
                file_put_contents('PDOErrors.txt',$err, FILE_APPEND);
                die();
            }
        }
        public function dbh()
        {
            return $this->dbh;
        }
    }
    PHP:
    In other file.php
    $con = new connect_pdo();
    $con = $con->dbh();
    PHP:
    What is the diference between Case 1 and Case 2, and what is the more safe connection class?
     
    piropeator, Feb 15, 2016 IP