gpt4 book ai didi

php - 在 OOP php 中获取查询错误

转载 作者:行者123 更新时间:2023-11-29 04:16:38 25 4
gpt4 key购买 nike

我只是 OOP php 的新手,我很难弄清楚如何使用类方法在数据库中进行查询。这是我的代码,我遇到了一个我不知道如何解决的错误。

我声明了连接变量,但我不知道为什么它是未定义的

Notice: Undefined variable: connection

Fatal error: Call to a member function query() on a non-object in

db.php

class DbConnector {

private $serverName;
private $userName;
private $password;
private $dbName;
private $connection;

public function __construct(){
$this->serverName = "localhost";
$this->userName = "root";
$this->password = "attl";
$this->dbName = "oop";

$this->connection = new mysqli($this->serverName, $this->userName, $this->password, $this->dbName);

if ($this->connection->connect_error) {
$this->connection = die("Connection failed: " . $this->connection->connect_error);
}
}

public function getConnection(){
return $this->connection;
}
}

索引.php

include('../queries/db.php');

class Users{

private $connection;

public function __construct(){
$con = new DbConnector();
$connection = $con->getConnection();
}
public function getUsers(){
$sql = $connection->query("SELECT * FROM login");

while($getUsers = $sql->fetch_array()){
echo $getUsers['username'];
}
}

}

$user = new Users();
return $user->getUsers();

最佳答案

您的问题是您试图访问局部范围的变量而不是类属性

public function getUsers(){
$sql = $connection->query("SELECT * FROM login"); // HERE

while($getUsers = $sql->fetch_array()){
echo $getUsers['username'];
}
}

这在该范围内找不到名为 $connection 的变量,您需要使用 $this 访问对象属性。

class Users {

private $connection;

public function __construct()
{
$con = new DbConnector();
// Assign this to object propety declared above
$this->connection = $con->getConnection();
}

public function getUsers()
{
// now access the object property set in constructor.
$sql = $this->connection->query("SELECT * FROM login");

while($getUsers = $sql->fetch_array()){
echo $getUsers['username'];
}
}
}

关于php - 在 OOP php 中获取查询错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716821/

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