How can PHP interact with MySQL to store and retrieve button states for a time tracking application?

To store and retrieve button states for a time tracking application, PHP can interact with MySQL by creating a database table to store the button states along with timestamps. The PHP script can then use SQL queries to insert and update button states in the database, as well as retrieve the latest button states based on timestamps.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "time_tracking";

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

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

// Insert button state into database
$button_state = $_POST['button_state'];
$sql = "INSERT INTO button_states (state) VALUES ('$button_state')";
$conn->query($sql);

// Retrieve latest button state from database
$sql = "SELECT state FROM button_states ORDER BY timestamp DESC LIMIT 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $latest_button_state = $row['state'];
    }
} else {
    echo "No button states found";
}

$conn->close();
?>