0
我正在尋找更好的PDO數據庫連接,我可以在不同的課程中使用它。例如我當前的代碼是這樣的:使用數據庫連接[PDO]使用類並在其他類中進一步使用它的更好方法?
core.php中
//Connecting to Database
try {
$db = new PDO("mysql:host=localhost;dbname=mydb", "project", "project123");
}
catch(PDOException $e) {
echo $e->getMessage();
}
類核心{
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function redirectTo($page,$mode = 'response',$message = '') {
if($message != '') {
header('Location: '.SITEURL.'/'.$page.'?'.$mode.'='.urlencode($message));
} else {
header('Location: '.SITEURL.'/'.$page);
}
exit();
}
}
從這個而除了我還有2類:牆。 php和ticker.php
class Wall {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function addComment($uid, $fid, $comment) {
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
$query = $this->db->prepare('INSERT INTO wall_comments (comment, uid_fk, msg_id_fk, ip, created) VALUES (:comment, :uid, :fid, :ip, :time)');
$query->execute(array(':comment' => $comment, ':uid' => $uid, ':fid' => $fid, ':ip' => $ip, ':time' => $time));
$nofity_msg = "User commented on the post";
$setTicker = Ticker::addTicker($uid,$nofity_msg,'comment');
if($setTicker) {
Core::redirectTo('wall/view-'.$fid.'/','error','Oops, You have already posted it!');
} else {
Core::redirectTo('wall/view-'.$fid.'/','error','Oops, Error Occured');
}
}
}
和ticker.php是:
class Ticker {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
function addTicker($uid,$msg,$type) {
$time = time();
$query = $this->db->prepare('INSERT INTO tickers (uid_fk, message, type, created) VALUES (:uid, :message, :type, :time)');
try {
$query->execute(array(':uid' => $uid, ':message' => $msg, ':type' => $type, ':time' => $time));
return $this->db->lastInsertId();
}
catch(PDOException $e) {
return 0;
}
}
}
現在我的問題是,我需要調用的函數addComment(),並在該函數內部有一個進一步的呼籲函數addTicker()存在於類Ticker中。這導致了一個Db連接問題,因爲在前面的類中已經創建了一個數據庫實例,所以我不知道如何解決這個問題。
這是我使用的主索引文件的代碼:
$core = new Core($db);
$ticker = new Ticker($db);
$wall = new Wall($db);
$wall->addComment($uid, $fid, $add_comment); // This statement is not working.. :(
我的目的是有一個共同的主數據庫連接,並進一步使用其它類連接。有沒有更好的方法來做到這一點..?
對不起,我忘了在上述問題的索引文件中添加我正在使用的代碼。 (編輯它現在..) @您的常識 那麼,我目前的錯誤是,我不能得到的聲明 $ wall-> addComment($ uid,$ fid,$ add_comment); 執行,到達線或語句時遇到錯誤: $ setTicker = Ticker :: addTicker($ uid,$ nofity_msg,'comment'); – 4fsal