gpt4 book ai didi

PHP - 无法从另一个类访问数据库连接器类。我究竟做错了什么?

转载 作者:行者123 更新时间:2023-11-29 13:00:21 24 4
gpt4 key购买 nike

我正在努力实现 this question 中概述的相同目标但我对这个答案的应用是行不通的。当尝试执行任何涉及数据库类的操作时,我得到空白的白屏。

这应该很简单——用户在表单中输入用户名和密码。如果 Controller 收到了两者,我会查询数据库并将提交的密码的哈希值与文件中的哈希值进行比较。问题是,一旦我开始进行数据库调用,我的页面就不会加载。

我有一个 Controller 和两个类。一类是数据库连接器,另一类是依赖于数据库连接器的身份验证模块。

数据库连接器类:

class inquiry
{
protected $pdo;

// Set up the initial db connection
function __construct()
{
try
{
$this -> pdo = new PDO('mysql:host=127.0.0.1;dbname=mysqlserver','mydatabase','ffffffffffffffff');
$this -> pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this -> pdo -> setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
$this -> pdo -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this -> pdo -> exec('set names "utf8"');
}
catch (PDOException $e)
{
echo $e -> getMessage();
}
}
}

然后,认证类:

class auth
{
private $username;
private $password;
private $db;

function __construct(inquiry $db)
{
$this -> db = $db;
}

function login($username, $password)
{
$this -> username = $username;
$this -> password = $password;

// Query database, get hashed password for username
$this -> db -> query('select password from users where username="bob";');

// Data needs to be fetched but PHP does not process anything past this point anyway

return true;
}
}

然后,在 Controller 中:

require_once '../inc/class.inquiry.php';
require_once '../inc/class.auth.php';

if (isset($_POST['username']) && isset($_POST['password']))
{
// Probably doing something wrong here
$dbconnect = new inquiry();
$user = new auth($dbconnect);

$authorized = $user -> login($_POST['username'], $_POST['password']);

if ($authorized == true)
{
// Send user to index page
header('Location: index.php');
exit();
}
}

我已经评论了我认为出错的部分,但我不知道该怎么做。任何提示将不胜感激!

最佳答案

您的所有代码在很多层面上都是错误的。从类应以大写字母开头的代码标准开始,格式化代码,最后调用一个不存在的方法。

首先,您的 inquiry 类没有所需的 query() 方法。看来你试图给我们一段不是你自己写的代码来调试。

其次,你的类(class)完全没用。即使它没有自定义包装查询方法,您仍然可以使用 PDO 的方法进行查询并执行查询。但是,即使您将 PDO 类型的对象的值分配给 protected $pdo,您也绝对无法在类之外访问此 $pdo,即从 auth 类。您应该为 $pdo 编写一个访问器,这样您就可以使用类似

$this->db->getPdo()->prepare("SELECT ......");

关于PHP - 无法从另一个类访问数据库连接器类。我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23435692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com