我使用一个简单的脚本来检查MySQL表格中的先前邀请并发送新邀请。但是这个脚本使服务器忙,并减慢了其他脚本的运行速度。我该怎么改变它?
for ($g=0; $g<500; $g++){
$lastsent = time() - (86400*30*6); // last 6 months
$chkinvlast = mysql_query("SELECT * FROM table WHERE (inv_email='$useremail[$g]' AND inv_datesent>'$lastsent')");
if (@mysql_num_rows($chkinvlast) < 1){
send_email($useremail[$g],$ltitle,$lbody);
}else{
echo "<br>Invitation for $user was NOT sent, because you already sent an invitation in last 6 months";
}
}
答案 0 :(得分:1)
删除for循环
$usermails = "(".implode(',',$usermail).")";
mysql_query("SELECT * FROM table WHERE (inv_email IN ($usermails) AND inv_datesent>'$lastsent')");
或准备好的陈述:
$usermails = "(".implode(',',$usermail).")";
$in = str_repeat('?,', count($usermails) - 1) . '?';
$sql = "SELECT * FROM table WHERE inv_email IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($usermails);
$row= $stm->fetchAll();
答案 1 :(得分:0)
不要对服务器进行500次调用..这是唯一可能的答案。当然它会变慢。
解决方案是以这种方式更改您的查询,它将使用WHERE IN函数。
查看here了解如何在您的情况下采用它。在这个用途中,你只会做1个查询而不是500个。看看它得到多快;-)