Question

BACKGROUND:

I am passing variables through AJAX to php file. The php file connects to a server and retrieves the result which it passes back to javascript. This happens every time a user clicks on the request button (about every 5 secs). Thus for each user, the php file (and so the mysql connection) is called once every 5 secs.

ISSUE:

As is apparent above, the number of mysql connections are impractically high.

QUESTION:

Is there a better architecture where instead of having so many mysql connections, I can rather have fewer connections.

enter image description here

I have read a little bit about mysql_pconnect. But what happens if I have to upgrade since I read somewhere that mysqli doesnt support it? How many queries can a single mysql_pconnect handle? If anyone suggests mysql_pconnect then how to implement it?

Was it helpful?

Solution

Is there a better architecture where instead of having so many
mysql connections, I can rather have fewer connections.

Don't really know, but I think that for you the proposed pconnect is the best available option. Unless you have either mysqli or PDO_mysql available now?

I have read a little bit about mysql_pconnect.
But what happens if I have to upgrade since I read somewhere that mysqli doesnt support it?

You would probably need to change method when upgrading beyond PHP 5.5.

How many queries can a single mysql_pconnect handle?

Unlimited, as long as the connection is kept alive. If there are no available free connections a new one is created.

If anyone suggests mysql_pconnect then how to implement it?

Change your current mysql_connect calls to mysql_pconnect. That should be all.

OTHER TIPS

What you are looking for is singleton design pattern for database connections. But it has it's trade off too. Example code for singleton design for database would be as below.

define('DB_NAME', "test");
define('DB_USER', "root");
define('DB_PASS', "rootpass");
define('DB_HOST', "localhost");

class Connection{
    private static $connection_;

    private function __construct(){
        $con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
        mysql_select_db(DB_NAME, $con);
        Connection::$connection_ =  $con;
    }

    public static function getConnection(){
        if( !Connection::$connection_ )
            new Connection;
        return Connection::$connection_;
    }

}

$con = Connection::getConnection();

Read more

php singleton database connection, is this code bad practice?

How static vs singleton classes work (databases)

You can find tons of example and information if you google. Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top