What are the advantages of using a database instead of a log file for storing visitor data in PHP?

When storing visitor data in PHP, using a database instead of a log file offers several advantages. Databases provide better organization and structure for the data, making it easier to query and retrieve specific information. Additionally, databases offer more flexibility in terms of data manipulation and scalability. They also provide better security features for protecting sensitive visitor information.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "visitor_data";

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

// Insert visitor data into the database
$visitor_ip = $_SERVER['REMOTE_ADDR'];
$visit_time = date('Y-m-d H:i:s');

$sql = "INSERT INTO visitors (ip_address, visit_time) VALUES ('$visitor_ip', '$visit_time')";

if ($conn->query($sql) === TRUE) {
    echo "Visitor data inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();