我有一个很大的下载网站,我有一个代码,更新每个下载,以保持跟踪有多少人下载每个文件和有多少人查看该文件。
然而,代码运行得很好,但是当我有大量的流量时,代码会减慢站点的速度,这使得mysql服务器使用了大量的资源。这个代码是可优化的吗?
我很感激有人为我做这件事,无论是通过内部加入他们等等。谢谢
<?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());
?>发布于 2012-03-15 21:44:04
您有5个查询,只是为了更新一个或多或少简单的计数器。在我看来,这实在是太多了。
我不知道你的并发用户数,但我建议使用以下方法:
log_hits表类似的下载日志。这将使您每次下载时的查询次数减少到一个。另一方面,统计cronjob每次只使用一个(虽然更昂贵)查询来完成大量(更便宜的)查询的工作。总体而言,这应该有助于改善页面的响应时间。
https://stackoverflow.com/questions/9720781
复制相似问题