I have a MySQL database table populated with non English data. When I view the data in Navicat MySQL browser the data appears fine. However when I run a php script to select and display the data on a web page it displays question marks instead. The page encoding is set to utf8 and even the MySQL collation is set to utf8 - something gets wrong in selecting and displaying... please help.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
MySQL connection settings could be at fault here. Run this MySQL command when you connect to the database from PHP, before you run any other SQL commands:
SET names 'utf8';
This should set the connection's encoding to UTF-8. As you're saying, the page and the database is already in UTF-8 (that should also mean the page sends Content-Type: text/html; charset=utf-8
); the connection itself can accidentaly have a different encoding by default :(
回答2:
In addition, in HTML, inside we must write:
<meta charset="utf-8">
When we create a MySQL database, we must use something like this:
CREATE DATABASE `base` DEFAULT CHARACTER SET=utf8;
When we create tables, use:
CREATE TABLE `base`.`table` (
`key` int(5) unsigned NOT NULL,
`name` varchar(100),
...
PRIMARY KEY (`key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
In PHP code, after mysql_connect() and mysql_select_db(), use:
mysql_query('SET NAMES UTF8');