How can SQL injection vulnerabilities be prevented in PHP code?

SQL injection vulnerabilities can be prevented in PHP code by using prepared statements and parameterized queries. This involves separating the SQL query from the user input, allowing the database to distinguish between code and data. By using prepared statements, input is treated as data rather than executable code, effectively preventing SQL injection attacks.

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

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

// Prepare a SQL query with a placeholder for user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the user input
$username = $_POST['username'];

// Execute the query
$stmt->execute();

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

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