2012-04-18 89 views
2

我正在使用PDO用于MySQL数据库连接,选择,更新和删除。具有特殊字符的PHP PDO

但我有与特殊字符选择行,例如一个问题,我想选择与“法官Fürstová米拉”的网页的标题,

page

id title      content 
1  Judge-Fürstová Mila  xxx 

SQL,

SELECT * 
FROM page 
WHERE title = 'Judge-Fürstová Mila' 

如果我通过phpmyadmin查询返回结果。

但它返回0与PDO,

$sql = ' SELECT * 
    FROM page 
    WHERE title = ?'; 

$items = $connection->fetch_assoc($sql,'Judge-Fürstová Mila'); 

下面是我的DB类,

class database_pdo 
{ 
    # database handler 
    protected $connection = null; 

    # make a connection 
    public function __construct($dsn,$username,$password) 
    { 
     try 
     { 
      # MySQL with PDO_MYSQL 
      $this->connection = new PDO($dsn, $username, $password); 
      $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     } 
     catch (PDOException $e) 
     { 
      # call the get_error function 
      $this->get_error($e); 
     } 
    } 

    # don't forget to add getter method to get $this->connection, it's just a good practice. 
    public function get_connection() 
    { 
     return $this->connection; 
    } 

    public function fetch_assoc($query, $params = array()) 
    { 
     try 
     { 
      # prepare the query 
      $stmt = $this->connection->prepare($query); 

      # if $params is not an array, let's make it array with one value of former $params 
      if (!is_array($params)) $params = array($params); 

      # execute the query 
      $stmt->execute($params); 

      # return the result 
      return $stmt->fetch(); 
     } 
     catch (PDOException $e) 
     { 
      # call the get_error function 
      $this->get_error($e); 
     } 

    } 

我错过了在我的DB类或者别的什么东西?

回答

2

尝试添加charset=UTF-8$dsn,并改变

$this->connection = new PDO($dsn, $username, $password); 

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

我相信这是SET NAMES utf8的thingie,至少这是我的情况

+0

非常感谢为了这!修正了这个答案!谢谢。 – laukok 2012-04-18 13:39:32