How can the PHP code for connecting to a MySQL database be improved for better functionality and security?

Issue: The PHP code for connecting to a MySQL database is vulnerable to SQL injection attacks and lacks error handling. Solution: To improve functionality and security, we can use prepared statements to prevent SQL injection attacks and add error handling to catch any potential issues with the database connection.

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

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

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

echo "Connected successfully";

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