What are the best practices for setting up MySQL connection to handle UTF-8 characters in PHP?

When setting up a MySQL connection in PHP to handle UTF-8 characters, it is important to ensure that the connection is configured to use UTF-8 encoding. This can be achieved by setting the character set to UTF-8 when establishing the connection. This will ensure that data is stored and retrieved correctly in UTF-8 format.

// Establish a MySQL connection with UTF-8 encoding
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Set UTF-8 encoding for the connection
$conn->set_charset("utf8");