How can PHP developers effectively retrieve a user's IP address and store it in a database?

To retrieve a user's IP address in PHP, you can use the $_SERVER['REMOTE_ADDR'] variable. Once you have the IP address, you can store it in a database by establishing a database connection, preparing an SQL query, and executing it to insert the IP address into a table.

// Retrieve user's IP address
$user_ip = $_SERVER['REMOTE_ADDR'];

// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Prepare and execute SQL query to insert IP address into a table
$sql = "INSERT INTO user_ips (ip_address) VALUES ('$user_ip')";
if ($conn->query($sql) === TRUE) {
    echo "IP address stored successfully";
} else {
    echo "Error storing IP address: " . $conn->error;
}

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