更改活动MySQL数据库上的字符集 [英] Changing character sets on a live MySQL database

查看:134
本文介绍了更改活动MySQL数据库上的字符集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一堆表使用latin1字符集在MySQL 5.1.x数据库。问题是,我们最近有一大堆用户尝试使用UTF-8编码输入文本,这似乎打破了事情。

I currently have a bunch of tables using the latin1 charset in a MySQL 5.1.x DB. Problem is, 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?

推荐答案

这里是一个和平的PHP代码改变现有表上的编码:

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());
    }
?>

它获取所有数据,转换它,然后更新数据库表。 (mysql :: array_qw函数将mysql查询结果转换为数组)

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

这篇关于更改活动MySQL数据库上的字符集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆