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 

> 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 

>            $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

  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 Dallas
3ft9 Ltd

PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to