无法在MySQL中存储UTF8字符 [英] Cannot store UTF8 characters in MySQL

查看:99
本文介绍了无法在MySQL中存储UTF8字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到我无法在MySQL数据库中存储ţ,î,ş等字符的原因.

Cannot find the reason why I am unable to store in a MySQL database characters like ţ, î, ş.

我的表定义是:

CREATE TABLE IF NOT EXISTS `gen_admin_words_translated` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `word_id` int(10) NOT NULL,
  `value` text COLLATE utf8_unicode_ci,
  `lang_id` int(2) NOT NULL,
  `needUpd` int(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2689 ;

使用以下脚本完成与数据库的连接:

The connection to the database is done with the following script:

$charset = "UTF8";
$link = mysql_connect($host, $user, $pass);
if(!$link){
    die("Unable to connect to database server.");
}
mysql_selectdb($database);
if(function_exists("mysql_set_charset")){
    mysql_set_charset($charset, $link);
}else{
    mysql_query("SET NAMES $charset");   
}

我在页面顶部:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

,脚本为:

$text = 'ţ, î, ş';
mysql_query("insert into gen_admin_words_translated (word_id, lang_id, value, needUpd) values (1, 1, '$text', 1)");

我最终在表中得到的是:

All I get in the end in the table is:

SELECT * FROM  `gen_admin_words_translated` 

id   word_id value lang_id needUpd
5166 1034    ?,    1       1

推荐答案

将我的评论扩展为答案:

Expanding my comments into an answer:

似乎您已正确设置了所有内容,并且只限于在数据库中插入字符串文字.要成功完成此操作,您还必须确保所保存的PHP脚本的文本编码也为UTF-8 .

It seems that you have set up things correctly, and are only stuck on inserting a string literal to the database. To do that successfully you must also ensure that your text encoding for the saved PHP script is also UTF-8.

大多数体面的编辑器都会让您知道您当前正在使用哪种编码,并且还可以另存为(即,在不同的编码之间进行转换)(即使今天记事本也可以这样做).但是,作为快速检查,您可以将字符添加到文件中的某个位置并保存.如果文件大小更改为1或2个字节而不是3个字节,则说明您不在UTF-8上,需要将文件转换为该编码.

Most decent editors will let you know which encoding you are currently working with and can also save as (i.e. convert between) different encodings (even Notepad does this today). However, as a quick check you can add the character to your file somewhere and save it. If the file size changes by 1 or 2 bytes instead of 3, you are not on UTF-8 and you need to convert the file to that encoding.

除此之外,当从浏览器接收文本作为输入时,您的代码应该可以很好地处理它.

Other than that, when receiving text as input from the browser your code should handle it just fine.

注意:尽管使用<meta>标记来设置页面的编码应该足够了,但是最好使用来自PHP的HTTP标头来做到这一点,如下所示:

Note: While using a <meta> tag to set the encoding for your page should be sufficient, it's better if you do this with an HTTP header from PHP like this:

header('Content-type: text/html; charset=utf-8');

这篇关于无法在MySQL中存储UTF8字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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