這周因為工作比較忙,就來分享個人常使用的PDO連線範例吧!
這邊分享兩種寫法,一種是單純PDO,一種是有使用Class的PDO分享給大家,那我們下篇文章見 !
普通寫法 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <?php $hostname = '127.0.0.1'; $username = 'root'; $password = ''; $db_name = 'test'; $dsn = "mysql:host=$hostname;port=3306;dbname=$db_name;charset=utf8";
try { $conn = new PDO($dsn, $username, $password); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); echo 'success'; } catch (PDOException $e) { echo $e->getMessage(); }
|
有使用 Class 寫法 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <?php class database { private $hostName = '127.0.0.1'; private $dbName = 'test'; private $userName = 'root'; private $password = ''; private $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false ]; private $pdo; public function __construct() { try { $this->pdo = new PDO( 'mysql:host=' . $this->hostName . '; port=3306;dbname=' . $this->dbName . ';charset=utf8mb4', $this->userName, $this->password, $this->options); } catch (PDOException $e) { echo $e->getMessage();
} } }
|