Script php para cambiar todos los campos de utf8mb3 a utf8mb4, en maysql8

<?php

// Conexión a la base de datos
$dbhost = "localhost";
$dbuser = "usuario";
$dbpass = "contraseña";
$dbname = "nombre_de_la_base_de_datos";

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

// Verifica la conexión
if (!$conn) {
    die("Error de conexión: " . mysqli_connect_error());
}

mysqli_query($conn, "ALTER DATABASE $dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

$tables = mysqli_query($conn, "SHOW TABLES");

// Recorre todas las tablas y cambia el conjunto de caracteres a utf8mb4
while ($table = mysqli_fetch_array($tables)) {
    $table_name = $table[0];
    mysqli_query($conn, "ALTER TABLE $table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

    $columns = mysqli_query($conn, "SHOW FULL COLUMNS FROM $table_name");
    while ($column = mysqli_fetch_array($columns)) {
        $column_name = $column['Field'];
        $column_type = $column['Type'];

        if (strpos($column_type, 'varchar') !== false ||
            strpos($column_type, 'text') !== false ||
            strpos($column_type, 'tinytext') !== false ||
            strpos($column_type, 'mediumtext') !== false ||
            strpos($column_type, 'longtext') !== false ||
            strpos($column_type, 'char') !== false) {
            mysqli_query($conn, "ALTER TABLE $table_name MODIFY $column_name $column_type CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
        }
    }
}

mysqli_close($conn);

Leave a Reply

Your email address will not be published. Required fields are marked *