每次我試圖執行查詢它表明:調用未定義的方法連接::準備()
fatal error: Call to undefined method connect::prepare()
class connect {
private static $instance = null;
private $pdo;
private function __construct() {
try{
$this->pdo = new PDO('mysql:localhost=127.0.0.1;dbname=comment', 'root', '');
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if(!isset(self::$instance)) {
self::$instance = new connect();
}
return self::$instance;
}
}
//這個在另一頁require_once 'connect.php';
class users {
public $pdo;
public function __construct() {
$this->pdo = connect::getInstance();
}
public function insertComment($user_id, $comment_text, $time) {
$sql = "INSERT INTO comments VALUES ('','$user_id', '$comment_text', '$time')";
$this->query = $this->pdo->prepare($sql);
$this->query->execute();
}
}
$user = new users;
$user_id = 10;
$comment_text = 'hello everyone';
$time = date("y/m/d - h:i:s");
$user->insertComment($user_id, $comment_text, $time);
在connect中,您在$ pdo屬性中擁有PDO。在用戶中,你有一個$ pdo屬性連接。要從用戶訪問PDO,您需要使用'$ this-> pdo-> pdo'。這是命名會讓你感到困惑的地方。 – Devon
它不工作,你能解釋更多,以得到整個想法 –
我的技巧是擺脫你的班'連接'。 PDO已經是一個配備齊全的db-class。無需將其包裝在自定義的一個! – Jeff