PDO PHP连接,致命错误 [英] PDO PHP Connection, Fatal Error

查看:62
本文介绍了PDO PHP连接,致命错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的连接类; firstcode.php

My Connection Class;firstcode.php

class DB_functions {
    public $db;
    function __construct() {
        try{
            $db = new PDO("mysql:localhost;dbname=xxx;charset=utf8","xxx","xxx");
            echo 'Connected';
        }catch(PDOException $e){
            print $e->getMessage();
            echo "No Connection";
        }
    }
    function __destruct() {}

    public function test(){

        $query = $db->query("SELECT * FROM User", PDO::FETCH_ASSOC);
        if($query->rowCount()){
            foreach ($query as $row) {
                print_r($row);
            }
        }
    }

}

我的测试PHP文件;

My test PHP File;

 <?php

require_once('firstcode.php');

$db = new db_functions();

$t = $db->test();

?>

还有我得到的错误;

注意:未定义的变量:第20行上firstcode.php中的db

Notice: Undefined variable: db in firstcode.php on line 20

致命错误:第20行上firstcode.php中非对象上调用成员函数query()

Fatal error: Call to a member function query() on a non-object in firstcode.php on line 20

预先感谢

推荐答案

您快到了.在您的课程中,您需要使用以下命令更改$db的每次迭代:

You're almost there. In your class, you need to change each iteration of $db with:

$this->db

所以您的课程看起来像这样:

So your class would look like this:

class DB_functions {
    public $db;
    function __construct() {
        try{
            $this->db = new PDO("mysql:localhost;dbname=xxx;charset=utf8","xxx","xxx");
            echo 'Connected';
        }catch(PDOException $e){
            print $e->getMessage();
            echo "No Connection";
        }
    }
    function __destruct() {}

    public function test(){

        $query = $this->db->query("SELECT * FROM User", PDO::FETCH_ASSOC);
        if($query->rowCount()){
            foreach ($query as $row) {
                print_r($row);
            }
        }
    }

}

在引用内部类变量时.它只能在类范围内访问,并通过$this引用.

这篇关于PDO PHP连接,致命错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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