用php数组匹配行

时间:2014-07-25 13:21:38

标签: php mysql

我有一个包含列的表会话(namestartendkeyactive)。每隔5分钟,我执行一个PHP脚本,运行一个输出数组的命令行应用程序。

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

现在我想实现

1)将PHP数组namekey与数据库匹配。如果用户和密钥存在则不执行任何操作(会话处于活动状态)。如果数组项不在数据库中,请创建一个新行(新会话)

2)对于数据库中与php数组不匹配的每个会话结束当前时间并将active设置为0(会话关闭)

最好的方法是什么?

目前我有这段代码:

// 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));
        }
    }

这有效,但不确定这是非常有效的。

0 个答案:

没有答案