【问题标题】:How to pass db object to mysqli_query in PHP class method如何在 PHP 类方法中将 db 对象传递给 mysqli_query
【发布时间】:2015-06-19 04:14:46
【问题描述】:

我正在尝试在类方法中进行 Mysql 查询,并尝试将 db 对象传递给 mysql_query 函数。

但它给出了这个错误: mysqli::query() 期望参数 1 是字符串,对象在...中给出。

<?php
class Database
{
    private $db_host = DB_HOST;
    private $db_user = DB_USER;
    private $db_pass = DB_PASS;
    private $db_name = DB_NAME;
    public $link;
    public $error;

    // Constructor
    public function __construct()
    {
        $this->connect();
    }
    private function connect()
    {
        $this->link = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
        if (!$this->link) {
            $this->error = "Database'e baglanilamiyor: " . $this->link->connect_error;
            return false;
        }
        $this->link->query($this->link, "SET NAMES UTF8");
    }
}

我不确定如何将 db 对象传递给类内查询... 任何帮助表示赞赏。

【问题讨论】:

  • 我认为你的连接函数需要返回连接对象。尝试一下,看看是否有效。
  • 试试 $this->link->query("SET NAMES UTF8", $this->link);
  • RTFM: php.net/manual/en/mysqli.query.php 在对象模式下,您不会传入连接句柄。这仅在程序模式下是必需的。

标签: php mysql class oop


【解决方案1】:

使用 mysqli 对象执行查询是这样完成的:

$mysqli_instance->query('select/update/...');

在您的情况下,mysqli_instance 是$this-&gt;link,而查询是"SET NAMES UTF8"。只需在上面的模式中替换两者:

$this->link->query("SET NAMES UTF8");

【讨论】:

    【解决方案2】:

    当您创建一个数据库对象时,您需要使用单例才能连接到该数据库一次。 您需要创建一个数据库实例并在释放连接之前验证它是否已连接。

    然后,当您进行查询时,它将看起来像这样。

       public static function getInstance()
        {
            if (!self::$_instance) { // If no instance then make one
                self::$_instance = new self();
            }
    
            return self::$_instance;
        }
    
        /**
         * Magic method clone is empty to prevent duplication of connection
         */
        private function __clone() { }
    
        /* Return a connection */
        public function getConnection()
        {
            return $this->_connection;
        }
    

    然后要访问这个数据库并进行查询,你需要做这样的事情。

       /** @var Database $connection */
        $db = Database::getInstance();
        $connection = $db->getConnection();
    
      /** You need to create your query then use this kind kind of statement assuming you have already done the rest */
      $result = mysqli_query($connection , $query);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 2011-09-04
      • 2021-04-28
      • 2017-07-29
      • 1970-01-01
      相关资源
      最近更新 更多