Problems with charset, russian letters

南楼画角 提交于 2019-12-25 18:41:53

问题


I have a problem with charset. When im inserting values to table in russian letters it appears like this - Р?ван.

This is my Database connection class.

class Database { 

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

    function __construct() {
        $this->connect();
    }
    function connect() {
        try {
            $this->dbh = new PDO('mysql:host=localhost;dbname=university', $this->user, $this->password,array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES CP1251'));
            $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();
    }
}

Yes i know, i dont have prepared statements there, ill do it after i fix the problem. As you see in db connection i wrote array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES CP1251'). It fixed the problem of displaying values from db(it was displayed same way). My sql is something like this :

$q = $this->db->insertQuery("INSERT INTO students (id,first_name,second_name,last_name,course) VALUES ('','Иван','Иванян','Иванович','1')");

In table its displayed like this - Р?ванян My all files are set UTF 8 without BOM. whats wrong here?

EDIT: Also all rows in tables are in utf8_general_ci


回答1:


Your database class makes no sense because you aren't using prepared statements properly. And even don't return anything from select query. And such a class makes very little sense overall.

Р?ван. is utf-8 encoded text shown as single-byte encoding. So, you have to add

header('Content-Type: text/html; charset=utf-8');

to your PHP files.



来源:https://stackoverflow.com/questions/20161978/problems-with-charset-russian-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!