MySQL data contains special characters like š and ć, but they are displayed as '?' on the web page. Why?
I am trying to retrieve a row from the table which contains the value Boris Borenović
.
Boris Borenovi?
is returned.
Both my MySQL database and table have utf8_unicode_ci
collation set.
My PHP page, which displays data from the table, contains the following header: <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
. I tried with charset=utf-8
as well, but it still doesn't work.
The Sql command I am using to query data from the table is SELECT * FROM contact
, so nothing special there, just boring plain query. I tried with开发者_C百科 SELECT * FROM contact COLLATE Latin1_General_CI
but that query can't be executed.
How do I make it work? Thanks.
Here is the answer: can't insert russian text into mysql database You need to configure MySQL to allow utf-8
Have you set your connection collation? Try executing SET NAMES utf8
to set all collations to utf-8, then set your charset to utf-8 as well prior to executing the select statement.
<?php
$mysql_host = "localhost";
$mysql_db = "database";
$mysql_user = "username";
$mysql_pass = "password";
$mysql_character = "latin1";
$mysql_collate = "latin1_bin";
$db = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
if(!$db) echo "Cannot connect to the database!";
mysql_select_db($mysql_db);
mysql_query("ALTER DATABASE `".$mysql_db."` DEFAULT CHARACTER SET '".$mysql_character."' COLLATE '".$mysql_collate."'");
$query = mysql_query("SHOW TABLES");
while($row = mysql_fetch_array($query)) {
$table = $row[0];
mysql_query("ALTER TABLE `".$table."` DEFAULT CHARACTER SET '".$mysql_character."' COLLATE '".$mysql_collate."'");
$query2 = mysql_query("SHOW columns FROM `".$table."`");
while($row = mysql_fetch_array($query2)) {
$column = $row[0];
$type = $row[1];
$null = $row[2];
if($null == "YES") $null = "NULL";
if($null == "NO") $null = "NOT NULL";
mysql_query("ALTER TABLE `".$table."` CHANGE COLUMN `".$column."` `".$column."` ".$type." CHARACTER SET '".$mysql_character."' COLLATE '".$mysql_collate."' ".$null);
}
}
?>
Your database is perfectly fine. If you was seeing ?
inside the database itself, then it would have meant that the database table encoding is wrong.
Since you're seeing ?
in the HTTP response, then it means that PHP isn't been instructed to write characters as UTF-8 to the response. Check step 3 of this PHP UTF-8 cheatsheet.
If you're then seeing for example Å¡
instead of š
, then you need to execute mysql_set_charset
with utf8
prior to the SELECT
as well.
My way is:
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET NAMES 'UTF8'");
mysql_query("SET CHARACTER SET_CLIENT='UTF8'");
Put this code after you connect on database
(mysql_select_db($Database);)
精彩评论