【发布时间】:2023-02-07 20:05:28
【问题描述】:
我正在开发一个用 PHP 编写的内部开发的应用程序。
我们有几个员工用户,可以进行数十种不同的更改,例如:添加新员工帐户、课程、学生、问题、测试等,以及修改或删除这些。
我的目标是编写一个函数来将某人所做的任何更改记录到 MySQL 表中。
我可以为每个请求一一完成。
因此,例如,用户可以发送请求将新员工帐户添加到数据库中。
if(isset($_REQUEST['newemployee'])){
$db = new db();
$insertrow = $db ->insertRow("INSERT INTO employees (firstname, lastname, email, role, color) VALUES (?, ?, ?, ?, ?)", array($_REQUEST['firstname'],$_REQUEST['lastname'],$_REQUEST['email'],$_REQUEST['role'],$_REQUEST['colorpicker1']));
}
我能做的是为任何个人请求写一个 if 语句。 例如。
// I already have a table named logs, its very dirty here but you get the idea, it does the job.
if(isset($_REQUEST['newemployee'])){
$done_by = $_SESSION['loguser']['id']; // this is how we track the user ids.
$action = 'created new employee account, email: '.$_REQUEST['email'];
$db = new db();
$insertrow = $db ->insertRow("INSERT INTO logs(user_id, action) VALUES (?, ?)", array($done_by, $action));
如果可能的话,我想尽可能地概括/自动化这个过程,以避免为每个可以触发的 REQUEST 编写几十个 if 语句。
我的想法是这样的:
if (ANY REQUEST is triggered){
# tell me what it is (e.g. 'newemployee')
# here I will insert the log in to the DB. The `action` field will not be very specific in this case, but I can live with that.
}
不过,我似乎不能只是一般地if REQUEST,这有可能吗?
【问题讨论】:
-
我不完全了解你的代码,但我相信如果 db() 是一个类,你将在其中获得 $_REQUEST 和 $_SESSION 值,所以如果我是正确的并且注意到这是一个完整的预感,你可以尝试添加它构造函数并在那里写你的日志代码,每次你初始化数据库时都会运行