我之前在我的正常mysql_*连接中有这个:

mysql_set_charset("utf8",$link);
mysql_query("SET NAMES 'UTF8'");

我需要它来做PDO吗?我应该把它放在哪里?

$connect = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

当前回答

我测试了这段代码

$db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql="select * from products  ";
$stmt=$db->prepare($sql);
$stmt->execute();
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){                  
    $id=$result['id'];
}

其他回答

我测试了这段代码

$db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql="select * from products  ";
$stmt=$db->prepare($sql);
$stmt->execute();
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){                  
    $id=$result['id'];
}

我认为你需要一个额外的查询,因为DSN中的字符集选项实际上被忽略了。请看其他答案评论中的链接。

看看Drupal 7是如何在http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:上实现的

// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
  $this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
  $this->exec('SET NAMES utf8');
}

你会把它放在你的连接字符串中,像这样:

"mysql:host=$host;dbname=$db;charset=utf8mb4"

然而,在PHP 5.3.6之前,charset选项是被忽略的。如果你运行的是旧版本的PHP,你必须这样做:

$dbh = new PDO("mysql:host=$host;dbname=$db",  $user, $password);
$dbh->exec("set names utf8mb4");

在PHP 5.3.6之前,charset选项被忽略。如果你运行的是旧版本的PHP,你必须这样做:

<?php

    $dbh = new PDO("mysql:$connstr",  $user, $password);

    $dbh -> exec("set names utf8");

?>
$conn = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);