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

SQL injection vulnerabilities can be addressed in PHP code that interacts with a MySQL database by using prepared statements with parameterized queries. This method allows the database to distinguish between code and data, preventing malicious SQL commands from being executed. By binding parameters to placeholders in the query, the input data is treated as data rather than executable code.

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

// Prepare a SQL statement with placeholders for parameters
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");

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

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

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

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

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

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