批改状态:未批改
老师批语:
<?php
class Db{
// 连接参数
public $dsn;
public $username;
public $password;
// 连接属性
public $pdo;
// 连接方法
public function connect(){
// 使用PDO方式管理数据库,连接成功则返回PDO对象,赋值给对象属性pdo
$this -> pdo = new PDO($this->dsn,$this->username,$this->password);
}
public function __construct($dsn,$username,$password)
{
$this -> dsn = $dsn;
$this -> username = $username;
$this -> password = $password;
// 自动调用对象方法,连接数据库,$this除了可以调用变量,还可以调用方法
$this->connect();
}
public function __destruct()
{
// 析构方法,可以用来释放数据库
// TODO: Implement __destruct() method.
$this -> pdo = null;
}
}
$db = new Db('mysql:host=127.0.1.1;dbname=ouyangke;','root','root');
if($db->pdo){
echo '连接成功';
}
//读取数据测试
$sql = 'SELECT * FROM `user`';
$stmt = $db->pdo->prepare($sql);
$stmt -> execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $res){
print_r($res);echo '<br>';
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号