开发者

Changing character sets on a live MySQL database

开发者 https://www.devze.com 2022-12-20 18:37 出处:网络
I currently have a bunch of tables using the latin1 charset in a MySQL 5.1.x DB. Problem is,开发者_StackOverflow社区 we recently had a bunch of users trying to input text using UTF-8 encoding, and tha

I currently have a bunch of tables using the latin1 charset in a MySQL 5.1.x DB. Problem is,开发者_StackOverflow社区 we recently had a bunch of users trying to input text using UTF-8 encoding, and that seemed to break things.

Is it safe to blindly update the table's character set? What are some best practices (besides obviously backing everything up) for a situation like this?


I suggest to take a look at Converting Character Sets post on mysqlperformanceblog.


Here is a peace of PHP code that changes encoding on existing table:

<?php
    $table_name = 'some_table';
    $from = 'latin1';
    $to = 'utf8';

    $q = 'SELECT * FROM '.$table_name;
    //get data from mysql table
    $data = mysql::array_qw($q) or die('Cound not select: '.mysql_error());

    for ($i = 0; $i < count($data); $i++)
    {
        $q = 'UPDATE '.$table_name.' SET ';

        foreach($data[$i] as $key=>$value)
        {
            $q.= $key.' = '."'".iconv($from, $to, mysql_real_escape_string($value))."', ";
        }
        $q[strlen($q)-2] = ' ';

        $q.= $key = "WHERE id = ".$data[$i]['id'];
        mysql_query($q) or die(mysql_error());
    }
?>

It gets all the data, converts it, and then updates database table. (mysql::array_qw function converts mysql query result to array)

0

精彩评论

暂无评论...
验证码 换一张
取 消