时间:2021-07-01 10:21:17 帮助过:36人阅读
在PDO出现之间,在PHP中连接数据库的函数根据数据库的不同而不同。
例如,MySQL用 mysql_connect 函数, PostgreSQL数据库用 pg_connect 函数。
通过PDO编写的代码,今后数据库发生变化,只需要适当修改数据库的连接参数,不需要修改逻辑代码即可。
PDO和主要数据库的驱动同PHP一起作为扩展发布,要激活它们只需简单的编辑php.ini文件: extension=php_pdo.dll
然后,选择针对特定数据库的DLL文件使用 dl() 在运行时加载,或者在php.ini文件中 php_pdo.dll 行后启用它们,如:
extension=php_pdo.dllextension=php_pdo_mysql.dllextension=php_pdo_pgsql.dllextension=php_pdo_sqlite.dll
$dsn = 'mysql:dbname=yii2test;host=localhost';
$user = 'sqluser';
$password = 'sqlpassword';
$db = new PDO($dsn, $user, $password);
try{
$dbh = new PDO($dsn, $user, $password);
}catch (PDOException $e){
print('Error:'.$e->getMessage());
die();
}
$dsn = 'pgsql:dbname=yii2test host=localhost port=5432';
$user = 'sqluser';
$password = 'sqlpassword';
try{
$dbh = new PDO($dsn, $user, $password);
}catch (PDOException $e){
print('Error:'.$e->getMessage());
die();
}
$dsn = 'sqlite:d:/sqlite/yii2test.db';
$user = '';
$password = '';
try{
$dbh = new PDO($dsn, $user, $password);
}catch (PDOException $e){
print('Error:'.$e->getMessage());
die();
}
PDO操作MySQL数据库示范代码:
$dsn = 'mysql:dbname=yii2test;host=192.168.0.69;post=3306';
$user = 'shou';
$password = 'shouadmin';
try{
$db = new PDO($dsn, $user, $password);
// $sql = 'insert into user(username, password,password_hash, status) value (?, ?, ?, ?)';
$stmt = $db->prepare($sql);
$param = [];
$param[] = 'admin'. date('YmdHis');
$param[] = time();
$param[] = md5(time());
$param[] = 10;
if($stmt->execute($param)) {
echo"insert ok !" .PHP_EOL;
} else {
echo"insert ng !" .PHP_EOL;
}
// echo PHP_EOL. "==> query" . PHP_EOL;
$sql = "select * from user";
$data = $db->query($sql);
foreach($dataas$row) {
echo$row["username"] . " " . $row["password"]. PHP_EOL;
}
// echo PHP_EOL. "==> prepare 1" . PHP_EOL;
$sql = 'select * from user where username like ?';
$stmt = $db->prepare($sql);
$stmt->execute(['admin%']);
while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($result);
}
// echo PHP_EOL. "==> prepare 2" . PHP_EOL;
$sql = 'select * from user where username like :username';
$stmt = $db->prepare($sql);
$stmt->execute([':username' => 'admin%']);
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($result);
}
}catch (PDOException $e){
print('Error:'.$e->getMessage());
die();
}
// 关闭数据库连接$db = null;
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了PDO学习笔记,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。