What are the best practices for changing the character encoding of tables in a MySQL database to UTF-8?

When changing the character encoding of tables in a MySQL database to UTF-8, it is important to ensure that all data is properly converted to avoid any data loss or corruption. This can be done by altering the table's character set and collation to utf8_general_ci using SQL queries.

<?php

// Connect to the database
$host = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database';
$connection = new mysqli($host, $username, $password, $database);

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

// Change character encoding of tables to UTF-8
$tables = $connection->query("SHOW TABLES");
while ($table = $tables->fetch_assoc()) {
    $tableName = $table['Tables_in_' . $database];
    $connection->query("ALTER TABLE $tableName CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}

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

?>