How can PHP code be structured to handle user activity tracking and retrieval from a database in a scalable and efficient manner?
To handle user activity tracking and retrieval from a database in a scalable and efficient manner, you can create a separate table in the database to store user activity logs. Each log entry should contain relevant information such as user ID, timestamp, and activity details. When tracking user activity, insert a new entry into the activity log table. When retrieving user activity, query the activity log table based on user ID and any other relevant criteria.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Track user activity
$user_id = 123;
$activity = "Logged in";
$timestamp = date("Y-m-d H:i:s");
$sql = "INSERT INTO activity_log (user_id, activity, timestamp) VALUES ('$user_id', '$activity', '$timestamp')";
$conn->query($sql);
// Retrieve user activity
$user_id = 123;
$sql = "SELECT * FROM activity_log WHERE user_id = '$user_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "User ID: " . $row["user_id"]. " - Activity: " . $row["activity"]. " - Timestamp: " . $row["timestamp"]. "<br>";
}
} else {
echo "No activity found for this user.";
}
// Close the database connection
$conn->close();