你好,我有一个我正在处理的示例项目,到目前为止我已经创建了 5 个 php 文件。
connection_info.php -> db credentials
connection.php -> database connection
database.php -> where all wueries will be (here I pass the connection instance)
logger.php -> a simple logger
index.php -> oh well index...
索引.php
<?php
require_once 'logger.php';
require_once 'connection.php';
require_once 'database.php';
$logger = new Logger();
$connection = new Connection($connection_info['host'], $connection_info['db'], $connection_info['user'], $connection_info['pass'], $logger);
$db = new Database($connection, $logger);
?>
<!DOCTYPE html>
<html>
<head>
<title>Administration</title>
</head>
<body>
<?php
$db->authenticateUser("alex", "123456");
?>
</body>
</html>
连接.php
<?php
require_once 'connection_info.php';
Class Connection {
private $user;
private $pass;
private $host;
private $db;
private $con;
private $logger;
function __construct($host = '127.0.0.1', $db, $user, $pass = null, &$logger) {
$this->user = $user;
$this->pass = $pass;
$this->host = $host;
$this->db = $db;
$this->logger = $logger;
try {
$connectionString = "mysql:host=$this->host;dbname=$this->db;charset=utf8";
$this->con = new PDO($connectionString, $this->user, $this->pass);
$this->logger->log('Database connection established');
return $this->con;
} catch (PDOException $e) {
$this->logger->log('Database connection failed: ' . $e->getMessage());
}
}
function __destruct() {
$this->con = null;
}
}
?>
数据库.php
<?php
Class Database {
private $connection;
private $logger;
function __construct(&$connection, &$logger) {
$this->connection = $connection;
$this->logger = $logger;
}
function __destruct() {
}
public function authenticateUser($user, $pass) {
if (func_num_args() != 2) {
$this->logger('Invalid arguemnts supplied while authenticating');
return false;
} else {
try {
$query = "SELECT * FROM `users` WHERE user=:user AND pass=:pass";
$stmt = $this->connection->prepare($query); // Error occurs here
$stmt->bindValue(':user', $user, PDO::PARAM_STR);
$stmt->bindValue(':pass', md5($pass), PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($results) == 1) {
$_SESSION['user'] = true;
return true;
} else {
$this->logger('Invalid credentials provided: "' . $user . '", "' . $pass . '"' );
return false;
}
} catch (PDOException $e) {
$this->logger('Error retrieving user: "' . $user . '", ' . $e->getMessage() );
return false;
}
}
}
}
?>
我得到的错误是这样的:"致命错误:在第 34 行的 D:''Development''xampp''htdocs''lab''feticcio''database.php 中调用未定义的方法 Connection::p repare() "
我试图自己弄清楚这一点,但我的思想被卡住了,可能是这很愚蠢,但我可以用第二双眼睛......
您的"连接"类没有称为"prepare"的方法。您将Connection
的实例传递到Database
中,然后调用一个名为prepare()
的方法,该方法在该类中不存在。你的意思是调用 PD 连接对象的 prepare()
方法(在你自己的 Connection 类中$con
)?您应该通过包装器属性(或直接公开$con->prepare()
方法的方法)公开它。