PHP/MySQL: Create new connection for each query?

2020-07-27 05:52发布

问题:

I have a webpage with some mysql querys, I must start new db connection and db close after every query or its more efficiently start an only one db connection at the top of the code and close at the bottom of the script? Thanks!

回答1:

Never create a new connection for every query; it's very wasteful and will overburden your MySQL server.

Creating one connection at the top of your script is enough - all subsequent queries will use that connection until the end of the page. You can even use that connection in other scripts that are include()ed into the script with your mysql_connect() call in it.



回答2:

I prefer to create some sort of class called Database of which upon creation will create a database connection using mysqli (OOP version of mysql).

This way i do not have to worry about that and i have a static class that has access to the database.

class MyAPI {
    private static $database = false;

    public static function GetDatabase() {
        if (MyAPI::$database === false) {
            MyAPI::$database = new Database(credentials can go here)
        }
        return MyAPI::$database;
    }
}

Now your system with the includsion of your API and your database can access the database and its initialization code does not have to be peppered around your files depending on what part of the program is running and your database/connection will not be created if it is not needed (only until it is called).


Just for fun i also like to have a function in my Database class that will perform a query and return its results, this way i do not have to have the SAME while loop over and over again throughout my code depending on where i make these calls.


I also forgot to answer your question. No multiple connections! its baaaad.



回答3:

Only create one connection. You don't even have to close it manually.



回答4:

multiple connexion is better for security and tracking. if you're going though a firewall between front and back there will be a timeout defined so a single connection will be a problem. but if your web server is on the same host as mysql, a single connection will be more efficient.