How can SQL Injections be prevented in PHP scripts?

SQL Injections in PHP scripts can be prevented by using prepared statements with parameterized queries. This technique ensures that user input is treated as data rather than executable code, thus preventing malicious SQL injection attacks.

// Establish a connection to the 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 value of the parameter and execute the query
$username = $_POST['username'];
$stmt->execute();

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

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