0

I have developed an ajax application in which the server page is called every 5 seconds, for fetching the latest data from database.

Lets say i am calling server.php from my client.html page, every 5 seconds to fetch the response. This is the sample code in client.html:

$(document).ready(function() {  
refresh_msg();
});

function refresh_msg()
{
setTimeout(update_msg, 5000);
}

function update_msg()
{
var url = "server.php";
var params = "task=update&id=12";

http.open("POST", url, true);           
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        var resp = http.responseText;
        }
}
http.send(params);

setTimeout(update_msg, 5000);
}

Now in the server.php file, i am including the database file (database.php) and serving the client requests. This is the sample code:

<?php
include_once 'database.php';

if(isset($_POST['task']) && isset($_POST['id']))
{
$sql = "select message from user_messages where id='".$_POST['id']."'";
$res = mysql_query($sql);
// send response
}
?>

And finally this is my database.php file, which has database connection details:

<?php
mysql_connect("localhost:3306","root","root");
mysql_select_db("my_database");
?>

Now the problem what is see is that, for every 5 seconds, a new mysql connection is created (i see a lot of connections getting created in my Mysql Administrator > Server Connections).

I feel that it is not an optimal way to query the database. Instead, can i have one mysql connection and use it for all subsequent ajax requests from the client?

shasi kanth
  • 6,987
  • 24
  • 106
  • 158
  • For every client that has joined the application, the requests are sent to server, every 5 seconds, and i see a lot of mysql connections are created. This is making the mysql server busy. – shasi kanth May 31 '12 at 07:45

2 Answers2

1

If your database server is on the same machine as the web server, the amount of overhead in creating a new connection on each request is really quite minimal. In the majority of simple use cases, creating a new connection to the database per request is probably just fine. If your database server is too busy, it likely has to do with the design of the application, NOT because of connections being opened and closed (see down below for a better solution).

If that answer simply isn't acceptable, you can explore using persistent database connections instead. In a generalized example with Apache, which is one of the most popular web servers out there, there are two cases:

  1. Standard connections. Apache's parent process will create some number of worker processes (as defined in Apache's configuration) which are used to handle requests. If a PHP file is requested, an instance of the PHP interpreter will be created in that worker process. Further, if a MySQL connection is requested during the interpretation of the PHP file(s), a connection to the database will be established. When the script execution is complete, the connection to the database will be closed.

  2. Persistent connections. All of the above is true except for one difference: when the PHP script is done executing, the connection to the database from that Apache process will NOT be closed. Then, if the next request handled by that worker requests the same database connection (that is, a connection to the same database, on the same host, with the same user/password), the previously-used connection will be re-used.

Whether or not persistent connections have a real impact on your performance depends on many factors, which range from web server capacity and configuration to application design and database structure.

A better solution:

Generally speaking, you probably don't need persistent connections; if you feel your database is too busy due to polling (the process of checking every X seconds), you'd be better off implementing a cache layer and eliminating the trip to the database entirely.

Supposing that you have a user-to-user messaging application, you could write some basic cache logic like:

  1. Upon the first request a user's page makes, query for his messages and put the most recent (or whatever) in a cache like memcached
  2. Each time the user polls, check to see if the value is in the cache; if it is, no change
  3. Each time a user sends a message to another user, remove the receiving user's last message from the cache
  4. The next time the receiving user polls the server, it will see no message is there, and go back to the database for the most recent value

Polling a database directly every few seconds will generally lead to an application that does not scale very well.

futureal
  • 3,025
  • 1
  • 22
  • 33
0

Connection pooling would be your answer. I am not a PHP expert but I could not find anything on google showing you how to do connection pooling.

You might want to read this SO question for some more information: Connection pooling in PHP

Hope that helps.

Community
  • 1
  • 1
Namphibian
  • 12,046
  • 7
  • 46
  • 76