Blogger Information
Blog 27
fans 0
comment 0
visits 22410
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用类连接数据库
不乖的博客
Original
827 people have browsed it

实例

<?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>';
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post