Search code examples
codeigniterunicodeutf-8utf8mb4

How to insert emoticons into MySQL using CodeIgniter


How to insert unicode characters into MySQL and retrieve them using CodeIgniter? Is there any settings to be done.

This is the query when I print it.

INSERT INTO `reviews` (`description`) VALUES ('😀')

But, it is saving as ????.

Here is what I have done. CodeIgniter database.php

$db['default']['char_set'] = 'utf8mb4';
$db['default']['dbcollat'] = 'utf8mb4_unicode_ci';

Solution

  • It works fine for me when I test it (editor is Sublime Text).

    Create MySQL table:

    CREATE TABLE `reviews` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    

    Run an insert in CI:

    $this->db->insert('reviews', array('description' => '😀'));
    

    Grab our data back:

    $result = $this->db->get('reviews');
    

    Output our result:

    echo '<pre>';
    print_r($result->row());
    echo '</pre>';
    

    Our result:

    stdClass Object
    (
        [id] => 1
        [description] => 😀
    )