dongqiangou5724 2013-05-07 17:47
浏览 43
已采纳

PHP调用被定义为此类成员的类的方法? mysql PDO [关闭]

I am trying to setup a PDO connection to replace my standard mysql connection. Until now I have a class called DB_Class that has in it's constructor the typical mysql_connect, mysql_select_db... stuff.

I use it by creating a new instance of DB_Class in the constructor of each of my objects that will hit the DB. I got the example online somewhere and it seems to work.

Now I want to switch to PDO and I am trying the same logic here but it is not working as I'd hoped. Here is what I have.

class DB_Class {
    function __construct() {
        //$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or
        //        die('Oops connection error -> ' . mysql_error());
        //mysql_select_db(DB_DATABASE, $connection) or die('Database error -> ' . mysql_error());

        $dbConnString = "mysql:host=" . DB_SERVER . ";port=".DB_PORT." dbname=" . DB_DATABASE;
        $dbConnection = new PDO($dbConnString, DB_USERNAME, DB_PASSWORD);
        //$dbConnection = new PDO('mysql:dbname='.DB_DATABASE.';host='.DB_SERVER.';charset=utf8', DB_USERNAME, DB_PASSWORD);
        $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
}

Here is the Constructor of my client class

//Initialize the DB Class 
    public function __construct() {
        $db = new DB_Class();
    }

Here is where I am not quite sure how to use it?

public function FindByOwnerID($id) {
        $clients = array();       

        $stmt = $db->prepare("SELECT * FROM Client WHERE OwnerID = :id");
        $stmt->execute(array(':id' => $id));          
  • 写回答

1条回答 默认 最新

  • 普通网友 2013-05-07 17:55
    关注

    The constructor should be

    $this->db = new DB_Class();
    ^^^^^^^^^
    

    $db by itself is merely a local variable within that method. You need to assign it as an object attribute, which is $this->whatever.

    Same goes wherever you use $db in the other methods, it should always be $this->db.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!