未捕获的错误:调用成员函数prepare()(PDO,php)

我试图使用 PHP 中的公共函数从表中获取数据,但出现以下错误:


未捕获的错误:调用成员函数prepare()(PDO,php)


我搜索了 2、3 个小时...但没有类似的结果或者我不明白。


<?php


class Config {


    public static $SQL;


    private function __construct() {

        $host_name = "localhost";

        $base_user = "root";

        $base_pass = "";

        $base_name = "home_page";


        try {

            self::$SQL = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);

            self::$SQL->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            echo "Connected successfully";

        } catch(PDOException $e) {

            die("Something went wrong, database connection closed. Reason: ". $e->getMessage());

        }

    }


    public static function GetData($table, $data, $id) {

        $wc = Config::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');

        $wc->execute(array($id));

        $r_data = $wc->fetch();

        return $r_data[$data];

    }


}


?>

我在我的基本文件中使用它:


<h1><?php echo Config::GetData("page_details", "Moto", 1) ?></h1>

错误来自这一行:


$wc = self::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');


红糖糍粑
浏览 88回答 1
1回答

呼啦一阵风

您想在任何地方使用有什么特殊原因吗STATIC?常见的方法是使用公共的动态方法和属性。我用 PHP OOP 中建议的命名约定重写了您的示例,它有效:<?phpclass Config{&nbsp; &nbsp; /** @var PDO $conn */&nbsp; &nbsp; private $conn = null;&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $host_name = "localhost";&nbsp; &nbsp; &nbsp; &nbsp; $base_user = "root";&nbsp; &nbsp; &nbsp; &nbsp; $base_pass = "";&nbsp; &nbsp; &nbsp; &nbsp; $base_name = "home_page";&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->conn = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "Connected successfully"; // <- this is unnnesesary&nbsp; &nbsp; &nbsp; &nbsp; } catch (PDOException $e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; die("Something went wrong, database connection closed. Reason: " . $e->getMessage());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public function findById($table, $data, $id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $stmt = $this->conn->prepare('SELECT `' . $data . '` FROM `' . $table . '` WHERE `uid` = ?');&nbsp; &nbsp; &nbsp; &nbsp; $stmt->execute(array($id));&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; $stmt->fetch(PDO::FETCH_ASSOC);&nbsp; &nbsp; }}// just for test$cfg = new Config();print_r($cfg->findById('foo', '*', 1));或者在你的情况下<?php echo $cfg->findById("page_details", "Moto", 1)['Moto'] ?>
打开App,查看更多内容
随时随地看视频慕课网APP