How can one ensure the security of database connections in PHP scripts?

To ensure the security of database connections in PHP scripts, it is important to use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, one should avoid storing database credentials directly in the script and instead use environment variables or configuration files outside of the web root. It is also recommended to enable SSL encryption for database connections to protect data in transit.

<?php
// Database configuration
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create a secure database connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Use prepared statements with parameterized queries to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();

// Close connection
$conn->close();
?>