PDO and UTF-8 special characters in PHP / MySQL?

前端 未结 4 794
北海茫月
北海茫月 2020-12-11 15:58

I am using MySQL and PHP 5.3 and tried this code.

$dbhost = \'localhost\';
$dbuser = \'root\';
$dbpass = \'\';
$con = mysql_connect(\"localhost\", \"root\",          


        
4条回答
  •  伪装坚强ぢ
    2020-12-11 16:46

    You're missing an S: it's SET NAMES and not SET NAME:

    $this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
    

    You also need to un-comment it of course. Also, PDO::MYSQL_ATTR_INIT_COMMAND can not be set with PDO::setAttribute() after you've established your database connection (the constant name says it all), you've to specify it in the constructor using the $driver_options argument, like this:

    $this->db = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
    

    An alternative to this is to just execute that very same query immediately after connecting:

    $this->db = new PDO($this->dsn, $this->username, $this->password);
    $this->db->exec("SET NAMES 'utf8';");
    

提交回复
热议问题