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.
你只有'connect'和'disconnect'方法,没有这种所谓的方法'query' –