PHP PDO with Special Characters

陌路散爱 提交于 2020-01-01 11:53:32

问题


I am using PDO for MySQL database connection, selecting, updating and deleting.

But I have a problem with selecting rows with special characters, for instance, I want to select a page title with 'Judge-Fürstová Mila',

Table page,

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

SQL,

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

Returns result if I query via phpmyadmin.

But it return 0 with PDO,

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

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

Below is my db class,

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

    }

Have I missed something in my db class or something else?


回答1:


Try to add charset=UTF-8 in your $dsn, and change

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

to

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

I believe it is that SET NAMES utf8 thingie, at least it was in my case



来源:https://stackoverflow.com/questions/10209777/php-pdo-with-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!