Are there best practices for updating and managing database entries related to user activity in PHP?

When updating and managing database entries related to user activity in PHP, it is important to follow best practices to ensure data integrity and security. One common approach is to use prepared statements to prevent SQL injection attacks and sanitize user input before updating the database. Additionally, logging user activity can help track changes and troubleshoot any issues that may arise.

// Sample code for updating and managing database entries related to user activity in PHP

// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Update user activity in the database
$user_id = $_SESSION['user_id']; // Assuming user ID is stored in a session variable
$activity = "Logged in"; // Example user activity
$timestamp = date("Y-m-d H:i:s");

$stmt = $conn->prepare("INSERT INTO user_activity (user_id, activity, timestamp) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $activity, $timestamp);

if ($stmt->execute()) {
    echo "User activity updated successfully";
} else {
    echo "Error updating user activity: " . $conn->error;
}

// Close database connection
$conn->close();