How can the security of PHP scripts be improved when interacting with databases?

To improve the security of PHP scripts when interacting with databases, it is crucial to use prepared statements with parameterized queries to prevent SQL injection attacks. This method helps sanitize user input and ensures that malicious SQL queries cannot be executed.

// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with parameters
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');

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

// Fetch results
$results = $stmt->fetchAll();