Re: When to call mysqli::close
| From: | Stuart Dallas | Date: | Tue, 31 Jan 2012 16:46:22 +0000 |
| Subject: | Re: When to call mysqli::close | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-316438@lists.php.net to get a copy of this message | ||
On 31 Jan 2012, at 16:28, Albert Kamau wrote:
> When should i call mysqli::close ? 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
This has little to do with MySQLi and lots to do with where the variable is assigned.
> public function function_name($id,$new_id ){
> $query = "UPDATE TABLE SET name = ? WHERE field = ? ";
> if($stmt=$this->prepare($query)){
If this succeeds then you have a statement variable, so whatever happens from now on you'll
need to clean up this variable.
> 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";
> }
At this point you clean up $stmt because you know it's been assigned. There's no point in
doing it in every else above because all paths through the code will reach here regardless of any
errors. If one of the elses above was returning out of the method then you'd need to make sure
you clean up $stmt before than happens.
> }else{
If you get in here then $stmt evaluates to false, so there's nothing to clean up.
> $message = "Could not prepare the statement";
> }
> return $message
> }
You may want to think about the order of your conditions. Personally I like to have the expression
in the if evaluate to true if there was a problem, that way the error handling and the thing that
caused the error are next to each other which I feel makes the code easier to read. Consider…
public function function_name($id, $new_id)
{
// Initialise the return value
$message = false;
// Prepare the statment
$stmt = $this->prepare('UPDATE TABLE SET name = ? WHERE field = ?');
if (!$stmt) {
$message = 'Could not prepare the statement';
} else {
// Bind the parameters and execute the statment
if (!$stmt->bind_param('is', $id, $new_id)) {
$message = 'Could not bind the parameters';
} elseif (!$stmt->execute()) {
$message = 'Could not execute the prepared statement';
} else {
// Everything worked, probably want to do something with
// $message here.
}
// Clean up the statement
$stmt->close();
}
return $message
}
Also, I know this is probably just an example, but based on the function parameters either your SQL
is wrong or the order of the parameters is wrong when binding, possibly both.
-Stuart
--
Stuart Dallas
3ft9 Ltd
http://3ft9.com/