天天看點

使用pdo連接配接mysql資料庫使用pdo連接配接mysql資料庫

使用pdo連接配接mysql資料庫

1、簡單連接配接mysql資料庫

<?php
	$dbname = 'testdb';
	$host = '127.0.0.1';
	$dsn = "mysql:dbname={$dbname};host={$host}";
	$user = 'dbuser';
	$password = 'dbpass';
	
	try {
	    $dbh = new PDO($dsn, $user, $password);
	} catch (PDOException $e) {
	    echo 'Connection failed: ' . $e->getMessage();
	}
           

2、pdo單例模式連接配接資料庫

<?php
   class PdoExt extends PDO {
       static protected $_instance;
       protected function __contruct($dsn, $user, $password) {
           return parent::__construct($dsn, $user, $password);
       }
       
       static public function getInstance($dsn, $user, $password) {
           if (!isset(self::$_instance)) {
               self::$_instance = new self($dsn, $user, $password);
           }
           return self::$instance;
       }
   }
   
   $host = '127.0.0.1';
   $dsn = "mysql:host={$host}";
   $username = "root";
   $password = "root";
   // 連接配接資料庫
   $pdo = PdoExt::getInstance($dsn, $username, $password);
   // 設定sql語句
   $sql = 'SELECT user,host FROM mysql.user WHERE user = :user';
   $statement = $pdo->prepare($sql);
   // 給:user綁定值
   $statement->bindParam(':user', $username);
   // 執行查詢
   $statement->execute();
   // 取結果中2條資料
   $users = $statement->fetchAll(2);
   print_r($users);