我正在尝试访问类别及其内容的列表。我有一堂课叫做分类。我不断收到此错误。奇怪的是,到目前为止,我已经在另外两个地方使用了相同的完全相同的代码,没有任何问题。我在这里所做的只是重用代码并更改所有变量。
Fatal error: Call to a member function prepare() on null
这是我班上的代码:
<?php class Category { public function fetch_all() { global $pdo; $query = $pdo->prepare("SELECT * FROM dd_cat"); $query->execute(); return $query->fetchAll(); } public function fetch_data($cat_id) { global $pdo; $query = $pdo->prepare("SELECT * FROM dd_cat WHERE cat_id = ?"); $query->bindValue(1, $cat_id); $query->execute(); return $query->fetch(); } } ?>
这是我尝试调用的代码:
<?php session_start(); //Add session_start to top of each page// require_once('includes/config.php'); require_once('includes/header.php'); include_once('includes/category.php'); ?> <link rel="stylesheet" href="css/dd.css"> <div id="menu"> <a class="item" href="drop_index.php">Home</a> - <a class="item" href="create_topic.php">Create a topic</a> - <a class="item" href="create_cat.php">Create a category</a> <div id="userbar"> <?php if( $user->is_logged_in() ) { echo 'Hello ' . $_SESSION['user_name'] . '. Not you? <a href="logout.php">Sign out</a>'; } else { echo '<a href="login.php">Sign in</a> or <a href="index.php">create an account</a>.'; } ?> </div> </div> <?php $category = new Category; $categories = $category->fetch_all(); ?> <div id ="wrapper"> <h1>Categories</h1> <section> <ul> <?php foreach ($categories as $category) { ?> <li><a href="category.php?id=<?php echo $category['cat_id']; ?>"> <?php echo $category['cat_title']; ?></a> </li> <?php } ?> </ul> </section> </div> <?php require_once('includes/footer.php'); ?>
看来您的$pdo变量未初始化。在您上传的代码中,我看不到它的初始化位置。
$pdo
确保global scope在调用类方法之前在中创建了一个新的PDO对象。(由于应在Category类中实现方法,因此应在全局范围内声明它)。
global scope
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);