. Advertisement .
..3..
. Advertisement .
..4..
I am tired of fixing the problem: call to a member function prepare() on null in the php; even if I get the reference from another forum, it still returns an error:
Fatal error: Call to a member function prepare() on null
To identify the problem, I will show you the detail here:
<?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');
?>
How do I do that? Could you support me in improving this problem?
The cause:
The error ”call to a member function prepare() on null” happens because you forget initializing
$pdo
variable, so the PDO object which you are referencing is invalid.Solution:
To fix this error, in the
global scope
you remember to initialize a new PDO object before the class of methods are called (because of the way you apply the methods in the Category group, you should declare it in the global scope).You can try/catch
PDOException
sYou can find everything you need by using the
print_r( $e );
line. I recently had an error message that looked likeunknown database 'my_db'
.