How can PHP developers transition from using a text file to a database for storing IP lockout data, and what are the benefits of this change?

To transition from using a text file to a database for storing IP lockout data, PHP developers can create a database table to store the IP addresses and lockout information. This change allows for easier management, querying, and updating of IP lockout data. By utilizing a database, developers can also implement more advanced features such as automatic expiration of lockouts and better scalability for handling a larger number of IP addresses.

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

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

// Create a table to store IP lockout data
$sql = "CREATE TABLE ip_lockouts (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    ip_address VARCHAR(15) NOT NULL,
    lockout_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {
    echo "Table ip_lockouts created successfully";
} else {
    echo "Error creating table: " . $conn->error;
}

// Insert a new IP address into the database
$ip_address = "192.168.1.1";
$sql = "INSERT INTO ip_lockouts (ip_address) VALUES ('$ip_address')";

if ($conn->query($sql) === TRUE) {
    echo "New IP address inserted successfully";
} else {
    echo "Error inserting IP address: " . $conn->error;
}

// Retrieve all IP addresses from the database
$sql = "SELECT ip_address FROM ip_lockouts";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "IP Address: " . $row["ip_address"] . "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();