我正在尝试学习PHP OOP概念,并使用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'];
但它会出现以下错误:
在第8行的C:\ xampp \ htdocs \ prac \ class.my.php中调用未定义的方法db :: query()。
答案 0 :(得分:1)
正如error
所说的那样,query()
类中的函数db
并不存在。在db
类上添加查询函数,如下所示:
function query($sql){
$this->connect(); // open a connection
// do your codes here
$this->disconnect(); // close the connection
}