[英]Retrieving data using PDO connection
我正在嘗試學習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()。
正如error
所言,您的db
類中不存在query()
函數。 在您的db
類上添加查詢函數,如下所示:
function query($sql){
$this->connect(); // open a connection
// do your codes here
$this->disconnect(); // close the connection
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.