当前位置 : 主页 > 网络编程 > PHP >

php pdo连接数据库

来源:互联网 收集:自由互联 发布时间:2021-06-30
?phpclass DAO{ private $dbh; public function __construct(){ $dsn = 'mysql:dbname=zrobot;host=127.0.0.1'; $user = 'root'; $password = 'zhudechao1877917'; try { $this-dbh = new PDO($dsn, $user, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND = "
 
<?php
class DAO{
    private $dbh;
    public function __construct(){
        $dsn = 'mysql:dbname=zrobot;host=127.0.0.1';
        $user = 'root';
        $password = 'zhudechao1877917';
        try {
            $this->dbh = new PDO($dsn, $user, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';"));
        } catch (PDOException $e) {
            echo 'Connection failed: ' . $e->getMessage();
        }
    }
    public function sRow($sql){
        $sth = $this->dbh->prepare($sql);
        $sth->execute();
        $ret = $sth->fetchAll(PDO::FETCH_ASSOC);
        return $ret[0];
    }
    public function sRows($sql){
        $sth = $this->dbh->prepare($sql);
        $sth->execute();
        return $sth->fetchAll(PDO::FETCH_ASSOC);
    }
    public function dbInsert($sql){
        $sth = $this->dbh;
        $count = $sth->exec($sql);
        if($count){
            return true;
        }else {
            return false;
        }
    }
    //insert update
    public function dbIUD($sql){
        $sth = $this->dbh;
        $count = $sth->exec($sql);
        if($count){
            return true;
        }else {
            return false;
        }
    }
}

网友评论