對於那些對性能有深入瞭解的人來說,這只是一個簡單的問題。我創建了一個「MySQL」類,每次執行查詢時,我都會創建一個新的MySQL對象。見下面PHP/MySQL性能問題
public function get_am_sales() {
$mysql = new MySQL();
$mysql->connect();
$query = "some query";
$mysql->query($query);
$result = $mysql->return_assoc();
unset($mysql);
return $result;
}
public function get_pm_sales() {
$mysql = new MySQL();
$mysql->connect();
$query = "some query";
$mysql->query($query);
$result = $mysql->return_assoc();
unset($mysql);
return $result;
}
public function get_comp_sales() {
$mysql = new MySQL();
$mysql->connect();
$query = "some query";
$mysql->query($query);
$result = $mysql->return_assoc();
unset($mysql);
return $result;
}
$sales = new Sales();
$amSales = $sales->get_am_sales();
$pmSales = $sales->get_pm_sales();
$compSales = $sales->get_comp_sales();
上面的代碼很明顯的作品,但我想知道如果這是一個性能命中,因爲我打開和關閉與每個函數調用的連接。我試圖用一個連接來實現這個類,但是我得到錯誤。見下面
public function connect() {
$this->mysql = new MySQL();
$this->mysql->connect();
}
public function get_am_sales() {
$query = "SELECT site_id, dly_sls AS am_sales, cov_cnt AS am_covers
FROM v_sales_yesterday
WHERE am_pm = 'AM'
GROUP BY site_id
ORDER BY site_id ASC";
$this->mysql->query($query);
$result = $this->mysql->return_assoc();
return $result;
}
public function get_pm_sales() {
$query = "SELECT site_id, dly_sls AS pm_sales, cov_cnt AS pm_covers
FROM v_sales_today
WHERE am_pm = 'PM'
GROUP BY site_id
ORDER BY site_id ASC";
$this->mysql->query($query);
$result = $this->mysql->return_assoc();
return $result;
}
public function get_comp_sales() {
$query = "SELECT business_date, site_id, dly_sls AS comp_sales
FROM v_sales_today_comp
WHERE am_pm = 'PM'
GROUP BY site_id
ORDER BY site_id ASC";
$this->mysql->query($query);
$result = $this->mysql->return_assoc();
return $result;
}
public function disconnect() {
unset($this->mysql);
}
$sales = new Sales();
$sales->connect();
$amSales = $sales->get_am_sales();
$pmSales = $sales->get_pm_sales();
$compSales = $sales->get_comp_sales();
$sales->disconnect();
執行「連接」函數後mysql連接是否關閉?如果認爲有必要,那麼保持連接打開的最佳方式是什麼(使用面向對象的方法)?如果您需要更多的細節,請告訴我,我很感謝您的幫助。
你得到的錯誤是什麼?通常情況下,您不能重新連接。爲了防止多重連接,你還應該爲你的DB類使用[singleton-pattern](http://php.net/manual/en/language.oop5.patterns.php#language.oop5.patterns.singleton)。 – feeela
我在嘗試查詢時遇到錯誤,這導致我認爲連接在查詢之前關閉。 – Brett
好的,我再問一次:你得到了什麼/哪個錯誤?停止假設,嘗試測試或調試。 – feeela