从PHP的类内的数据库获取数据

时间:2018-12-27 12:16:27

标签: php mysql class oop pdo

如何在类内部从数据库中获取数据?

我的数据库中有一个users表,我想以面向对象的方式访问此数据。这意味着我不想一直在我的代码中编写查询,相反,我想通过说$Users->getUserById(2)->getName();

来获取此数据。

但是问题是我无法在这些类中建立数据库连接。

$pdo = new PDO("mysql:host=ipofdatabase;dbname=nameofdatabase", "username", "password", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

class Users {
    public function usersList() {
        $db_users = $pdo->query("SELECT id, username, mail FROM users");
        $users = array();

        foreach ($db_users as $u) {
            $users[] = array(
                'id' => $u['id'],
                'username' => $u['username'],
                'mail' => $u['mail']
            );
        }
    }

    public function getUserById($id) {
        return new User($id);
    }
}

我希望$Users->usersList()输出包含所有数据的数组,但我收到一条错误消息,即第3行中的变量$ pdo未定义。

  

注意:未定义的变量:第6行的C:\ apache \ docs \ Users.php中的pdo

是否应该在每个类中建立数据库连接?这会不会影响表演?

2 个答案:

答案 0 :(得分:3)

您需要创建一个__construct函数才能进入PDO。您在类的外部中声明了$pdo变量。该课程可以访问内部内容。

class Foo
{
    protected $pdo; # here we define PDO as part of the class scope.

    public function __construct()
    {
        # we then assign $pdo to be a PDO instance
        $this->pdo = new \PDO('mysql:hostname=localhost;dbname=foobar', 'user', 'pass');
    }

    public function doSomething()
    {
        # we then use the $pdo var using $this->pdo
        $this->pdo->prepare('SELECT * FROM `table`');
        # etc.
    }
}

答案 1 :(得分:0)

我会做这样的事情。创建一个模型来存储“用户”数据。然后,UserHandler可以加载并跟踪这些模型。

此外,可以将对DH的引用传递到UserHandler构造,以保留脚本另一部分的连接。

<?php 

class User{
    public $id;
    public $username;
    public $mail;

    public function __construct( $sArg_Id = "", $sArg_UserName = "", $sArg_Mail = "" ) {        
        $this->id = (int)$sArg_Id;
        $this->username = $sArg_UserName;
        $this->mail = $sArg_Mail;
    }
}


class UserHandler {

    // hold references to our user objects
    public $aUsers = array();

    // hold a ref to DataHandler     
    public $oDH = null;
    private $bDHInit = false;


    public function __construct( &$oArg_DH = null ) {

        // if reference passed, and if not already init
        if($oArg_DH && !$this->bDHInit){
            $this->oDH = $oArg_DH;
            $this->bDHInit = true;
        }
    }

    public function usersList() {

        $this->InitDH();

        $db_users = $this->oDH->query("SELECT id, username, mail FROM users");

        // add a new user object to aUsers array
        foreach ($db_users as $u) {
            $this->aUsers[$u['id']] = new User($u['id'], $u['username'], $u['mail']);
        }
    }

    public function getUserById($id) {

        if(isset($this->aUsers[$id])){
            return $this->aUsers[$id];
        }else{

            // load user id, or return new user object with id
            // return new User($id);
        }

        return false;
    }

    public function InitDH(){
        // I would also create a DataHandler class to wrap some of the PDO methods
        if(!$this->bDHInit){

            $this->oDH = new PDO(
                "mysql:host=ipofdatabase;dbname=nameofdatabase", 
                "username", 
                "password", 
                array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

            $this->bDHInit = true;
        }
    }
}