致命错误:调用成员函数prepare()时为null,已经是必需的pdo

时间:2019-01-18 15:53:27

标签: php pdo

致命错误:在第40行的C:\ AppServ \ www \ queryGet.php中,对成员函数prepare()的调用为null 当我运行“ http://localhost/queryGet.php?get=buildings”时,我不断收到致命错误,并且找不到错误所在。 问题是我还有一些其他页面以相同的开始(会话+ require config.php),并且使用了数据库,但这仅显示prepare()错误。

这是“ queryGet.php”:

<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once( '/conf/config.php' );
if ($_GET['get'] == 'buildings') { getBuildings(); };
function getBuildings()
{
    $sql = "SELECT name, ID FROM willyschool.building;"; // get building name, id from building DB
    try {
        $stmt = $pdo->prepare($sql); // this is line 40
        if ($stmt->execute()) {
            $result = $stmt->fetchAll();
            foreach ($result as $row) {
                echo "<option to='" . $row['ID'] . "'>" . $row['name'] . "</option>";
            }
        } 
    } catch (PDOException $e) {
        echo "Error:" . $e->getMessage();
    }
}
?>

这是“ config.php”:

<?php
class MyPDO extends PDO
{
    public function __construct($file = 'db.ini')
    {
        if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');

        $dns = $settings['database']['driver'] .
        ':host=' . $settings['database']['host'] .
        ((!empty($settings['database']['port'])) ? (';port=' . $settings['database']['port']) : '') .
        ';dbname=' . $settings['database']['schema'];

        parent::__construct($dns, $settings['database']['username'], $settings['database']['password']);
    }
}
try{
    $pdo = new MyPDO();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
    die("ERROR: Could not connect. ". $e->getMessage());
}
?>

0 个答案:

没有答案