Make PDO connection utf8 encoded

2019-08-20 16:53发布

问题:

I am trying to encode my connection to become UTF8. I was looking at some other posts, but soe some reason it doesnt work. No idea what I am doing wrong.

This is how my conn looks

 $this->db_conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);

And this is what I am trying to do, but it says that is not correct

 $this->db_conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password.";charset=utf8");

Gives this error Database Connection Error: SQLSTATE[28000] [1045] Access denied for

I am using MySql

回答1:

Move your charset before the user and password.

$this->db_conn = new PDO("mysql:host=" .
     $this->host .
     ";dbname="  . $this->db_name .
     ";charset=utf8" ,
     $this->username,
     $this->password);


回答2:

It needs to be part of the first argument. Your second version should look like this:

$this->db_conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name.";charset=utf8", $this->username, $this->password);

The error you're getting is because your password is wrong (you're appending ";charset=utf8" to the password, and your password likely does not end with that).