maybe_convert_table_to_utf8mb4

If a table only contains utf8 or utf8mb4 columns, convert it to utf8mb4.

Description

maybe_convert_table_to_utf8mb4( (string) $table ); 

Parameters (1)

0. $table (string)
The table to convert.

Usage

  1. if ( !function_exists( 'maybe_convert_table_to_utf8mb4' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/upgrade.php'; 
  3.  
  4. // The table to convert. 
  5. $table = ''; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = maybe_convert_table_to_utf8mb4($table); 
  9.  

Defined (1)

The function is defined in the following location(s).

/wp-admin/includes/upgrade.php  
  1. function maybe_convert_table_to_utf8mb4( $table ) { 
  2. global $wpdb; 
  3.  
  4. $results = $wpdb->get_results( "SHOW FULL COLUMNS FROM `$table`" ); 
  5. if ( ! $results ) { 
  6. return false; 
  7.  
  8. foreach ( $results as $column ) { 
  9. if ( $column->Collation ) { 
  10. list( $charset ) = explode( '_', $column->Collation ); 
  11. $charset = strtolower( $charset ); 
  12. if ( 'utf8' !== $charset && 'utf8mb4' !== $charset ) { 
  13. // Don't upgrade tables that have non-utf8 columns. 
  14. return false; 
  15.  
  16. $table_details = $wpdb->get_row( "SHOW TABLE STATUS LIKE '$table'" ); 
  17. if ( ! $table_details ) { 
  18. return false; 
  19.  
  20. list( $table_charset ) = explode( '_', $table_details->Collation ); 
  21. $table_charset = strtolower( $table_charset ); 
  22. if ( 'utf8mb4' === $table_charset ) { 
  23. return true; 
  24.  
  25. return $wpdb->query( "ALTER TABLE $table CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );