Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Change the default setting of the database
- $dbname = 'your_database_name_here';
- $host = 'database_host_here';
- $user = 'database_user_here';
- $password = 'database_password_here';
- $options = array(
- PDO::ATTR_PERSISTENT => true,
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_ORACLE_NULLS => PDO::NULL_TO_STRING
- );
- $dsn = 'mysql:host=' . $host . ';dbname=' . $dbname . ";charset=utf8";
- $dbh = new PDO($dsn, $user, $password, $options);
- // Change the default character set of the database (that does not change any data actually, it's just in case you will create new tables or fields in the future)
- $sql = "ALTER SCHEMA $dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
- echo "$sql<br>";
- $stmt = $dbh->prepare($sql);
- $stmt->execute();
- // Get all the fields of all your tables in your database and save the data in an array
- $sql = "SELECT column_name, data_type, column_type, table_name, collation_name, character_set_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = '$dbname' order by table_name";
- echo "$sql<br>";
- $stmt = $dbh->prepare($sql);
- $fieldarray = $stmt->fetchAll(PDO::FETCH_ASSOC);
- $table_name_before = "";
- // Now loop through every field of your database
- foreach ($fieldarray as $field) {
- $collation_name = $field["collation_name"];
- $table_name = $field["table_name"];
- $character_set_name = $field["character_set_name"];
- $column_name = $field["column_name"];
- $column_type = $field["column_type"];
- // For every new table change the default character set of the table (again, this does NOT change any existing data, it is just the default values in case you add new fields later without specifying the character set)
- if ($table_name != $table_name_before) {
- $sql = "ALTER TABLE $table_name CHARACTER SET utf8 COLLATE utf8_unicode_ci";
- echo "$sql<br>";
- $stmt = $dbh->prepare($sql);
- $stmt->execute();
- }
- // If the collation name or the character set of the field is in latin1, change it to utf8. This ACTUALLY converts the data in the field.
- // You might need to change the collation_name and character_set_name variables in case you have other data in your DB than latin1 and latin1_swedish_ci
- if ($collation_name == 'latin1_swedish_ci' OR $character_set_name == 'latin1') {
- $sql = "ALTER TABLE $table_name CHANGE $column_name $column_name $column_type CHARACTER SET utf8 COLLATE utf8_unicode_ci";
- echo "$sql<br>";
- $stmt = $dbh->prepare($sql);
- $stmt->execute();
- }
- $table_name_before = $table_name;
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement