何时应该调用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