How can PHP scripts be secured against SQL injection attacks when incorporating user input for database queries?

To secure PHP scripts against SQL injection attacks when using user input for database queries, it is essential to use prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable SQL code, thus preventing malicious SQL injection attacks.

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

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

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

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

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

// Process the results as needed

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