何時應該調用mysqli :: close?我從來沒有用過if語句來檢查bind_param(),prep()和execute()是否成功。我應該在方法末尾調用$ stmt-> close()(下面)。或者我應該在每種情況之後調用它,以確保即使在某個階段進程失敗時關閉數據庫連接,例如綁定參數。何時調用mysqli :: close
public function function_name($id,$new_id){
$query = "UPDATE TABLE SET name = ? WHERE field = ? ";
if($stmt=$this->prepare($query)){
if($stmt->bind_param("is", $id, $new_id)){
if($stmt->execute()){
}else{//Could not execute the prepared statement
$message = "Could not execute the prepared statement";
}
}else{//Could not bind the parameters
$message = "Could not bind the parameters";
}
}else{
$message = "Could not prepare the statement";
}
return $message
}
除非您處於長時間運行腳本的情況,否則不要執行關閉操作,因爲在腳本退出時,PHP將爲您清理。除非您確定已完成所有數據庫操作,否則不應關閉連接。 – 2012-01-31 16:45:20
@MarcB - 我不確定我是否同意這是很好的做法。雖然PHP會自動將所有內容全部拆除,但如果您打算遷移到本地編程領域,養成照顧資源和處理完它們的習慣是一個非常重要的習慣。 – Polynomial 2012-01-31 16:50:40
順便說一句,你應該看看PHP異常處理,而不是使用'if'語句的巨大嵌套:http://php.net/manual/en/class.exception.php – Crontab 2012-01-31 17:04:00