dongmo9996 2014-07-25 13:21
浏览 12

用php数组匹配行

I have a table sessions with columns (name, start, end, key and active). Every 5 minutes I execute a PHP script running a commandline application which outputs an array.

array(
    [0]
        [name] => user1
        [key] => h2r92
        ....
        ....
    [1] ...
)

Now I would like to achieve

1) Match PHP array name and key with database. If the user and key exists do nothing (the session is alive). If an array item is not in the database, create a new row (new session)

2) For every session in the database that is not matched with the php array set end to current time and set active to 0 (session closed)

What is the best way to approach this?

Currently I have this code:

// get active sessions from db
    $db_sessions = array();
    $query = "SELECT * FROM lm_session WHERE feature_id = :fid AND active = 1";
    $stmt = $this->db->prepare($query);
    $stmt->execute(array(':fid' => $fid));
    while($row = $stmt->fetch(PDO::FETCH_ASSOC, PDO::CURSOR_SCROLL))
    {
        $db_sessions[$row['key']] = $row['user'];
    }

    // loop through current sessions
    if(is_array($data['session'])){

        // New and existing sessions
        foreach($data['session'] as $session) {

            if(isset($db_sessions[$session['key']]) && $db_sessions[$session['key']] == $session['user']) {
                unset($db_sessions[$session['key']]);
            } else {

                // session does not exist
                $query = "INSERT INTO lm_session (`feature_id`, `user`, `workstation`, `in`, `key`, `active`) VALUES (:fid, :user, :system, :in, :key, :active)";
                $stmt = $this->db->prepare($query);
                $stmt->execute(array(':fid' => $fid, ':user' => $session['user'], ':system' => $session['system'], ':in' => $session['time'], 'key' => $session['key'], 'active' => 1));    
            }
        }
        // closed sessions
        foreach($db_sessions as $key => $user)  {

            $query = "UPDATE lm_session SET active = 0 WHERE feature_id = :fid AND user = :user AND `key` = :key AND active = 1";
            $stmt = $this->db->prepare($query);
            $stmt->execute(array('fid' => $fid, ':user' => $user, ':key' => $key));
        }
    }

This works but not sure this is very efficient.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信会员卡接入微信支付商户号收款
    • ¥15 如何获取烟草零售终端数据
    • ¥15 数学建模招标中位数问题
    • ¥15 phython路径名过长报错 不知道什么问题
    • ¥15 深度学习中模型转换该怎么实现
    • ¥15 HLs设计手写数字识别程序编译通不过
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 TYPCE母转母,插入认方向
    • ¥15 如何用python向钉钉机器人发送可以放大的图片?