php 致命错误:在 null 上调用成员函数 prepare()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28592400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:57:36  来源:igfitidea点击:

Fatal error: Call to a member function prepare() on null

php

提问by ddonche

I am trying to access a list of categories and their contents. I have a class called Categories. I keep getting this error. The weird thing is that I've used this same exact code in two other places so far with no problems. All I did here was reuse the code and change all the variables.

我正在尝试访问类别列表及其内容。我有一个叫做类别的类。我不断收到此错误。奇怪的是,到目前为止,我已经在另外两个地方使用了完全相同的代码,没有出现任何问题。我在这里所做的只是重用代码并更改所有变量。

Fatal error: Call to a member function prepare() on null

Here is the code to my class:

这是我班级的代码:

    <?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();
    }
}

?>

And here is the code I am trying to call:

这是我试图调用的代码:

<?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');
?>

回答by D_R

It looks like your $pdovariable is not initialized. I can't see in the code you've uploaded where you are initializing it.

看起来您的$pdo变量未初始化。我在您上传的代码中看不到初始化它的位置。

Make sure you create a new PDO object in the global scopebefore calling the class methods. (You should declare it in the global scope because of how you implemented the methods inside the Category class).

确保global scope在调用类方法之前创建了一个新的 PDO 对象。(您应该在全局范围内声明它,因为您是如何在 Category 类中实现方法的)。

$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

回答by aesede

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

您可以 try/catch PDOExceptions(您的配置可能会有所不同,但重要的部分是 try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e );line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

print_r( $e );行将显示您需要的所有内容,例如我最近遇到一个错误消息类似于unknown database 'my_db'.

回答by burf

@delato468 comment must be listed as a solution as it worked for me.

@delato468 评论必须列为解决方案,因为它对我有用。

In addition to defining the parameter, the user must pass it too at the time of calling the function

除了定义参数外,用户在调用函数时也必须传递参数

fetch_data(PDO $pdo, $cat_id)