Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP how to check if a MySQLi query needs to be closed?

I created a simple MySQLi class for a project I'm working on to make it easier and more streamlined to pull from and push to the DB. (also to get more familiar with OOP in PHP)

A problem I keep running into is in an effort to make it as efficient as possible. I try to close / free every query / statement / result set. In doing so I get the following error a lot:

Warning: mysqli_result::close(): Couldn't fetch mysqli_result

I think I get the above specifically because it's trying to close the query twice in a row.

Currently my class can make prepared and unprepared statements. So I try to close queries / statements in 2 places. I check when preparing a statement if I have already prepared a statement, if so I need to close the old one before I make a new one and lastly in the destructor of the class.

I realize I could just close the query / statement after I've pulled and stored the result but this seems to be messy for a few reasons. For one it removes the possibility of reusing the prepared statement. As well as disallowing me to pull some information about the query after it's been run such as affected rows and the like.

I know I could just store this info for every query and what not but it just seems like the proper way to go about this problem would be to close / free the query / statement if I need to make another one, and again at the end of the script.

I have tried looking around and reading up on how I should properly handle this task but I have been unable to come up with anything.

So my question is, is there anyway to test if a query or statement needs to be closed or freed? Or is there a better way I should be attempting to tackle this issue?

Thanks for any help or insight anyone can offer.

like image 605
anomareh Avatar asked Nov 14 '22 13:11

anomareh


1 Answers

I think that if there are no rows left in the result set, it should be closed automatically. So, if you iterate through the whole result set, there's no need to call mysqli_result. However, you should close it if you fetch, let's say, only the first row from a result set containing about 100 rows.

like image 136
Ignas R Avatar answered Dec 11 '22 04:12

Ignas R