Unicode error using PDO. Mysql Unicode problem

Unicode error using PDO. Mysql Unicode problem

Are you having those ???? things on your webpage when something you entered on Mr mysql is unicode character?
Here is a fix for that

Assuming you are using PDO object in your Db Class..

$db = array containing information ....
$this->pdo = new PDO("mysql:host={$db['host']};dbname={$db['database']};charset=utf8", $db['username'], $db['password']);

Now the next task to to tell Mysql to honor unicodes:

$this->query('SET NAMES utf8');
$this->query('SET CHARACTER SET utf8');
$this->query('SET COLLATION_CONNECTION="utf8_general_ci"');

where your query function could look like

public function query($query, $params=array())
	{
		$results=array();
		if (!empty($this->pdo))
		{
			try
			{
				$stmt=$this->pdo->prepare($query);
				$stmt->execute($params);
				$results=$stmt->fetchAll(PDO::FETCH_ASSOC);
			}
			catch(PDOException $exception)
			{
				echo "error occured";
				//logit or whatever
				die();
			}
		}
		return $results;
	}

Yea this would take care of the problem. There are certain things you have to do on the mysql database itself to handle unicode but I will not discuss those here
Hope it would help somebody..

Configuring PHP + MySQL + Apache on Amazon EC2 Step by Step

Access MySQL from Host being on Vagrant

Setting new Vagrant machine for PHP-Mysql development

error duplicate entry for key when creating new unique key mysql

Using mysql keyword as column in Doctrine Entity – PHP

PDO not throwing any exceptions

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*