简体   繁体   中英

How to connect to MySQL using php and external file and control open and close DB

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?

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.

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.

要将它全部放在外部文件中,只需将代码放在标准<?php ?>标记内的单独.PHP文件中,然后使用include "externalFile.php";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM