How do you efficiently connect to mysql in php without reconnecting on every query

前端 未结 2 1997
执念已碎
执念已碎 2020-12-09 11:02

I\'m pretty sick of having to rewrite my code every time I learn something new about php (like the fact that mysql connections cannot be passed around in a session as a hand

2条回答
  •  北海茫月
    2020-12-09 11:11

    Normally connections happen once a page load. AKA

    class Database{
        public function connect()
        {
             $this->connection = mysql_connect();
        }
    
        // This will be called at the end of the script.
        public function __destruct()
        {
            mysql_close($this->connection);
        }
    
        public function function query($query)
        {
            return mysql_query($query, $this->connection);
        }
    }
    $database = new Database;
    $database->connect();
    
    $database->query("INSERT INTO TABLE (`Name`) VALUES('Chacha')");
    

    Basically, you open the connection in the beginning of the page, close it at the end page. Then, you can make various queries during the page and don't have to do anything to the connection.

    You could even do the mysql_connect in the constructor as Erik suggest.


    To use the above using global variables (not suggested as it creates global state), you would do something like

    Global $db;
    
    $db = new Database;
    // ... do startup stuff
    
    function doSomething()
    {
        Global $db;
        $db->query("Do Something");
    }
    

    Oh, and no one mentioned you don't have to pass around a parameter. Just connect

    mysql_connect();
    

    Then, mysql_query will just use the last connection no matter what the scope is.

    mysql_connect();
    
    function doSomething()
    {
        mysql_query("Do something");
    }
    

    Per the comments:

    I think you should use mysql_pconnect() instead of mysql_connect(), because mysql_connect() doesn't use connection pooling. – nightcoder

    You might want to consider whether you use mysql_connect or mysql_pconnect. However, you should still only connect once per script.

提交回复
热议问题