简体   繁体   中英

Do I need to connect db every time in php?

I have a Class called User, and have 2 methods, one is "login", another is "register". Both "login" and "register" requires connect the db. Do I need to connect db everytime?? Can I have something which connect once only to reduce the time of connecting db? Thank you.

Keeping a connection to the database open requires dedicated resource on both the web server and the database server, and the number of open connections available is often very limited (in the range of 100). The connection process is usually very fast, and shouldn't be a problem. By opening and dropping connections as quickly as possible, it's usually no problem to scale up.

As always, try the simple and lightweight approach first (which would be connecting every time and dropping the connection as soon as possible). From there you can measure if there really is a problem.

Yes you need to connect every time. But you can actually reduce the load of connecting by using mysql_pconnect() as long as your username, host and password is same. This will check if there is any active resource with the same connection DSN. If found, it will then return the same object as long as it it alive, instead of creating a new connection.

Hope that helps.

In that case class User should expect a DB connection object provided in the constructor. Then the constructor should save it as local variable, and both login() and register() methods would expect that this variable contains a valid connection object.

And, please, use PDO instead of old mysql_* methods. This will give you a connection object, that you can share among all the classes, which require a DB connections

Yes Sir. Everytime a user connects to your application to do a Login Action o Register Action a connection to the DB must be opened and closed at the end. A Keep Alive option will kill your server.

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