What is the recommended field type for storing timestamps in MySQL for tracking user online status?
When tracking user online status in MySQL, the recommended field type for storing timestamps is the DATETIME data type. This allows for easy manipulation and comparison of dates and times in MySQL queries. By using DATETIME, you can accurately track when a user was last online and easily determine their current online status based on the timestamp stored in the database.
// Create a DATETIME field in MySQL table to store user online status
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
last_online DATETIME
)";
// Connect to MySQL database and execute the SQL query
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn->query($sql) === TRUE) {
echo "Table users created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();