What are some tips for improving the security and efficiency of PHP scripts that interact with databases?

Issue: To improve the security and efficiency of PHP scripts that interact with databases, it is important to use prepared statements to prevent SQL injection attacks and to properly sanitize input data. Code snippet:

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

// Prepare a SQL statement using a prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind parameters and execute the statement
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Sanitize output data before using it
foreach ($results as $row) {
    echo htmlspecialchars($row['username']);
}