2015-11-18 79 views
0

检索数据我想学习PHP的面向对象的概念,并具有使用PDO如下数据库连接:使用PDO连接

class db{ 
private $host; 
private $user; 
private $pass; 
private $dname; 
private $conn; 

function __construct(){ 
    $this->host = "localhost"; 
    $this->user = "root"; 
    $this->pass = ""; 
    $this->dname= "nast"; 
    $this->connect(); 
} 

function __destruct(){ 
    $this->disconnect(); 
} 

function connect(){ 

    if(!$this->conn){ 

     try{ 
      $this->conn = new PDO('mysql:host='.$this->host.'; dbname='.$this->dname.'', $this->user, $this->pass, 
            array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); 
     } 

     catch(Exception $e){ 
      die('Erreur:' .$e->getMessage()); 
     } 

     if(!$this->conn){ 
      $this->status_fatal = true; 
      echo'Connection Not Established'; 
      die(); 
     } 
     else{ 
      $this->status_fatal = false;   } 
    } 
    return $this->conn; 
} 

function disconnect(){ 
    if($this->conn){ 
     $this->conn = null; 
    } 
} 

}

并把它命名为“class.db.php”。我从互联网上得到它。

然后我尝试使用下面的代码

require 'class.db.php'; 

$bdd = new db(); // create a new object, class db() 
$sql = 'SELECT * FROM student'; 

$q = $bdd->query($sql); 
$q->setFetchMode(PDO::FETCH_ASSOC); 

$r = $q->fetch(); 
echo $r['id']; 

,以从数据库中检索数据,但它给了以下错误:

Call to undefined method db::query() in C:\xampp\htdocs\prac\class.my.php on line 8.

+1

你只有'connect'和'disconnect'方法,没有这种所谓的方法'query' –

回答

1

至于什么error说,功能query()不存在于你的db类中。添加查询功能,您db类,像这样:

function query($sql){ 
    $this->connect(); // open a connection 

    // do your codes here 

    $this->disconnect(); // close the connection 
} 
+0

感谢您的时间“Dexterb” ...正如我在oop上说的那样,这次你会很好地帮我在代码部分输入什么。我会很感激,因为有点困惑在这里写什么..... –