mysql中的字符集无效

时间:2013-11-23 13:07:42

标签: php mysql database pdo character-encoding

我正在使用mysql。当我做简单的查询SELECT * FROM table它返回РђР»РμРєСЃРμРμРІРёС‡。它应该显示俄语字母。我的数据库,表,列设置为utf8_general_ci。 php文件是utf8而不是bom。当我查询设置NAMES cp1251时,它解决了问题,但为什么有cp1251,如果所有内容都在utf 8中?

数据库连接

class Database { 

    public $user = 'root';
    public $password = '';

    function __construct() {
        $this->connect();
    }
    function connect() {
        try {
            $this->dbh = new PDO('mysql:host=localhost;dbname=university;charset=utf8', $this->user, $this->password);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
            }
    }

    function selectQuery( $sql ) {
        $this->stmt = $this->dbh->prepare($sql);
        $this->stmt->execute();
    }

    function insertQuery( $sql ) {
        $this->stmt = $this->dbh->prepare($sql);
        $this->stmt->execute();
    }
}

查询

$this->db = new Database();
$q = $this->db->selectQuery('SELECT * FROM students');
$data = $this->db->stmt->fetchAll($q);

1 个答案:

答案 0 :(得分:-1)

在连接后使用此查询设置归类手册。

$PDO = new PDO('mysql:host = localhost; dbname = dbname', $username, $pswd);
$PDO -> exec("SET SESSION collation_connection = 'utf8_persian_ci';");
$PDO -> exec("SET CHARACTER SET 'utf8';");
$PDO -> exec("set names utf8");

我为波斯语设置了这一行,你必须为你的语言设置第二行utf8_persian_ci ...
我和波斯人有同样的问题,这对我很有帮助,希望对你也有帮助......