使用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 = 'SELECT user,host FROM mysql.user WHERE user = :user';
$statement = $pdo->prepare($sql);
$statement->bindParam(':user', $username);
$statement->execute();
$users = $statement->fetchAll(2);
print_r($users);