pdo - 带有特殊字符的 PHP PDO

标签 pdo special-characters php-5.3

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

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

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

SQL,

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

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

但它使用 PDO 返回 0

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

    }

我是否错过了数据库类中的某些内容或其他内容?

最佳答案

尝试在您的$dsn中添加charset=UTF-8,然后更改

$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的事情,至少在我的情况下是这样的

关于pdo - 带有特殊字符的 PHP PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10209777/

相关文章:

mysqldump,避免转义双引号

php - XML、HTML、PHP,使用引号编写优雅、易于阅读的字符串

php - 使用 php 5.3 和 Laravel 4 取消引用数组

php - 如何使用 file_get_contents ('php://input' 获取文件信息 + 正文)?

即使用户名/密码很短/很长或密码不匹配,PHP 注册表也会将数据写入数据库。要改变什么?

php - 为注册用户简单上传数据库中的图像

android - TextView 不在 android 中显示类似 "à è ì ò ù"的字符

mysql - PHP fatal error : Call to a member function getEntry() upgraded php 5. 3 到 5.6

PHP 从两个表中选择并回显表名

php - 如何将数组中的每条数据保存到数据库中