我有这个错误
Call to a member function query() on null in admin.php on line 36, functicon showMenu_type_1(), query on null...........
使用这两个php文件时:
connect.php
<?php
class Connection{
protected $db;
public function Connection(){
$conn = NULL;
try{
$conn = new PDO('mysql:host=localhost;dbname=home', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
$this->db = $conn;
}
public function getConnection(){
return $this->db;
}
}
$pd = new Connection();
?>
admin.php的
<?php
require_once('form.php');
require_once('connect.php');
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
?>
<?php
/**
*
*/
$pdo= $pd->getConnection();
class menu_multi
{
function showMenu_type_1(){
$sql_1 =$pdo->query("SELECT * FROM category WHERE menu_parent_id = 0 && type= 'MT01'");
}
}
答案 0 :(得分:1)
它是null,因为$ pd是全局的,你必须在函数中明确说明。
<?php
require_once('connect.php');
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
class menu_multi
{
function showMenu_type_1(){
// since $pd is global we have to be explicit that's what we want.
global $pd;
$pdo = $pd->getConnection();
$sql_1 = $pdo->query("SELECT * FROM category WHERE menu_parent_id = 0 && type= 'MT01'");
print_r($sql_1);
foreach ($sql_1 as $value) {
print_r($value);
}
}
}
$m = new menu_multi;
$m->showMenu_type_1();
我让这张表进行测试:
CREATE TABLE `category` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`menu_parent_id` int(11) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`type` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
这是表格中的数据:
INSERT INTO `category` (`id`, `menu_parent_id`, `name`, `type`)
VALUES
(1, 0, 'item 1', 'MT01'),
(2, 0, 'item 2', 'MT01'),
(3, 0, 'item 3', 'MT01'),
(4, 0, 'item 4', 'MT01'),
(5, 0, 'item 5', 'MT01');
以下是测试的输出:
PDOStatement Object
(
[queryString] => SELECT * FROM category WHERE menu_parent_id = 0 && type= 'MT01'
)
Array
(
[id] => 1
[0] => 1
[menu_parent_id] => 0
[1] => 0
[name] => item 1
[2] => item 1
[type] => MT01
[3] => MT01
)
Array
(
[id] => 2
[0] => 2
[menu_parent_id] => 0
[1] => 0
[name] => item 2
[2] => item 2
[type] => MT01
[3] => MT01
)
Array
(
[id] => 3
[0] => 3
[menu_parent_id] => 0
[1] => 0
[name] => item 3
[2] => item 3
[type] => MT01
[3] => MT01
)
Array
(
[id] => 4
[0] => 4
[menu_parent_id] => 0
[1] => 0
[name] => item 4
[2] => item 4
[type] => MT01
[3] => MT01
)
Array
(
[id] => 5
[0] => 5
[menu_parent_id] => 0
[1] => 0
[name] => item 5
[2] => item 5
[type] => MT01
[3] => MT01
)