简体   繁体   中英

How to make a log while insert , update, delete a record into DataBase Tables in MYSQL Using PHP

I want to make a log details for my database while a record insert into any table and update any table and delete any record from an table in MYSQL - PHP. Please give me some ideas.

You've used laravel tag, so I assume you want to find a 'Laravel way' to do it.

The best practice is to use Eloquent Events .

Each time when Laravel will hit the DB, it will try to run some of these events: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored

-ing events are used before hitting DB, -ed events are used right after hitting DB.

Example:

public function boot()
{
    User::created(function () {
        Log::info('User was just created successfully');
    });
}

One solution is writing a helper function that logs successful insert/update sql queries if you have full control over your PHP application. A helper function can be called on every instance of insert/update queries which logs the features of the sql query you have. Some features for example can be the table name, the record id, and the type of operation ie insert or update, along with the system date.

In the module I have developed and have the link for below, these features are extracted from the original sql query automatically. This is one solution to the logging problem.

Here is my working solution. See the repository's Readme file to see how to add the module to your PHP application

Here is how it works:

  1. We pass our original sql query to a function in the logging module;
  2. The function will extract sql features from the query;
  3. It will save all features to the log table we have setup in the database, along side system date and IP (Other features can be extracted also);

To see the logged data (as an interface to what we have logged):

  1. We call the main function in the front-end side of the module;
  2. This main function will get as parameter the number of most recent log records it should return;
  3. It will present the log records neatly, for example it will collect repeat number of operations on same record in to one entry. The CSS styling can be adjusted as needed.
  4. The whole interface can be minimized or restored using a show/hide button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM