我這有,錯誤(是的,我搜索過,但找不到任何解決方案)。PDO準備()錯誤
Fatal error: Call to a member function prepare() on a non-object in C:\inetpub\oop\_classes\class.users.php on line 19
Class.users.php:
<?php
include_once("class.db.php");
class Users {
protected $vpanel;
public function __construct() {
$this->vpanel = new Database();
$this->vpanel = $this->vpanel->dbConnection();
}
public function Login($username, $password) {
if(!empty($username) || !empty($password)) {
$sth = $this->vpanel->prepare("SELECT * FROM `users` WHERE `username` = ? AND `password` = ?");
$sth->bindParam(1, $username);
$sth->bindParam(2, $password);
$sth->execute();
if($sth->rowCount() == 1) {
echo "Correct details.";
} else {
echo "Incorrect details.";
}
} else {
echo "Fill out all the fields.";
}
}
} ?>
class.db.php:
<?php
class Database {
public function dbConnection() {
$dbhost = "localhost";
$dbname = "DBNAME";
$dbusername = "DBUSERNAME";
$dbpass = "PASSWORD";
try {
$this->vpanel = new PDO("mysql:host".$dbhost.";dbname=".$dbname."", $dbusername, $dbpass);
$this->vpanel->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage() . " (class.core.php) ";
}
}
} ?>
global.php:
<?php
session_start();
ini_set('display_errors', 1);
require_once $_SERVER['DOCUMENT_ROOT'] . "/_includes/config.php";
try {
$vpanel = new PDO("mysql:host".$Config['db']['host'].";dbname=".$Config['db']['dbname']."", $Config['db']['uname'], $Config['db']['pass']);
} catch(PDOException $e) {
echo $e->getMessage();
}
require_once $_SERVER['DOCUMENT_ROOT'] . "/_classes/class.db.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/_classes/class.users.php";
$database = new Database();
$users = new Users(); ?>
我不知道什麼錯了,我對PDO方法(和一些OOP)很陌生......所以......謝謝。
'$這個 - > vpanel = $這個 - > vpanel->的DbConnection()'將分配'NULL'到'$這個 - > vpanel'後'dbConnection()'完成,因爲它不返回任何東西。 – DCoder
如果你已經成功建立了你的MySQL數據庫的連接,那麼你正在運行的查詢返回一個錯誤,因此失敗 –
順便說一句,擺脫這種在try..catch東西。它是無用的且容易出錯這裏 –