返回列表 回復 發帖

sql的編碼改成UTF-8轉碼

  1. <?php
  2. define('DB_NAME', 'putyourdbnamehere'); // 數據庫名稱
  3. define('DB_USER', 'usernamehere'); // MySQL用戶名
  4. define('DB_PASSWORD', 'yourpasswordhere'); // MYSQL密碼
  5. define('DB_HOST', 'localhost'); // 很大可能你需修改此

  6. function UTF8_DB_Converter_DoIt() {
  7. $tables = array();
  8. $tables_with_fields = array();

  9. // Since we cannot use the WordPress Database Abstraction Class (wp-db.php),
  10. // we have to make an a stand-alone/direct connection to the database.
  11. $link_id = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Error establishing a database connection');
  12. mysql_select_db(DB_NAME, $link_id);

  13. // Gathering information about tables and all the text/string fields that can be affected
  14. // during the conversion to UTF-8.
  15. $resource = mysql_query("SHOW TABLES", $link_id);
  16. while ( $result = mysql_fetch_row($resource) )
  17. $tables[] = $result[0];

  18. if ( !empty($tables) ) {
  19. foreach ( (array) $tables as $table ) {
  20. $resource = mysql_query("EXPLAIN $table", $link_id);
  21. while ( $result = mysql_fetch_assoc($resource) ) {
  22. if ( preg_match('/(char)|(text)|(enum)|(set)/', $result['Type']) )
  23. $tables_with_fields[$table][$result['Field']] = $result['Type'] . " " . ( "YES" == $result['Null'] ? "" : "NOT " ) . "NULL " . ( !is_null($result['Default']) ? "DEFAULT '". $result['Default'] ."'" : "" );
  24. }
  25. }

  26. // Change all text/string fields of the tables to their corresponding binary text/string representations.
  27. foreach ( (array) $tables as $table )
  28. mysql_query("ALTER TABLE $table CONVERT TO CHARACTER SET binary", $link_id);

  29. // Change database and tables to UTF-8 Character set.
  30. mysql_query("ALTER DATABASE " . DB_NAME . " CHARACTER SET utf8", $link_id);
  31. foreach ( (array) $tables as $table )
  32. mysql_query("ALTER TABLE $table CONVERT TO CHARACTER SET utf8", $link_id);

  33. // Return all binary text/string fields previously changed to their original representations.
  34. foreach ( (array) $tables_with_fields as $table => $fields ) {
  35. foreach ( (array) $fields as $field_type => $field_options ) {
  36. mysql_query("ALTER TABLE $table MODIFY $field_type $field_options", $link_id);
  37. }
  38. }

  39. // Optimize tables and finally close the mysql link.
  40. foreach ( (array) $tables as $table )
  41. mysql_query("OPTIMIZE TABLE $table", $link_id);
  42. mysql_close($link_id);
  43. } else {
  44. die('<strong>There are no tables?</strong>');
  45. }

  46. return true;
  47. }
  48. UTF8_DB_Converter_DoIt();
  49. ?>
複製代碼
返回列表 回復 發帖