为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
红糖糍粑 2023-09-15 09:31:45
我试图使用 PHP 中的公共函数从表中获取数据,但出现以下错误:未捕获的错误:调用成员函数prepare()(PDO,php)我搜索了 2、3 个小时...但没有类似的结果或者我不明白。<?phpclass 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` = ?');
查看完整描述

1 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

您想在任何地方使用有什么特殊原因吗STATIC?常见的方法是使用公共的动态方法和属性。我用 PHP OOP 中建议的命名约定重写了您的示例,它有效:


<?php


class Config

{


    /** @var PDO $conn */

    private $conn = null;


    public function __construct()

    {

        $host_name = "localhost";

        $base_user = "root";

        $base_pass = "";

        $base_name = "home_page";


        try {

            $this->conn = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);

            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            echo "Connected successfully"; // <- this is unnnesesary

        } catch (PDOException $e) {

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

        }

    }


    public function findById($table, $data, $id)

    {

        $stmt = $this->conn->prepare('SELECT `' . $data . '` FROM `' . $table . '` WHERE `uid` = ?');

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


        return  $stmt->fetch(PDO::FETCH_ASSOC);

    }


}


// just for test

$cfg = new Config();

print_r($cfg->findById('foo', '*', 1));

或者在你的情况下


<?php echo $cfg->findById("page_details", "Moto", 1)['Moto'] ?>


查看完整回答
反对 回复 2023-09-15
  • 1 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信