如何为 PDO 数据库连接构建和调用简单的 PHP class
How to build and call a simple PHP class for a PDO DB connection
这是我目前的情况:
class DB {
var $DBUser = 'xxx';
var $DBPass = 'xxx';
var $DBServer = 'xxx';
var $DBName = 'xxx';
public function connect() {
try {
$strDSN = "mysql:host=$this->DBServer;dbname=$this->DBName;";
$username = $this->$DBUser;
$pass = $this->$DBPass;
$conn = new PDO($strDSN, $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'connected';
}
catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
} //end method
} //end class
然后调用它:
$db = new DB;
$conn = $db->connect;
$stmt = $conn->prepare('SELECT * FROM XXX WHERE id = :id');
$id = $_GET['id'];
$stmt->execute(array('id'=>$id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
但是,我收到此错误消息:
Fatal error: Call to a member function prepare()
on a non-object
知道我做错了什么吗?
调用方法时,包括括号:
$conn = $db->connect();
// ^^ missing
第二个问题是您的连接方法没有 return 连接句柄。在 try
块中添加:
return $conn;
最后,在引用实例和 class 属性时,不要包含 $
。
$username = $this->DBUser;
// ^ $ should not be present
这是我目前的情况:
class DB {
var $DBUser = 'xxx';
var $DBPass = 'xxx';
var $DBServer = 'xxx';
var $DBName = 'xxx';
public function connect() {
try {
$strDSN = "mysql:host=$this->DBServer;dbname=$this->DBName;";
$username = $this->$DBUser;
$pass = $this->$DBPass;
$conn = new PDO($strDSN, $username, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'connected';
}
catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
} //end method
} //end class
然后调用它:
$db = new DB;
$conn = $db->connect;
$stmt = $conn->prepare('SELECT * FROM XXX WHERE id = :id');
$id = $_GET['id'];
$stmt->execute(array('id'=>$id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
但是,我收到此错误消息:
Fatal error: Call to a member function
prepare()
on a non-object
知道我做错了什么吗?
调用方法时,包括括号:
$conn = $db->connect();
// ^^ missing
第二个问题是您的连接方法没有 return 连接句柄。在 try
块中添加:
return $conn;
最后,在引用实例和 class 属性时,不要包含 $
。
$username = $this->DBUser;
// ^ $ should not be present