How can SQL injection vulnerabilities be mitigated in PHP applications that interact with MySQL databases?

SQL injection vulnerabilities can be mitigated in PHP applications by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, the database engine can distinguish between code and data, making it more secure.

// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Bind parameters to the placeholders
$stmt->bind_param("s", $username);

// Set the parameter values
$username = $_POST['username'];

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

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

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