2012-08-26 33 views
0

我有一个足球幻想联盟的PHP脚本,有20个球队和400多名球员分配到球队,我有500个用户。向数据库添加一些数据后,php更新代码很慢?

每个星期都应该给每个玩家分配一个分数,这样最终每个用户都会有一个总分数,并且这个分数会产生本赛季的排名。

正常添加了第一周的积分,但第二周的积分变得非常缓慢,第三周的积分出现套接字超时错误。

这里是我使用的是在加分的用户代码:

// Adding Point To the user player list 
$sql_user="select * from ".$prev."user LIMIT 0, 100 "; 

$re_user=mysql_query($sql_user); 
while($d_user=mysql_fetch_array($re_user)) 
{ 
$userID=$d_user['id']; 

    $sql_addpointgroup="select * from ".$prev."addpoint group by weekno order by weekno"; 
    $re_addpointgroup=mysql_query($sql_addpointgroup); 
    while($d_addpointgroup=mysql_fetch_array($re_addpointgroup)) 
    {  
     $points=0; 
     $sql_addpoint="select * from ".$prev."addpoint where weekno='".$d_addpointgroup['weekno']."'"; 
     $re_addpoint=mysql_query($sql_addpoint); 
     while($d_addpoint=mysql_fetch_array($re_addpoint)) 
     { 
     $points=$d_addpoint['points']; 
     $sql_weekstatistic="select * from ".$prev."weekstatistic where weekno='".$d_addpointgroup['weekno']."' and userID='$userID' and playerID='".$d_addpoint['playerID']."'"; 
     $re_weekstatistic=mysql_query($sql_weekstatistic); 
     if(mysql_num_rows($re_weekstatistic)>0) 
     { 
      $sql_update="update ".$prev."weekstatistic set points='$points' where weekno='".$d_addpointgroup['weekno']."' and userID='$userID' and playerID='".$d_addpoint['playerID']."'"; 

      mysql_query($sql_update); 
     } 
     } 
}  
} 

我有限的用户数100个用户每提交即使这样的代码仍然缓慢。

慢的只有这个代码其他网站部分正常工作。

有什么方法可以用其他更快的方式编写代码,或者如果还有其他事情我可以做?

许多在此先感谢,

+0

仅供参考,您的查询可能并不安全。您不会转义任何数据以用于查询,并且可能会被黑客入侵。考虑使用PDO准备好的查询来避免此问题。 – Brad

+0

我想补充,如果你不希望使用PDO可以使用real_escape_string()来防止SQL注入黑客攻击你的脚本。这是一个很好的链接,展示了如何使用它。 http://php.net/manual/en/mysqli.real-escape-string.php – Ishikawa

+0

请您解释一下,并检查您是否使用了正确索引的查询,没有全表扫描等。 – jfried

回答

1
select * from 

我希望你知道的*SELECT查询的含义。 这意味着ALL COLUMNS。 您不需要每行的所有列的值。 请在您的查询中具体说明,并只选择您需要的列。

例如,这个查询:

$sql_weekstatistic="select * from ".$prev."weekstatistic where weekno='".$d_addpointgroup['weekno']."' and userID='$userID' and playerID='".$d_addpoint['playerID']."'"; 

你已经拥有的价值:

weekno @ $d_addpointgroup['weekno'] 
userID @$userID 
playerID @$d_addpoint['playerID'] 

基于其他查询。

但是,您仍然使用SELECT * FROM

这是我关于性能和SQL的小技巧。

BTW,保护您的查询,使用mysql_real_escape_tring(), 或者,甚至更好,移动到mysqliPDO作为@lshikawa是在暗示。

+0

我相信是这样的话,没有理由使用'*'除非真的有必要或你的表是非常小的。上投了反对票。了解更多关于SQL注入的位置:http://stackoverflow.com/questions/11939226/sql-injections-and-adodb-library-general-php-website-security-with-examples –

0

我不会提及SQL注入的问题,而是建议您遵循本主题中其他人的建议。严重 - 如果您要求人们提交个人数据以存储在您的数据库中,则应该保护他们免于窃取数据。

您的过程缓慢的原因可能是双重原因。

首先,当只有一个是必要的时候使用5个查询。你问的大量数据,你用它来问它更多的问题数据库 - 不知道您的架构,很难给你一个工作更换,但是这样的:

update ".$prev."weekstatistic 
set  points = ap.points 
from  weekstatistic ws, 
     addpoint  ap, 
     user   u 
where weekno = //work out the current weeknumber 
and  userID = u.userID 
and  playerID = ap.playerID' 

这应达到同样的,但只有一个查询;这应该快得多。

其次,你可能没有你的表进行正确的指标 - 这是一个经典的原因“正如我在表中获取更多的数据我的查询变慢”。阅读EXPLAIN,并添加一些索引。