When should i call mysqli::close? I never used to use if statements to check whether bind_param(), prep() and execute() were successful. Should I call $stmt->close() at the end of the method(below) . Or should I call it after every condition ensuring that I close the database connection even if the process fails at some stage e.g bind param.
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
}
When PHP exits it closes the database connections gracefully.
The only reason to use the close method is when you want to terminate a database connection that you´ll not use anymore, and you have lots of thing to do: Like processing and streaming the data, but if this is quick, you can forget about the close statement.
Putting it in the end of a script means redundancy, no performance or memory gain.
Whats is important: unset unused data, and if you will want to avoid memory leaks (which in my humble opnion are problem of PHP core in this case) use:
mysqli_kill();
mysqli_close();
This way the socket is killed too.
You should always gracefully close the connection when you are done with it, to avoid performance and memory/handle leak problems. On the other hand, you should also make sure that you really are done with it - your script will crash if you try to use a closed connection.
The same goes for statements. If a statement is no longer going to be used, dispose of it appropriately.
Just a little thought you could create another method called function_close
and call it after you have called the function_name
method.
This way if you change to pdo or mongo you will just have to refactor the methords rather than every instance of close
.
you should close it especially after a multi query (http://php.net/manual/en/mysqli.multi-query.php) because you could get memory problems. Otherwise closing is not needed.