Problems with charset, russian letters

2019-09-20 02:19发布

问题:

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.