Is it possible to set the MySQL connection to UTF-8 encoding in PHP to avoid automatic encoding conversions?

When connecting to MySQL in PHP, it is important to set the connection encoding to UTF-8 to avoid automatic encoding conversions that may lead to data corruption or display issues. This can be achieved by executing a query to set the connection encoding to UTF-8 immediately after establishing the connection.

// Establish MySQL connection
$connection = new mysqli("localhost", "username", "password", "database");

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

// Set connection encoding to UTF-8
$connection->query("SET NAMES 'utf8'");
$connection->query("SET CHARACTER SET 'utf8'");