php - Why do we close result in Mysqli -
why closing $result
$mysqli = new mysqli("localhost", "root", "root", "test"); if ($mysqli->connect_errno) { echo "failed connect mysql: " . $mysqli->connect_error; } if ($result = $mysqli->query("select * user")) { while ($row = $result->fetch_object()) { //var_dump($row); } $result->close(); }
your check if connection failed falls through code uses connection. won't work because it's not live connection. make sure if connection fails, code depends on not reached. (note i'm not necessary advocating use of exit or die. can make rather bad user experience. can useful, ideally should output better message , leave ugly error stuff logs [unless you're testing or it's command line script]).
as close() (which alias free()):
free() deallocates of stuff attached result. need understand there 2 (simplification, go it) ways of retrieving rows:
buffered - snatched in 1 go. in other words, time start looping through records, they're in memory. buffered. not being pulled server every time call fetch() rather being pulled memory.
non buffered - there may small buffer, every time call fetch(), php must pull new row database. @ beginning of loop, not sitting in memory.
interesting note: num_rows() can called on buffered query efficiently since of rows pulled (though should never pull of rows count them -- that's count for). non buffered queries cannot num_rows() until pull of rows. meaning either error, or turn buffered query.
anyway, actual question:
free() frees associated result object. in case of buffered query, rows sitting in memory. in case of non buffered query, free() release whatever rows may sitting in memory , cancel rest of request. php telling mysql, "hey know rows request? changed mind. can drop request."
as if should free results... well, whenever variable goes out of scope*, happen anyway. there is, however, no harm in explicitly doing it, , in situations query may use lot of memory , query after may use lot of memory, may wish free sets keep memory usage low.
* or maybe when request ends. don't remember off top of head.
Comments
Post a Comment