php records which fields have been modified in the database change log

Sometimes it is very useful for background management, especially personnel management to record the user's behavior log. The log can be used to trace something operated by someone. However, it's not easy to modify a field for a table, so I come up with a way. Here's how to do it.

I. need to create a data first

CREATE TABLE `hanchao_change_log` (
  `id` int(10) NOT NULL COMMENT '' AUTO_INCREMENT PRIMARY KEY,
  `model` varchar(50) NOT NULL COMMENT 'Table of triggering behaviors',
  `user_id` int(10) NOT NULL DEFAULT '0' COMMENT 'Executive user id',
  `record_id` int(10) NOT NULL DEFAULT '0' COMMENT 'Data that triggers the behavior id',
  `action` varchar(50) NOT NULL COMMENT 'add/edit/del',
  `action_ip` int(10) NOT NULL DEFAULT '0' COMMENT 'Implementing actors ip',
  `create_time` int(10) NOT NULL DEFAULT '0' COMMENT 'Time of execution',
  `remark` text NOT NULL COMMENT 'Log remarks'
) COMMENT='Data change log' ENGINE='InnoDB' COLLATE 'utf8_general_ci';

The function of writing a record

/**
  * Log database
  * @param string $action Behavior identification
  * @param string $model Model name of triggering behavior
  * @param int $record_id Record id of triggering behavior
  * @param int $user_id User id of the execution behavior
  * @param int $mark Custom notes
  * @return boolean
  */
function change_log($action = null, $model = null, $record_id = null, $user_id = null,$mark=null){
    if(empty($action) || empty($model) || empty($record_id)){return 'Parameter cannot be empty';}
    if(empty($user_id)){$user_id = is_login();}
    if($action=='edit' && $mark && is_array($mark) && $mark['oldparam']){
        $oldparam=json_decode(htmlspecialchars_decode($mark['oldparam']),1);unset($mark['oldparam']);
        $edit=array();
        foreach($mark as $k=>$v){if(isset($oldparam[$k]) && $v!=$oldparam[$k]){$edit[$k]=$v;}}
        if($edit){$mark="Modify content:\n";foreach($edit as $k=>$v){$mark.=$k.":".(is_array($v)?serialize($v):$v)."\n";}}
    }
    //Insert behavior log
    $data=array();
    $data['action']         =   $action;
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   get_client_ip(1);
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   NOW_TIME;    
    if(!empty($mark))$data['remark']=$mark; 
    M('ChangeLog')->add($data);
}

3. Add hidden fields to the template to record the old values of all fields (no need to edit records with notes, add and delete, etc.)

<input type="hidden" name="oldparam"  value='{:json_encode($info)}'/>

4. Add call function in corresponding method

change_log('add',CONTROLLER_NAME,$id,'','Add merchandise');
change_log('edit',CONTROLLER_NAME,$id,'',$postdata);
change_log('del',CONTROLLER_NAME,$id,'','Delete merchandise');

Settle

Keywords: Programming Database

Added by beaudoin on Thu, 31 Oct 2019 15:40:46 +0200