nikitz
nikitz

Reputation: 1091

How to avoid repeatedly connecting to the database

I have this PHP script which is called every second from each user in my website:

<?php
$user = addslashes($_POST["user"]);
require("db.php");

$query = mysql_query("SELECT * FROM users WHERE username = '$user'");
$row = mysql_fetch_array($query);
$id = $row["id"];
$date = date( 'Y-m-d H:i:s', time() );

$query = mysql_query("SELECT * FROM activity WHERE id_key = '$id'"); 
if (mysql_num_rows($query) > 0) 
{ 
    $upload = mysql_query("UPDATE activity SET last_activity = '$date' WHERE id_key = '$id'");
    if (!mysql_query($upload))
    {
         die('Error: ' . mysql_error());
    }
}
else{
    $sql = "INSERT INTO activity (id_key, last_activity) VALUES ('$id', '$date')";
    if (!mysql_query($sql))
    {
        die('Error: ' . mysql_error());
    }
}

I want to know if there is a way to do it better or how to remove db connection every time, because this overloads my hosting cpu.

Upvotes: 1

Views: 114

Answers (1)

Itay Grudev
Itay Grudev

Reputation: 7424

With PHP you can't avoid that. Apache handles every request by starting a new, independent PHP process and thus a new connection to the database is required for every new process.

Indeed, the time necessary to establish a connection is small, but certainly it is not "a few short microseconds". Depends on your infrastructure it would take a few milliseconds to establish a connection.
Note that the drivers always establish a TCP socket, probably encrypted so there is some penalty in connecting, but in standard PHP environment it cannot be avoided.

Upvotes: 1

Related Questions