在null上调用成员函数prepare()-PDO [英] Call to a member function prepare() on null - PDO

查看:91
本文介绍了在null上调用成员函数prepare()-PDO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了与此相关的每个答案,但似乎没有一个答案能完全回答正在发生的事情. 目前,在尝试使用pdo编写语句时,标题出现错误.

I have searched every single answer regarding this and none seem to fully answer what's going on. Currently I am getting the error in the title when trying to prepare a statement with pdo.

我尝试过:

改为使用构造函数

使用非静态

在有构造函数时使用$ this

Using $this when I had a constructor

正在捕获PDO异常,似乎没有异常

Catching PDO exceptions, none seem to be thrown

这是main.php

Here is main.php

class db {
    public static $db;
    public static $db2;

    public static function start() {
        $host = "localhost";
        $dbname = "dbname";
        $usr = "user";
        $ps = "pass";

        $pdo = "mysql:host=$host;dbname=$dbname";
        $opt = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_PERSISTENT => true
        ];
        try {
        db::$db = new PDO($pdo, $usr, $ps, $opt);

        return db::$db;
        } catch(PDOException $e) {
            $e->getMessage();
        }
    }
}

然后初始化数据库,我使用db::start();

And then to initialize the database, I call the start function in index.php with db::start();

现在,要出错了.

在main.php中,在一个完全不同的类和函数中,我尝试静态地调用此连接.

Within main.php, in a whole different class and function, I try to call this connection statically.

$stmt0 = db::$db->prepare("SELECT * FROM users WHERE uname=:u");

但是完成后,我在此行上收到标题错误.

But when done, I receive the error in the title, on this line.

大多数人可能会认为,嗯,连接一定有错误,然后调用null.如果是这种情况,那是因为我在错误日志或页面中什么都没看到,所以可以防止引发我的异常.

Most would probably think, hmm, there must be an error with the connection then if it is calling it null. If that's the case, something is preventing my exception from being thrown because I see nothing in the error logs or on the page.

推荐答案

您的PDO无法连接,并且由于您没有在这种情况下做任何事情(您catch却默默地将其删除),所以在雷达下.

Your PDO is failing to connect, and since you aren't doing anything with that condition (you catch it but then silently drop it), it's going under the radar.

尝试删除try..catch块.如果连接中发生错误,您需要知道!

Try removing the try..catch block. If an error is happening in connection, you need to know!

这篇关于在null上调用成员函数prepare()-PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆