【发布时间】:2017-01-18 10:24:47
【问题描述】:
我只是使用 OOP php 的新手,我很难弄清楚如何使用类方法在数据库中查询。这是我的代码,我遇到了一个我不知道如何解决的错误。
我声明了连接变量,但我不知道为什么它是未定义的
注意:未定义变量:连接
致命错误:在非对象中调用成员函数 query()
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;
}
}
index.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();
【问题讨论】:
-
在@hanky panky 上面标记的链接上非常不同
-
原来的问题是
I'm getting error Notice: Undefined variable: connection in C:\xampp\htdocs\oop\views\index.php on line 13所以恕我直言,重复的标志可以帮助您快速解决问题 -
你得到什么错误?
-
是的,谢谢,但它非常不同,因为寻找链接它不是类 OOP 方法。 @HankyPanky
-
注意:未定义变量:第 13 行 C:\xampp\htdocs\oop\views\index.php 中的连接 致命错误:在 C 中的非对象上调用成员函数 query() :\xampp\htdocs\oop\views\index.php 第 13 行。我不知道,但已声明连接。 @MUNISHKUMAR