|
因为要搞多语言版的项目,数据库是Mysql-4.1.9,使用PHP来操作Mysql,为了能使用utf8,今天搞了一天,终于搞定,期间也参考了好多资料,似乎都有问题,也许是没有找到真正的有用的资料,后来经过自己的“小聪明”,终于搞定!
注意:mysql 3.X的版本不支持utf8!
下面分别从mysql的安装,建数据库,建表以及PHP的连接来介绍!
1.安装mysql
很简单,我现在已经做好了yum升级
yum -y Mysql-server就OK了
2.创建数据库
进入mysql
mysql> create database bixuan character set utf8;
Query OK, 1 row affected (0.01 sec)
# 这里是创建了一个bixuan的数据库,其编码用:utf8
mysql>
# 下面是创建表,SQL语句如下
[code:1]CREATE TABLE `type` (
`id` int(10) unsigned NOT NULL auto_increment,
`flag_deleted` enum('Y','N') character set utf8 NOT NULL default 'N',
`flag_type` int(5) NOT NULL default '0',
`type_name` varchar(50) character set utf8 NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;[/code:1]
这样,数据库:bixuan和表type以及type表里的字段flag_deleted和type_name都支持了utf8!
如果修改数据库成utf8的:
mysql> alter database bixuan character set utf8;
修改表默认用utf8:
mysql> alter table type character set utf8;
修改字段用utf8:
mysql> alter table type modify type_name varchar(50) CHARACTER SET utf8;
3.用PHP来连接MYSQL
写PHP的程序的时候要注意几个地方:
·在每次连接数据库后和在执行mysql_query()操作之前,请先执行下面的语句:
[code:1]mysql_query("SET NAMES 'utf8'");[/code:1]
这个是表示用户执行查询语句的时候用utf8编码!insert,update操作似乎不需要!(没测试)
·在网页输入用utf-8编码:
[code:1]@header("Content-Type: text/html; charset=utf-8");[/code:1]
·你所写的这个.php程序请以utf8编码存储!
下面是我写的例子:
[code:1]<?
import_request_variables('pgc','');
@$con= mysql_connect("localhost","test","test") or die ("can't connect the db.");
mysql_select_db("bixuan");
@header("Content-Type: text/html; charset=utf-8");
mysql_query("SET NAMES 'utf8'");
if($add == "add"){
//mysql_query("SET CHARACTER SET utf8");
echo $type_name."<br>";
//$ss = "insert into type (type_name) values ('$type_name')";
$ss = "update type set type_name='$type_name' where id='1'";
echo $ss."<br>";
mysql_query($ss);
echo "add succesful.";
}
$sql = " select * from type";
$re = mysql_query($sql);
while($row = mysql_fetch_array($re)){
echo $row[type_name]."<br>";
}
?>
<FORM METHOD=POST ACTION="utf8.php" method="post">
type_name:<INPUT TYPE="text" NAME="type_name" value="<?echo $type_name?>"><BR>
<INPUT TYPE="submit" NAME="submit" value="submit"><INPUT TYPE="hidden" NAME="add" value="add">
</FORM>[/code:1]
如果有问题,请跟帖,谢谢!同时也期待您的指教!
本文地址:http://www1.ourlinux.net/bbs/showforum.php?showtopic=294 如果转载请注名:碧轩居/bixuan - http://www.ourlinux.net |
|