在线访问大型交通网站的访客

时间:2010-10-26 13:48:38

标签: php mysql optimization performance query-optimization

我管理着一个相当大的交通网站。在每个页面上,我们通过运行以下代码在线跟踪访问者。然后我们有一个cron删除超过X分钟的记录。

 if(!isset($_SESSION[users_online_id])) {
 if(!(date('H')=='02' && date("i") >= 37 && date("i") <= 45)) {
 # NEW VISITOR - DOESN'T HAVE A USER_ONLINE_ID
  $update_query = "INSERT INTO online SET
  ip_address = '".$visitors_ip_address."',
  datetime = now(),
  user_id = ".$visitor_id.",
  page = '".escape($_SERVER[REQUEST_URI])."',
  area = '".$this_area."',
  type = ".$visitor_type;
  mysql_query($update_query);

  # SET THEIR SESSION VAR FOR NEXT PAGE CHECKING
  $_SESSION[users_online_id] = mysql_insert_id();
 }
     }
     else{
 # USER HAS A SESSION

 # CHECK THAT THE RECORD STILL EXIST
 $check_record = "SELECT COUNT(1) FROM online WHERE id = ".$_SESSION[users_online_id];
 $check_record = mysql_query($check_record);

 if(mysql_result($check_record,0) > 0){
  # IF RECORD STILL EXISIT ( WAS NOT DELETED) UPDATE IT
  $update_query = "UPDATE online SET 
  datetime = now(),
  user_id = ".$visitor_id.",
  page = '".escape($_SERVER[REQUEST_URI])."',
  type = '".$visitor_type."',
  area = '".$this_area."',
  ip_address= '".$visitors_ip_address."'
  WHERE id = '".$_SESSION[users_online_id]."'";
  mysql_query($update_query);
 }
 else if(!(date('H')=='02' && date("i") >= 37 && date("i") <= 45)){
  # IF RECORD WAS DELETED (TO LONG ON 1 PAGE), INSERT A NEW RECORD
  $update_query = "INSERT INTO online SET
  ip_address = '".$visitors_ip_address."',
  datetime = now(),
  user_id = ".$visitor_id.",
  page = '".escape($_SERVER[REQUEST_URI])."',
  area = '".$this_area."',
  type = ".$visitor_type;
  mysql_query($update_query);
  $_SESSION[users_online_id] = mysql_insert_id();
 }
      }

进行一些性能监控,我注意到与该表交互的查询开始花费更长的时间来执行。关于如何改进的任何想法?

2 个答案:

答案 0 :(得分:1)

您可以消除SELECT查询并使用UPDATE查询和mysql_affected_rows()函数。

答案 1 :(得分:0)

小点但是......

$ _ SERVER ['REQUEST_URI']比$ _SERVER快7倍[REQUEST_URI]

还要确保将id设置为主键。