Member Login
Discussion

UTF8, PHP and MySQL

The problem

Get a £ character stored to MySQL, retrieved and then displayed without any weird characters in front of it using UTF8.

The solution

Make sure that you are using UTF8 everywhere!

The browser:

<?php header("Content-type: text/html; charset=utf-8"); ?>

You can also use a meta tag that is redundant in theory:


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Mysql:

Make sure that your table's collation is utf8_general_ci and that all string fields within the table also have the utf8_general_ci collation.

And here's the really important bit: make sure your client connection is also using UTF-8:

For mysql:


mysql_set_charset
('utf8');

or for mysqli:


mysqli_set_charset
('utf8');

or execute the SQL immediately after connection:


SET NAMES UTF8
;

or for PDO:


$handle 
= new PDO("mysql:host=localhost;dbname=dbname",
    
'username''password'
    array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

or for Zend_Db:


$params 
= array(
    
'host' => 'localhost',
    
'username' => 'username',
    
'password' => 'password',
    
'dbname' => 'dbname',
    
'driver_options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8;');
);
$db Zend_Db::factory('PDO_MYSQL'$params);

Now everything works as expected!

Source: http://akrabat.com/2009/03/18/utf8-php-and-mysql/

Current jobs
No job postings to display
Who's new
  • dhurba
  • samir
  • sushil
  • rightchoice2c_me
  • bishal
Poll
Which is your favorite PHP Web Framework?: