How can the use of timestamps in PHP and MySQL optimize the process of recording user visits and preventing duplicate entries?

To optimize the process of recording user visits and prevent duplicate entries, we can use timestamps in PHP and MySQL. By storing the timestamp of each visit in the database and checking for existing entries within a certain time frame, we can effectively prevent duplicates.

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Get current timestamp
$current_timestamp = time();

// Check if there is an entry within the last hour
$query = "SELECT * FROM visits WHERE timestamp >= NOW() - INTERVAL 1 HOUR";
$result = $mysqli->query($query);

if($result->num_rows == 0) {
    // Insert new visit record
    $insert_query = "INSERT INTO visits (timestamp) VALUES ('$current_timestamp')";
    $mysqli->query($insert_query);
}

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