2

Hello so I have a logs table in my database and in every user action like log in, log out, edit, delete, create, I want it to be logged. Here is my current code in every action:

    $action = "Log in"; //if user log in
    $query = "INSERT INTO tbllogs 
            (logorigin, 
             logaction, 
             loguser, 
             logdate, 
             logoutcome) 
              VALUES
            (:origin, 
             :action, 
             :user, 
             :dt, 
             :outcome)";

              $stmt = $dbc->prepare($query);
              $stmt->bindParam(':origin', $ip);
              $stmt->bindParam(':action', $action);
              $stmt->bindParam(':user', $_SESSION['id']);
              $stmt->bindParam(':dt', $dateTime);
              $stmt->bindParam(':outcome', $outcome);
              $stmt->execute();

What I wanted to do is instead of repeating this code in every user action, I want to create a function that will do like this. But my problem is, I am using different values in my $action variable like for example if the user will log in, $action = "Log in", if the user logs out, $action = "Log out". How can I accomplish that? Thank you!

wobsoriano
  • 12,348
  • 24
  • 92
  • 162

2 Answers2

2

You can do something like this below :

function logData($action, $values_to_be_saved) {

    if ($action == 'Log in') {
        //Query to save values
    }
}

You can call it like :

$action = 'Log in'; // Any action you want to call
$values_to_be_saved // Array containing values to be saved like origin, action, user, dt, outcome
logData($action, $values_to_be_saved);

Or you can use a switch case for this.

Praveen Dabral
  • 2,449
  • 4
  • 32
  • 46
1

Make the following function in a file and include it on every page where you want to Log the activity. And then call the function with variable as follows:

logging('Log In',$ip,$outcome);

function logging($action=null,$ip,$outcome){
    $query = "INSERT INTO tbllogs (logOrigin, logAction, logUser, logDate, logOutcome) VALUES (:origin, :action, :user, :dt, :outcome)";
              $stmt = $dbc->prepare($query);
              $stmt->bindParam(':origin', $ip);
              $stmt->bindParam(':action', $action);
              $stmt->bindParam(':user', $_SESSION['id']);
              $stmt->bindParam(':dt', $dateTime);
              $stmt->bindParam(':outcome', $outcome);
              $stmt->execute();
}

Hope it helps.

عثمان غني
  • 2,786
  • 4
  • 52
  • 79