Non English characters appear as question marks on

2019-02-19 01:22发布

问题:

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');