PDO 在类中的使用

发布于 2024-08-17 12:24:09 字数 392 浏览 6 评论 0原文

我有一些类执行一些 MySQL 查询和准备好的语句。然而,我不知道如何将我的 PDO 对象合并到这些类中。例如,我想做这样的事情:

<?php

$dbh = new PDO(...);

class Foo extends PDO {
    public $dbh;

    public function bar() {
        $this->dbh->prepare('SELECT * FROM table');
        $this->dbh->execute();

    }
}


?>

不幸的是,它不起作用。谁能建议一种优雅的方法来做到这一点?感谢您抽出时间。抱歉,我是新手,如果您有任何不清楚的地方,请留下评论,我会尽力回复!

I have a few classes that perform some MySQL queries and prepared statements. However, I am lost in how to incorporate my PDO object within those classes. For example, I want to do something like this:

<?php

$dbh = new PDO(...);

class Foo extends PDO {
    public $dbh;

    public function bar() {
        $this->dbh->prepare('SELECT * FROM table');
        $this->dbh->execute();

    }
}


?>

Unfortunately, it doesn't work. Can anyone suggest an elegant way to do this? Thanks for your time. Sorry I'm new to this, please leave any comments if you are unclear about anything and I'll do my best to respond!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

旧瑾黎汐 2024-08-24 12:24:09

您可以在实现单例模式的类中实例化与数据库的连接。
连接将完成一次,并且所有其他对象/脚本都可以轻松访问此类。

我在下面的示例中使用一个名为“Core”的类;

class Core
{
    public $dbh; // handle of the db connexion
    private static $instance;

    private function __construct()
    {
        // building data source name from config
        $dsn = 'pgsql:host=' . Config::read('db.host') .
               ';dbname='    . Config::read('db.basename') .
               ';port='      . Config::read('db.port') .
               ';connect_timeout=15';
        // getting DB user from config                
        $user = Config::read('db.user');
        // getting DB password from config                
        $password = Config::read('db.password');

        $this->dbh = new PDO($dsn, $user, $password);
    }

    public static function getInstance()
    {
        if (!isset(self::$instance))
        {
            $object = __CLASS__;
            self::$instance = new $object;
        }
        return self::$instance;
    }

    // others global functions
}

这个类从一个名为“Config”的静态类获取参数,您可以在其中存储您的配置:

<?php
class Config
{
    static $confArray;

    public static function read($name)
    {
        return self::$confArray[$name];
    }

    public static function write($name, $value)
    {
        self::$confArray[$name] = $value;
    }

}

// db
Config::write('db.host', '127.0.0.1');
Config::write('db.port', '5432');
Config::write('db.basename', 'mydb');
Config::write('db.user', 'myuser');
Config::write('db.password', 'mypassword');

在所有脚本/对象中,您只需获取 Core 的实例,然后查询数据库

$sql = "select login, email from users where id = :id";

try {
    $core = Core::getInstance();
    $stmt = $core->dbh->prepare($sql);
    $stmt->bindParam(':id', $this->id, PDO::PARAM_INT);

    if ($stmt->execute()) {
        $o = $stmt->fetch(PDO::FETCH_OBJ);
        // blablabla....

如果您需要有关单例的更多信息,请查看 PHP文档 http://php.net/manual/en/language.oop5.patterns。 php

You can instantiate your connection to the database in a class that implement the singleton pattern.
The connection will be done once and this class will be easily accessible by all of your other objects / scripts.

i use a class called "Core" in the following example;

class Core
{
    public $dbh; // handle of the db connexion
    private static $instance;

    private function __construct()
    {
        // building data source name from config
        $dsn = 'pgsql:host=' . Config::read('db.host') .
               ';dbname='    . Config::read('db.basename') .
               ';port='      . Config::read('db.port') .
               ';connect_timeout=15';
        // getting DB user from config                
        $user = Config::read('db.user');
        // getting DB password from config                
        $password = Config::read('db.password');

        $this->dbh = new PDO($dsn, $user, $password);
    }

    public static function getInstance()
    {
        if (!isset(self::$instance))
        {
            $object = __CLASS__;
            self::$instance = new $object;
        }
        return self::$instance;
    }

    // others global functions
}

this class take parameters from a static class called "Config" where you can store your configuration:

<?php
class Config
{
    static $confArray;

    public static function read($name)
    {
        return self::$confArray[$name];
    }

    public static function write($name, $value)
    {
        self::$confArray[$name] = $value;
    }

}

// db
Config::write('db.host', '127.0.0.1');
Config::write('db.port', '5432');
Config::write('db.basename', 'mydb');
Config::write('db.user', 'myuser');
Config::write('db.password', 'mypassword');

in all your scripts / objects you just have to get the instance of Core and then query the DB

$sql = "select login, email from users where id = :id";

try {
    $core = Core::getInstance();
    $stmt = $core->dbh->prepare($sql);
    $stmt->bindParam(':id', $this->id, PDO::PARAM_INT);

    if ($stmt->execute()) {
        $o = $stmt->fetch(PDO::FETCH_OBJ);
        // blablabla....

If you need more information about singleton look at the PHP doc http://php.net/manual/en/language.oop5.patterns.php

我不会写诗 2024-08-24 12:24:09

这是一个大部分完整的工作剪辑和内容。粘贴 Guillaume Boschini 上面的答案的示例。

填充的数据库表(MySQL):

CREATE TABLE `useraddress` (                                                                                                                                        
  `addressid` int(10) unsigned NOT NULL AUTO_INCREMENT,                                                                                                                             
  `userid` int(10) unsigned NOT NULL,                                                                                                                                               
  `addresstitle` char(100) NOT NULL,                                                                                                                        
  `streetaddressa` char(100) NOT NULL,
  `streetaddressb` char(100) DEFAULT NULL,
  `unit` char(50) DEFAULT NULL,
  `city` char(50) NOT NULL,
  `state` char(2) NOT NULL,
  `zip` int(5) NOT NULL,
  `zipplusfour` int(4) DEFAULT NULL,
  PRIMARY KEY (`addressid`),
  KEY `userid` (`userid`),
  CONSTRAINT `useraddress_fk_1` FOREIGN KEY (`userid`) REFERENCES `user` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

在/DBLibrary/pdocore.php中:

<?php

    Config::write('db.host', 'localhost');
    Config::write('db.port', '3306');
    Config::write('db.basename', 'DBName');
    Config::write('db.user', 'DBUser');
    Config::write('db.password', 'DBPassword');

    class Config {

        static $confArray;

        public static function read($name) {
            return self::$confArray[$name];
        }

        public static function write($name, $value) {
            self::$confArray[$name] = $value;
        }

    }

    class Core {
        public $dbh; // handle of the db connection
        private static $instance;

        private function __construct()  {

            // building data source name from config
            $dsn = 'mysql:host=' . Config::read('db.host') . ';dbname=' . Config::read('db.basename') . ';port=' . Config::read('db.port') .';connect_timeout=15';

            // getting DB user from config
            $user = Config::read('db.user');

            // getting DB password from config
            $password = Config::read('db.password');

            $this->dbh = new PDO($dsn, $user, $password);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        }

        public static function getInstance() {
            if (!isset(self::$instance)) {
                $object = __CLASS__;
                self::$instance = new $object;
            }
            return self::$instance;
        }

        // others global functions
    }
?>

在/objectsLibrary/SYS_UserAddress.php中:

<?php

    define('k_uaddress_addressid','addressid');
    define('k_uaddress_userid','userid');
    define('k_uaddress_addresstitle','addresstitle');
    define('k_uaddress_addressa','streetaddressa');
    define('k_uaddress_addressb','streetaddressb');
    define('k_uaddress_unit','unit');
    define('k_uaddress_city','city');
    define('k_uaddress_state','state');
    define('k_uaddress_zip','zip');
    define('k_uaddress_zipplusfour','zipplusfour');

    require_once '../DBLibrary/pdocore.php';

    class SYS_UserAddress {

        public $addressid;
        public $userid;
        public $addresstitle;
        public $addressa;
        public $addressb;
        public $unit;
        public $city;
        public $state;
        public $zip;
        public $zipplusfour;

        public function SYS_UserAddressByAddressId($_addressid) {

            $returnValue=FALSE;

            $query='select * from useraddress where ' . k_uaddress_addressid . '=:addressid';

            try {
                $pdoCore = Core::getInstance();
                $pdoObject = $pdoCore->dbh->prepare($query);

                $queryArray = array(':addressid'=>$_addressid);

                if ($pdoObject->execute($queryArray)) {

                    $pdoObject->setFetchMode(PDO::FETCH_ASSOC);;

                    while ($addressrow = $pdoObject->fetch()) {

                        $this->addressid=$addressrow[k_uaddress_addressid];
                        $this->userid=$addressrow[k_uaddress_userid];
                        $this->addresstitle=$addressrow[k_uaddress_addresstitle];
                        $this->addressa=$addressrow[k_uaddress_addressa];
                        $this->addressb=$addressrow[k_uaddress_addressb];
                        $this->unit=$addressrow[k_uaddress_unit];
                        $this->city=$addressrow[k_uaddress_city];
                        $this->zip=$addressrow[k_uaddress_zip];
                        $this->zipplusfour=$addressrow[k_uaddress_zipplusfour];

                    }
                    $returnValue=TRUE;
                }
            }
            catch(PDOException $pe) {
                trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
            }

            return $returnValue;

        }
    }

    $test=1;
    $testAddressId=2;

    if($test>0) {

        $testAddress = new SYS_UserAddress();

        $testAddress->SYS_UserAddressByAddressId($testAddressId);

        echo '<pre>';
        echo print_r($testAddress);
        echo '</pre>';

    }

?>

上面的帖子确实对我有帮助。我现在发表的这篇文章会让我更快地到达我想要的地方。仅此而已。如果有任何问题,我会及时修复。

Here is a mostly complete working cut & paste example of Guillaume Boschini's answer above.

A populated DB table (MySQL):

CREATE TABLE `useraddress` (                                                                                                                                        
  `addressid` int(10) unsigned NOT NULL AUTO_INCREMENT,                                                                                                                             
  `userid` int(10) unsigned NOT NULL,                                                                                                                                               
  `addresstitle` char(100) NOT NULL,                                                                                                                        
  `streetaddressa` char(100) NOT NULL,
  `streetaddressb` char(100) DEFAULT NULL,
  `unit` char(50) DEFAULT NULL,
  `city` char(50) NOT NULL,
  `state` char(2) NOT NULL,
  `zip` int(5) NOT NULL,
  `zipplusfour` int(4) DEFAULT NULL,
  PRIMARY KEY (`addressid`),
  KEY `userid` (`userid`),
  CONSTRAINT `useraddress_fk_1` FOREIGN KEY (`userid`) REFERENCES `user` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

In /DBLibrary/pdocore.php:

<?php

    Config::write('db.host', 'localhost');
    Config::write('db.port', '3306');
    Config::write('db.basename', 'DBName');
    Config::write('db.user', 'DBUser');
    Config::write('db.password', 'DBPassword');

    class Config {

        static $confArray;

        public static function read($name) {
            return self::$confArray[$name];
        }

        public static function write($name, $value) {
            self::$confArray[$name] = $value;
        }

    }

    class Core {
        public $dbh; // handle of the db connection
        private static $instance;

        private function __construct()  {

            // building data source name from config
            $dsn = 'mysql:host=' . Config::read('db.host') . ';dbname=' . Config::read('db.basename') . ';port=' . Config::read('db.port') .';connect_timeout=15';

            // getting DB user from config
            $user = Config::read('db.user');

            // getting DB password from config
            $password = Config::read('db.password');

            $this->dbh = new PDO($dsn, $user, $password);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        }

        public static function getInstance() {
            if (!isset(self::$instance)) {
                $object = __CLASS__;
                self::$instance = new $object;
            }
            return self::$instance;
        }

        // others global functions
    }
?>

In /objectsLibrary/SYS_UserAddress.php:

<?php

    define('k_uaddress_addressid','addressid');
    define('k_uaddress_userid','userid');
    define('k_uaddress_addresstitle','addresstitle');
    define('k_uaddress_addressa','streetaddressa');
    define('k_uaddress_addressb','streetaddressb');
    define('k_uaddress_unit','unit');
    define('k_uaddress_city','city');
    define('k_uaddress_state','state');
    define('k_uaddress_zip','zip');
    define('k_uaddress_zipplusfour','zipplusfour');

    require_once '../DBLibrary/pdocore.php';

    class SYS_UserAddress {

        public $addressid;
        public $userid;
        public $addresstitle;
        public $addressa;
        public $addressb;
        public $unit;
        public $city;
        public $state;
        public $zip;
        public $zipplusfour;

        public function SYS_UserAddressByAddressId($_addressid) {

            $returnValue=FALSE;

            $query='select * from useraddress where ' . k_uaddress_addressid . '=:addressid';

            try {
                $pdoCore = Core::getInstance();
                $pdoObject = $pdoCore->dbh->prepare($query);

                $queryArray = array(':addressid'=>$_addressid);

                if ($pdoObject->execute($queryArray)) {

                    $pdoObject->setFetchMode(PDO::FETCH_ASSOC);;

                    while ($addressrow = $pdoObject->fetch()) {

                        $this->addressid=$addressrow[k_uaddress_addressid];
                        $this->userid=$addressrow[k_uaddress_userid];
                        $this->addresstitle=$addressrow[k_uaddress_addresstitle];
                        $this->addressa=$addressrow[k_uaddress_addressa];
                        $this->addressb=$addressrow[k_uaddress_addressb];
                        $this->unit=$addressrow[k_uaddress_unit];
                        $this->city=$addressrow[k_uaddress_city];
                        $this->zip=$addressrow[k_uaddress_zip];
                        $this->zipplusfour=$addressrow[k_uaddress_zipplusfour];

                    }
                    $returnValue=TRUE;
                }
            }
            catch(PDOException $pe) {
                trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
            }

            return $returnValue;

        }
    }

    $test=1;
    $testAddressId=2;

    if($test>0) {

        $testAddress = new SYS_UserAddress();

        $testAddress->SYS_UserAddressByAddressId($testAddressId);

        echo '<pre>';
        echo print_r($testAddress);
        echo '</pre>';

    }

?>

The post above really helped me. This post I am making now would have gotten me to where I wanted to be faster. That is all. If anything isn't right, I'll be around to fix it.

情释 2024-08-24 12:24:09

$dbh 不在 Foo 的范围内,请改为这样做:

class Foo /*extends PDO*/
{
    public $dbh;

    public function __construct()
    {
        $dbh = new PDO(/*...*/);
    }

    public function bar()
    {
        $this->dbh->prepare('SELECT * FROM table');
        return $this->dbh->execute();
    }
}

此外,Foo 不需要扩展 PDO< /代码>。

$dbh isn't within the scope of Foo, do this instead:

class Foo /*extends PDO*/
{
    public $dbh;

    public function __construct()
    {
        $dbh = new PDO(/*...*/);
    }

    public function bar()
    {
        $this->dbh->prepare('SELECT * FROM table');
        return $this->dbh->execute();
    }
}

Also, Foo doesn't need to extend PDO.

戈亓 2024-08-24 12:24:09

我找到了一个更好的解决方案:
当您在类外部有一个 PDO 连接并且无法在类内部使用该连接时,将该 PDO 对象作为参数发送给构造函数

///这就是我的 pdo 连接

$pdo_object = new PDO('mysql:host=localhost;dbname=blabla','user','pw');

/// 我将该类的实例创建为 obj

$dataObj=new class_name($pdo_obj);

/ //// 类内部 :::simplified

class class_name{

private $handler;//// this is what i use for PDO connection inside the class

public function __construct($connection_name){

    if(!empty($connection_name)){
        $this->handler=$connection_name;
  ///its a great thing that holy php doesnt care much about variant types. any variant is able to carry any object (like PDO obj)
    }else{
        throw new Exception("cant connect bla bla...");
    }



}/////contruct fx

////how i use that pdo connection which is implamented to a local var called handler  with any sql query is : 

$dataSet= $this->handler->query("SELECT * FROM users WHERE ....");



}////endof class

i found a better solution :
when you have a PDO connection outside of your class and cant use that connection inside the class , send that PDO object to the constructor as a parameter

///thats my pdo connection

$pdo_object = new PDO('mysql:host=localhost;dbname=blabla','user','pw');

/// im creating the instance of that class as an obj

$dataObj=new class_name($pdo_obj);

///// inside the class :::simplified

class class_name{

private $handler;//// this is what i use for PDO connection inside the class

public function __construct($connection_name){

    if(!empty($connection_name)){
        $this->handler=$connection_name;
  ///its a great thing that holy php doesnt care much about variant types. any variant is able to carry any object (like PDO obj)
    }else{
        throw new Exception("cant connect bla bla...");
    }



}/////contruct fx

////how i use that pdo connection which is implamented to a local var called handler  with any sql query is : 

$dataSet= $this->handler->query("SELECT * FROM users WHERE ....");



}////endof class
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文