How can PHP developers ensure secure database connections in their scripts?

To ensure secure database connections in PHP scripts, developers should use parameterized queries or prepared statements to prevent SQL injection attacks. Additionally, they should avoid storing sensitive information such as database credentials directly in the script and instead utilize environment variables or configuration files for secure storage.

<?php
// Establishing a secure database connection using PDO
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>