我试图在类方法中进行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对象传递给类内查询... 任何帮助表示赞赏。
答案 0 :(得分:0)
使用mysqli对象执行查询是这样完成的:
$mysqli_instance->query('select/update/...');
在您的情况下,mysqli_instance为$this->link
,查询为"SET NAMES UTF8"
。只需在上面的模式中替换两者:
$this->link->query("SET NAMES UTF8");
答案 1 :(得分:0)
创建数据库对象时,需要使用singleton才能连接一次该数据库。 您需要创建数据库实例并在释放连接之前验证它是否已连接。
然后当你进行查询时,它看起来像这样。
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);