0

I am new to open source (and PHP in particular) and have a question, maybe someone could offer an answer.

I want to connect to a DB but I want to use one external file that will have the DB settings and connect to server and DB.

When doing it in the PHP file, it's easy, I setup everything, call the: mysql_connect() method and then call the: mysql_select_db() method, do what ever I need to do and close the connection.

What I am asking is how do I close the connection if I put all the settings and the connect and select_db methods in an external helper file and just want to include it?

I really couldn't find anything about this, it looks like the connection is persistent and I don't want it to stay open for every user that connect to the DB.

What am I missing here?

4 Answers 4

1

There are several approaches:

  • Once the PHP finishes execution, all the database connections will close.
  • If you have only one connection, mysql_close() will close it.
  • If you have more than one connection, you should have a global variable to keep track of each connection and use mysql_close($res) to close each one.
Sign up to request clarification or add additional context in comments.

Comments

1

mysql_connect() will not open a persistent connection, the lifetime of the connection resource is until the last ?> is reached or mysql_close($con) is called. If you want to open a persistent connection use mysql_pconnect().

That said, it is worth your while looking into the PDO ( http://php.net/manual/en/book.pdo.php ) for database resources, it'll help you learn PHP from an OO perspective and gives you access to far more features than standard the mysql_ functions.

Comments

0

To put it all in an external file, just put your code in a separate .PHP file inside the standard <?php ?> tags and then use include "externalFile.php";

Comments

0

if you want to close connection you can use mysql_close() method at the end of the page where you include your db setting file

if you use class for the connection make function to close connection and call that function using object You can not close it in

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.