dronthpi05943 2017-09-21 19:16
浏览 23
已采纳

PHP运行一次查询

This may sound silly but i am trying to figure out the best approach to run a query only once in a stats table that have all values set to 0 as a starting point and i would like your opinion, my table is by example:

Col1 - Col2 - Col3 - Col4 - Created - Modified
0      0      0      0      Datetime- Datetime

My main script have several foreach loops where i evaluate some conditions, if there is a match, i build the query and run a mysqli multiquery at the end, by example (pseudo code):

$query = '';
foreach ($array as $val) {
  if ($val == $mycondition) {
    $query .= "UPDATE mytable SET Col1 = Col1 + 1;";   
  }
}

$db = mysqliConnection();
$num = $db->query("SELECT * FROM my table WHERE id = '".$ID."' AND Col1 = 0 AND Col2 = 0 AND Col3 = 0 AND Col4 = 0");

$result = mysqli_num_rows($num);
// if 0 it means that nothing has been modified yet so i can run the query
if ($result > 0) {
  $db->multi_query($query)
}
$db->close();

This is the best approach i can think of right now, i created the columns created and modified but i think they will not work for this, as the creation time will always be before the modified time, probably in milisecs (but i dont want to risk taking the path to allow the mutiquery run after max 3 sec or so, cause if the user run the page several time by mistake between 3 secs it will store wrong values) and the modified column will change as soon as the first value is updated making the next queries fail if i rely on that column as condition in the WHERE clause (even if are just milisec).

What do you think guys is the best approach or i am in the right path?

Best Regards

展开全部

  • 写回答

1条回答 默认 最新

  • drq231358 2017-09-21 22:57
    关注

    I would suggest to use a flag. Something like:

    $queryFlag = 0;
    
    if($queryFlag == 0) {
         //Do you things here
         $queryFlag = 1;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部