如何记录特定用户执行的查询

时间:2019-03-18 19:03:17

标签: php mysql mysqli

我想保留已执行的MySQLI查询的表日志历史记录,并记录执行查询的特定用户以及执行查询的日期和时间- 在我的任何(所有)PHP页面上。

实现此目标的最佳方法和最简单的方法是什么?

PHP

session_start();


if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }

$connection = mysqli_connect("****", "****", "****", "****");
    if (!$connection) {
        die("Database connection failed: " . mysqli_connect_error());
    }

if(isset($_POST['update'])) {
    $accountNo = $_GET['ID'];
    $firstname = $_POST['firstname'];
    $surname = $_POST['surname'];
    $dob = $_POST['dob'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $town = $_POST['town'];
    $postcode = $_POST['postcode'];

SO用户的建议:

  

但是,这个建议有很多错误。

    $query = "UPDATE usertable set firstname = '".$firstname."', surname='".$surname."', dob='".$dob."', email='".$email."', phone='".$phone."', address='".$address."', town='".$town."', postcode='".$postcode."' where accountNo='".$accountNo."'";

    $log_action = mysqli_query($connection,$query);
$result = mysqli_query($connection,$query);

if($result) {

define("LOG_FILE", "https://www.*******.com/logfile.txt");
function log_action($action, $data) {
    $time = date('Y-m-d h:i:s');
    $user = isset($_SESSION['username']) ? $_SESSION['username'] : '';
    $message = "$time\tuser=$user\taction=$action\tdata=$data\n";
    file_put_contents(LOG_FILE, $message, FILE_APPEND);
}

1 个答案:

答案 0 :(得分:2)

写一个包装器库,记录您要记录的所有mysqli调用,例如

function my_mysqli_query($link, $query, $resultmode = MYSQLI_STORE_RESULT) {
    log_action('mysqli_query', $query);
    return mysqli_query($link, $query, $resultmode);
}
function my_mysqli_prepare($link, $query) {
    log_action('mysqli_prepare', $query);
    return mysqli_prepare($link, $query);
}
...
define("LOG_FILE", "/path/to/logfile.txt");
function log_action($action, $data) {
    $time = date('Y-m-d h:i:s');
    $user = isset($_SESSION['username']) ? $_SESSION['username'] : '';
    message = "$time\tuser=$user\taction=$action\tdata=$data\n";
    file_put_contents(LOG_FILE, $message, FILE_APPEND);
}

我已将其写入日志文件。您可以改为登录数据库表,它只是log_action()中的更多代码。

然后在所有其他脚本中进行全局替换,将mysqli_query替换为my_mysqli_query,将mysqli_prepare替换为my_mysqli_prepare,依此类推。因此您的代码如下所示:

if(isset($_POST['update'])) {
    $accountNo = $_GET['ID'];
    $firstname = $_POST['firstname'];
    $surname = $_POST['surname'];
    $dob = $_POST['dob'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $town = $_POST['town'];
    $postcode = $_POST['postcode'];

    $query = "UPDATE usertable set firstname = '".$firstname."', surname='".$surname."', dob='".$dob."', email='".$email."', phone='".$phone."', address='".$address."', town='".$town."', postcode='".$postcode."' where accountNo='".$accountNo."'";

    $result = my_mysqli_query($connection,$query);
    if ($result) {
        echo "Update successful";
    }
}