How can the risk of SQL injection be mitigated in PHP code like the example provided?

To mitigate the risk of SQL injection in PHP code, it is essential to use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate the SQL logic from the data input, preventing malicious SQL injection attacks.

// Using prepared statements to mitigate SQL injection risk
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();

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

// Fetch data from the result set
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close the statement and connection
$stmt->close();
$mysqli->close();