我有这个,错误(是的,我已经搜索过它,但找不到任何解决方案)。
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)......所以......谢谢。
答案 0 :(得分:0)
您的dbConnection没有返回任何内容。您需要让它返回$ this-&gt; vpanel,以便Users-&gt; __构造可以将其分配给类变量。
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);
return $this->vpanel;
} catch(PDOException $e) {
echo $e->getMessage() . " (class.core.php) ";
return false;
}
}
您的登录功能:
public function Login($username, $password) {
if($this->vpanel === false){
echo "There is no database connection.";
return false;
}
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.";
}
}