How can SQL Injections be prevented in PHP when interacting with a database?

SQL Injections can be prevented in PHP by using prepared statements with parameterized queries. This method allows the database engine to distinguish between code and data, thus preventing malicious SQL injection attacks.

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

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

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

// Execute the statement with user input
$username = $_POST['username'];
$stmt->execute();

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

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