How can PHP developers ensure that their code is secure when retrieving and displaying user data from a SQL database?

To ensure that PHP code is secure when retrieving and displaying user data from a SQL database, developers should use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, developers should validate and sanitize user input to prevent cross-site scripting (XSS) attacks. Finally, it's important to restrict database user permissions to only allow necessary actions to mitigate potential security risks.

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Retrieve user data securely
$user_id = $_GET['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

// Display user data
while ($row = $result->fetch_assoc()) {
    echo "Username: " . htmlspecialchars($row['username']) . "<br>";
    echo "Email: " . htmlspecialchars($row['email']) . "<br>";
}

// Close the connection
$stmt->close();
$conn->close();