通常对数据的操作都需要记录日志,由于表结构的不同,每次都需要重新组织 SQL 语句则显得相当繁琐。写了几个函数来解决这个问题,不过有局限性:表的第一个字段必须为 id int identity。
// Sample // 生成日志表 createlogtable($table); // 生成记录操作日志的SQL语句 $logsql = genopelogsql($table, "id=$id", 'update'); // 将日志记录SQL拼接到原SQL $sql = $logsql.$sql; // 执行操作 $db->query($sql);
function genopelogsql($table, $cond, $opetype) { global $db, $tablepre, $username; $prefix = $tablepre; if (empty($prefix)) $prefix = 'ope'; $table_log = "{$table}_{$tablepre}log"; // 操作者、操作类型 $operator = "'".strtolower($opetype)."d by $username' AS operator"; // 通过 SELECT * 而无需指定字段名 $sql .= "INSERT INTO $table_log SELECT *, $operator, getdate() AS operatetime FROM $table".($cond ? " WHERE $cond" : NULL); return $sql.chr(13); } function createlogtable($table, $prefix = '') { global $db, $tablepre; $prefix = $tablepre; if (empty($prefix)) $prefix = 'ope'; // 日志表名 $table_log = "{$table}_{$prefix}log"; // 检查日志表是否存在 if (!($db->object_id($table_log))) { // 局限性:表的第一个字段必须为 id int identity $db->query("SELECT 1 as src_id, * INTO [dbo].$table_log FROM $table WHERE 1<>1 ALTER TABLE $table_log DROP COLUMN id ALTER TABLE $table_log ALTER COLUMN src_id INT NULL ALTER TABLE $table_log ADD {$prefix}operator VARCHAR(50) NULL ALTER TABLE $table_log ADD {$prefix}operatetime DATETIME NULL CONSTRAINT DF_{$table_log}_operatetime DEFAULT getdate() WITH VALUES"); } }