[英]How to close the MySQLi connection?
具有以下代碼,如果我嘗試在控制器中執行它,則創建此類的實例並始終導致get_one,然后導致get_two,則返回錯誤,因為get_two mysql-connection已關閉。
class Foo extends Bar
{
function __construct()
{
parent::__construct();
$this->mysqli = new mysqli($this->cfg->db->host,
$this->cfg->db->user,
$this->cfg->db->password,
$this->cfg->db->database);
$this->mysqli->query('SET NAMES utf8');
}
public function get_one()
{
$table_one = array();
$result = $this->mysqli->query('SELECT * FROM `table_one`');
for ($i=0; $row = $result->fetch_assoc(); $i++) {
$table_one[] = $row;
}
$result->close();
$this->mysqli->close();
return $table_one;
}
public function get_two()
{
$table_two = array();
$result = $this->mysqli->query('SELECT * FROM `table_two`');
for ($i=0; $row = $result->fetch_assoc(); $i++) {
$table_two[] = $row;
}
$result->close();
$this->mysqli->close();
return $table_two;
}
}
只想到這個
public function get_one($keep = false)
{
...
if(!$keep)
$this->mysqli->close();
...
}
如何正確的方式?
您不想在每個函數中關閉MySQL連接,而是在銷毀類時關閉。 從PHP 5開始,您可以使用__destruct()函數。 當不再有任何對對象的有效引用時,將自動調用此函數。 嘗試刪除:
$this->mysqli->close();
來自get_one()和get_two()。 然后將以下函數添加到您的類中:
function __destruct()
{
//try to close the MySql connection
$closeResults = $this->mysqli->close();
//make sure it closed
if($closeResults === false)
{
echo "Could not close MySQL connection.";
}
}
這將使您的連接在類破壞時關閉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.