我有點新的數據庫連接使用MySQL的PDO,這裏有我的兩個文件:PHP PDO MySQL的:如何使用在不同類
我有我用來連接到數據庫的連接類:
class connection{
private $host = 'localhost';
private $dbname = 'devac';
private $username = 'root';
private $password ='';
public $con = '';
function __construct(){
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We\'re sorry but there was an error while trying to connect to the database';
file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND);
}
}
}
我有我使用從數據庫中查詢數據的ACCOUNT_INFO類:
class account_info{
function getAccountInfo(){
$acc_info = $this->con->prepare("SELECT * FROM account_info");
$acc_info->execute();
$results = $acc_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key) {
$results->owner_firstname;
}
}
}
我包括在我的index.php頁面這些文件:
include_once 'classes/connection.class.php';
include_once 'classes/accountinfo.class.php';
$con = new connection();
$info = new account_info();
$info->getAccountInfo();
我只是不能得到它的工作我沒有得到任何輸出,我認爲它與範圍有關,但我不知道正確的原因爲什麼要解決它,因爲我是新手這PDO和麪向對象的東西。 在此先感謝。
然後他將爲他的賬戶類的每個實例創建一個新的數據庫連接(以及其他每個類這需要數據庫連接)。 – Martin 2012-07-16 23:49:59
@Martin,我已經更新了我的答案 – Shoe 2012-07-16 23:58:15
好了,所以下面的最新版本,他現在需要跟蹤$ con在整個應用程序範圍內(並且非常小心,不要覆蓋它),並將其傳遞給每個其他對象/明確地關閉。現在我明白爲什麼單身人士是一個壞主意! :) – Martin 2012-07-16 23:58:43