简体   繁体   中英

Store database (PDO) connection

I'm currently writing a PHP application and i noticed that my page loads kinda slow. I takes about 2 seconds (2.0515811443329 to be exact).

I've tracked down what the bottleneck was and it's the part where i'm creating a PDO connection to my MySQL database.

My 'connect()' method doesn't do any exoctic stuff. It simply looks like this:

public function connect ( $database, $host, $username, $password )
{
    try
    {
        $this->db = new \PDO("mysql:dbname=".$database.";host=".$host, $username, $password);
        if ( !$this->db )
        {
            throw new \Exception('Failed to connect to the database!');
        }

        $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    }
    catch ( \Exception $e )
    {
        echo '<strong>Exception: </strong>'.$e->getMessage();
        return false;
    }

    return true;
}

So when i comment out the call to the 'connect()' method, then my page loads in: 0.035506010055542

This is a huge difference. I can imagine that creating a connection to a database does take up some time, but it takes more than 1,5 seconds... I'm not sure if this is normal?

If it is normal, that it takes up that amount of time then is there a way to store the database connection? Like putting it in a session? Actually, as far as i know storing it in a session isn't possible. But it would be the ideal solution. Storing the connection somewhere until the user closes his browser.

In anyway, is there a problem with my PDO / MySQL? And can i simply store the connection resource somehow? So that i don't have to reconnect to my database everytime for every new page?

PS. I'm doing this all on a localhost (Windows).

You're probably making a connection with 'localhost' as address. Try to change that to '127.0.0.1'. That should fix the problem.

You can create a persistent connection to database using PDO . From the manual

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

And example:

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

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