How can PHP developers prevent SQL injection vulnerabilities when retrieving user data based on IDs from URLs?

To prevent SQL injection vulnerabilities when retrieving user data based on IDs from URLs, PHP developers should always sanitize and validate user input before using it in SQL queries. One way to achieve this is by using prepared statements with parameterized queries, which separate SQL logic from user input data, thus preventing malicious SQL injection attacks.

<?php
// Assuming $id is the user ID retrieved from the URL
$id = $_GET['id'];

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

// Prepare a SQL statement using a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

// Execute the statement
$stmt->execute();

// Fetch the result
$result = $stmt->get_result();

// Process the retrieved user data
while ($row = $result->fetch_assoc()) {
    // Process user data here
}

// Close the statement and the database connection
$stmt->close();
$conn->close();
?>