Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

php - Problems with charset, russian letters

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...