0

I'm building a PHP site mainly via peaking at other peoples code. The code in particular I'm attempting to mimic has this line of code at the bottom of almost all of their .PHP files that have anything to do with SQL connections...

// Never forget to close the connection, otherwise memory leaks will happen!
mysqli_close($dbConnection);

So my question is; does his comment have some merit? Should I always be closing my mysqli connections in this fashion in all of my PHP files? Or would that be wasting my time, and does it happen automatically or something?

Thanks in advance!

Samuel Stiles
  • 2,118
  • 5
  • 22
  • 27
  • this question is already raised ...before..http://stackoverflow.com/questions/880885/is-closing-the-mysql-connection-important – sAnS May 26 '13 at 06:45

2 Answers2

3

I'm building a PHP site mainly via peaking at other peoples code.

That's quite wrong approach in case of learning PHP, as this language have very bad ancestry - so, 99% of code you may find will be plainly awful, full of bad practices and wild superstitions.

You'd make yourself a huge favor if start building your site peeking into some modern PHP framework tutorial.

Regarding the question you asked - no, it is not that strictly necessary. Make your PHP scripts always run fast, die young - and you will never ever have a need in closing whatever resources manually.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
2

Short answer is no. The comment if false.... but, while a connection is open it is consuming resources both on the webserver and database server and you should, as soon as your done with it, close it down.

Imagine a situation where after you grab the data from the server you have to do some complex calculation and layout, this will take time and you will be consuming a connection to the server.

You're being kinda like that annoying guy in the checkout lane of a store that after he gets his change, has to stand there and organize his wallet instead of getting the hell out of the way so you can check out.

Orangepill
  • 24,500
  • 3
  • 42
  • 63
  • So you're saying, you should design your code in a way in which it does all the calculations -- then opening when you require a database connection to place information. If you can structure your code like this, you won't need to close your MySql at the end. +1 – Dave Chen May 27 '13 at 03:40