When to close Prepared Statement

Viewed 13295

When to close prepared statements in PHP?

Example:

    $query = "insert into web_reviews (title,added_date,reviewer_home_url,read_more_link,summary) values(?,?,?,?,?)";
    $stmt = $this->db->prepare($query);
    $stmt->bind_params($this->title,$this->added_date,$this->reviewer_home_url,$this->read_more,$this->summary);
    $stmt->execute() or die("Cannot add the date to the database, please try again.");
    $stmt->close();

    $stmt = $this->db->prepare("select id from web_reviews where title = ? and read_more = ?");
    $stmt->bind_params($this->title,$this->read_more);
    $stmt->execute();
    $stmt->bind_results($web_review_id);
    $stmt->close();

Should I use $stmt->close(); here?

Edit:

What is written on the PHP Manual and also one comment from the manual says:

Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Comment:

if you are repeating an statement in an loop using bind_param and so on inside it for a larger operation. i thougt id would be good to clean it with stmt->close. but it broke always with an error after aprox. 250 operations . As i tried it with stmt->reset it worked for me.

2 Answers

I am unable to comment currently, so I am just providing an answer. When you run a prepared statement that queries the database for a result, it will not execute another query unless you remove the current result it is storing. $result = $stmt->get_result(). Secondly, If you will need the result from the first query to be saved so that you use it later, then I recommend using two result sets. The first stores the result from the first execution of $stmt and the second for the second execution. This might not answer the question directly, but it may help someone.

Related