Wednesday, January 9, 2013

Enable UTF-8 encoding in PHP5/PDO/MySQL

When opening connection, add SET NAMES command to PDO constructor:
$pdo = new PDO('mysql:host=hostname;dbname=database', 'username', 'password',
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
    );
And related MySQL databse setup: For a new database:
CREATE DATABASE database_name
 CHARACTER SET utf8
 DEFAULT CHARACTER SET utf8
 COLLATE utf8_general_ci
 DEFAULT COLLATE utf8_general_ci
 ;
For an already created database:
ALTER DATABASE database_name
 CHARACTER SET utf8
 DEFAULT CHARACTER SET utf8
 COLLATE utf8_general_ci
 DEFAULT COLLATE utf8_general_ci
 ;
For a new table:
CREATE TABLE table_name(
 ...
 )
 DEFAULT CHARACTER SET utf8   
 COLLATE utf8_general_ci;
For an already created table:
ALTER TABLE table_name
 DEFAULT CHARACTER SET utf8
 COLLATE utf8_general_ci
 ;

No comments:

Post a Comment