我有两个类,一个连接类和一个包含菜单代码的类。
首先,我尝试从菜单中(从数据库中)获取所有类别,因此我尝试使用连接类中的Fatal error</b>: Call to a member function query() on null in <b>mywebsitepath/includes/menuClass.php</b> on line <b>9</b><br />
函数。但这给了我以下错误:
<?PHP
session_start();
class Connection {
// Configure Database Vars
private $host = 'localhost';
private $username = 'user';
private $password = 'pass!';
private $db_name = 'dbname';
public $db;
function __construct() {
// Create connection
$db = new mysqli($this->host, $this->username, $this->password, $this->db_name);
// Check connection
if ($db->connect_errno > 0) {
die('Unable to connect to the database: '.$db->connect_error);
}
$this->db = $db;
}
public function query($query) {
$db = $this->db;
$this->db->query('SET NAMES utf8');
if (!$result = $this->db->query($query)) {
die('There was an error running the query ['.$db->error.']');
} else {
return $result;
}
}
public function multi_query($query) {
$db = $this->db;
if (!$result = $this->db->multi_query($query)) {
die('There was an error running the multi query ['.$db->error.']');
} else {
return $result;
}
}
public function real_escape_string($value) {
return $this->db->real_escape_string($value);
}
public function inserted_id() {
return $this->db->insert_id;
}
}
$conn = new Connection;
?>
我是OOP的新手,但我想在扩展连接类时,我可以使用子类中的函数。
这是我的连接类:
<?php
require_once('includes/connection.php');
class Menu extends Connection
{
public function selectCats()
{
$cats = "SELECT * FROM snm_categories WHERE published = '1'";
$catscon = $conn->query($cats);
return $cats;
}
}
?>
这是我在菜单课上的小尝试:
$menu = new Menu();
$cats = $menu->selectCats();
在我的索引上,我想循环结果:
MariaDB
(还没有循环,但首先我想摆脱错误)
我错过了什么/做错了什么?
答案 0 :(得分:2)
问题是在派生类中,使用imagenames
(未在任何地方定义),您需要使用基类中定义的连接...
$conn
答案 1 :(得分:1)
您在连接对象属性$db
但是在selectCats
方法中,您使用的$con
不存在。您还忘记在变量前面使用$this->
,该变量需要告诉PHP查看此对象和/或其父项中的属性。
所以修改代码
<?php
require_once('includes/connection.php');
class Menu extends Connection
{
public function selectCats()
{
$cats = "SELECT * FROM snm_categories WHERE published = '1'";
$catscon = $this->db->query($cats);
// ^^^^^^^^^ changed here
return $cats;
}
}
?>