How can SQL injection vulnerabilities be mitigated in PHP code that interacts with a MySQL database?

SQL injection vulnerabilities can be mitigated in PHP code that interacts with a MySQL database by using prepared statements with parameterized queries. This approach allows the database to distinguish between SQL code and data input, preventing malicious SQL injection attacks.

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

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

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

// Set the parameter values and execute the query
$username = $_POST['username'];
$stmt->execute();

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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