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?