数据库
首页 > 数据库> > PHP / MySQL中的PDO和UTF-8特殊字符?

PHP / MySQL中的PDO和UTF-8特殊字符?

作者:互联网

我正在使用MySQLPHP 5.3并尝试此代码.

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$con = mysql_connect("localhost", "root", "");
mysql_set_charset('utf8');
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("kdict", $con);
$sql = "SELECT * FROM `en-kh` where english='a'";
echo $sql;
$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
{
  echo $row['english'] . " </br> " . $row['khmer'];
  echo "<br />";
}
?>

=&GT我有很好的UTF-8渲染显示,做得很好.

但是现在我创建了一个类PDO,以便于扩展和更容易

 class crud {
     // code..
     public function conn()
     {
         isset($this->username);
         isset($this->password);
         if (!$this->db instanceof PDO)
         {
             $this->db = new PDO($this->dsn, $this->username, $this->password);
             $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
             $this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");   
          }
      }
      /*more code here*/
}



/*** a new crud object ***/
$crud = new crud();
/*** The DSN ***/
$crud->dsn = "mysql:dbname=kdict;host=localhost";

/*** MySQL username and password ***/
$crud->username = 'root';
$crud->password = '';
/*** select all records from table ***/
$records = $crud->rawSelect("SELECT * FROM `en-kh` where english='a'");

/*** fetch only associative array of values ***/
$rows = $records->fetchAll(PDO::FETCH_ASSOC);

/*** display the records ***/
foreach($rows as $row)
{
    foreach($row as $fieldname=>$value)
    {
        echo $fieldname.' = '.$value.'<br />';
    }
    echo '<hr />';
}
?>

但它显示我的角色这样的’????’

我在Stack Overflow上找到了这个链接,看起来我遇到了同样的问题
Special characters in PHP / MySQL

它与我的问题看起来一样=>我试图解决它,但我仍然无法正常工作.

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

谁能告诉我这是什么问题?我该如何纠正?

谢谢

解决方法:

你错过了一个S:it’s SET NAMES而不是SET NAME:

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

当然,你还需要取消评论.此外,PDO :: MYSQL_ATTR_INIT_COMMAND can not be setPDO::setAttribute()建立数据库连接后(常量名称显示全部),您必须使用$driver_options参数在constructor中指定它,如下所示:

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

另一种方法是在连接后立即执行相同的查询:

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

标签:unicode-string,php,pdo
来源: https://codeday.me/bug/20190929/1832446.html