What are best practices for connecting to a MySQL database in PHP?

When connecting to a MySQL database in PHP, it is best practice to use the mysqli extension, as it provides improved security and functionality compared to the older mysql extension. It is also important to properly sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements can help improve performance and security by separating SQL logic from user input.

<?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";
?>