4

我正在使用PDO进行 MySQL 数据库连接、选择、更新和删除。

但是我在选择带有特殊字符的行时遇到问题,例如,我想选择一个带有“Judge-Fürstová Mila”的页面标题,

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');

下面是我的数据库类,

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);
        }

    }

我错过了我的数据库类或其他东西吗?

4

1 回答 1

5

尝试添加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东西,至少在我的情况下

于 2012-04-18T13:03:19.197 回答