How to use UTF-8 in Codeigniter with MySql database
Thursday, December 29, 2016
Set up or convert your MySQL:
For new database creation to use UTF-8
CREATE DATABASE example
CHARACTER SET utf8
DEFAULT CHARACTER SET utf8
COLLATE utf8_unicode_ci
DEFAULT COLLATE utf8_unicode_ci;
To convert the database to use UTF-8 (if already exist database)
ALTER DATABASE example
CHARACTER SET utf8
DEFAULT CHARACTER SET utf8
COLLATE utf8_unicode_ci
DEFAULT COLLATE utf8_unicode_ci;
Table creation to use UTF-8
CREATE TABLE blog (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
body TEXT COLLATE utf8_unicode_ci NOT NULL DEFAULT ''
) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
As with the database, if your tables already exist then you can use the following code to convert your data. You might get some fairly strange results if it is full of data in another non-English character set, but on the whole this has never been an issue for me.
First way to alter table
ALTER TABLE blog (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(100) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
body TEXT COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
) DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Second way to alter table
ALTER TABLE blog CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
php.ini setting to use UTF-8:
default_charset = "utf-8";
Set up codeigniter to UTF-8:
Config.php
$config['charset'] = 'UTF-8';
database.php
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
html header in index.php
header('Content-Type: text/html; charset=utf-8');
Labels: Codeigniter, MySql, PHP, UTF-8
Post a Comment