I have a large download site, an i have a code that updates each download to keep track of how many unique person download each file and how many total person view the file.
However, the code works fine, but when I have alot of traffic, the code slows down the site, an allow mysql server to use alot of resource. Is this code optimizable ?
I would appreciate someone to do it for me, whether by inner joining them etc. Thanks
<?php
#Gathers the client info
$agent = $_SERVER['HTTP_USER_AGENT'];
$brows = explode(" ",$agent);
$ubr = "$brows[0]";
$exptime = time() + 200;
$var = time();
$uip = user_ip();
$del = mysql_query("DELETE FROM log_hits WHERE exptime < '".$var."'");
$hits = mysql_fetch_array(mysql_query("SELECT * FROM user_downloads WHERE id='".$file_id."'"));
#Process unique download count
$u_check = DB::FetchArray(DB::Query("SELECT COUNT(*) FROM log_hits where browser='".$ubr."' and uip='".$uip."' and file_id='".$file_id."'"));
if($file_check[0]=="0")
{
$res3 = DB::Query("INSERT INTO log_hits SET browser='".$ubr."', uip='".$uip."', exptime='".$exptime."', file_id='".$file_id."'");
$unique = $hits[day_unique] + 1;
}else
{
$unique = $hits[day_unique];
}
#update regular hits to the file,
$week = $hits[weekly] + 1;
$hour = $hits[this_hour] + 1;
$todayx = $hits[today_hits] + 1;
$total = $hits[total] + 1;
$month = $hits[month] + 1;
$res3 = DB::Query("UPDATE `user_downloads` SET `day_unique`='{$unique}', `weekly`='{$week}', `this_hour`='{$hour}', `month`='{$month}', `total`='{$total}' , `today_hits`='{$todayx}' WHERE `id`='".$file_id."'") or die(mysql_error());
?>
You have 5 queries just to update a more or less simple counter. In my opionion this is way to much.
I don’t know about your amount of concurrent users, but I would suggest something like the following approach:
log_hitstable.This would reduce your queries for each download to one. On the other hand the statistics cronjob would only use a single (though more expensive) query to do the work of a multitude of (cheaper) queries each time. Overall this should help to improve the response times of your page.