UTF8文字显示????从db查询时

时间:2012-10-05 17:39:17

标签: php javascript mysql sql json

当我输入此代码并从数据库中调用它时,它将文本显示为问号而不是字母,这些是阿拉伯字母,因此UTF8应该可以工作,但我不知道whit现在不会。

<?php
header("Content-Type: application/json; charset=UTF-8");

$server   = "";
$username = "";
$password = "";
$database = "";

$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

$sql = "SELECT * FROM events WHERE id='1' ";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)) {
    $records[] = $row;
}

mysql_close($con);

print_r($records);

?>

它显示为结果

Array
(
    [0] => Array
        (
            [id] => 1
            [event] => ????? ?????
            [speaker] => ???? ???????
            [area] => ???????
            [place] => ???? ??????
            [addr] => ??? ???? ????????
            [datefrom] => 2012-10-05
            [dateto] => 
            [timefrom] => 19:26:27
            [timeto] => 
        )

)

3 个答案:

答案 0 :(得分:0)

检查您的数据库是否也使用UTF-8:

SHOW CREATE DATABASE `your_db_name`

您是如何插入数据的?

并验证您的Web服务器配置正确(使用UTF8)。

答案 1 :(得分:0)

您需要在存储utf8的列上设置utf8排序规则:

rowname varchar(100) COLLATE utf8_unicode_ci NOT NULL,

......而且连接也很重要(参见Roger Ng的回答)

答案 2 :(得分:-1)

以下是将客户端和数据库之间的连接设置为UTF-8

的代码
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER_SET_CLIENT=utf8');
mysql_query('SET CHARACTER_SET_RESULTS=utf8');

$sql = "SELECT * FROM events WHERE id='1' ";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());

在开始SQL语句之前输入这些代码。