ホーム

オブジェクト指向でPDO - PHP

実装

<?php 

class Database
{
    protected $dbh;
    function getDBH()
    {
        try{
            $dsn = 'mysql:host=localhost; dbname=test1;charset=utf8;';
            $user = 'root';
            $password = 'root';
            $this->dbh = new PDO($dsn, $user,$password);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            $this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
        }catch(PDOException $e){
            die($e->getMessage());
        }
    }
}

class DataSelect extends Database
{
    function __construct()
    {
        $this->getDBH();
    }
    function test()
    {
        try{
            $sql="SELECT * FROM tb";
            $stmt = $this->dbh->prepare($sql);
            $stmt->execute([]);
            $rows=$stmt->fetchAll(PDO::FETCH_ASSOC);
            print_r($rows);
        }catch(PDOException $e){
            die($e->getMessage());
        }
    }
}
$myExec=new DataSelect;
$myExec->test();

 ?>

-ホーム

Copyright© off , 2020 All Rights Reserved Powered by AFFINGER5.