How can SQL Injections be prevented in PHP code that interacts with a MySQL database?

SQL Injections can be prevented in PHP code by using prepared statements and parameterized queries. This approach separates SQL code from user input, making it impossible for malicious input to alter the SQL query structure.

// 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 = ?");
$stmt->bind_param("s", $username);

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

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

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