Fixing Emojis in MySQL and CakePHP: Complete Guide
The problem occurs because your database is not configured to properly store emojis or special characters. To fix this, follow these steps:
1️⃣ Check the Table Charset
Run this command to check your table's current configuration:
SHOW CREATE TABLE your_table_name;
If the charset is set to utf8
(and not utf8mb4
), then it does not support emojis.
✅ Solution: Convert the table to utf8mb4
with:
ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
If you want to change the entire database:
ALTER DATABASE your_database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
2️⃣ Adjust the Connection in CakePHP
In the config/app.php
file, check the database configuration and add:
'encoding' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'flags' => [ PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci' ],
3️⃣ If You Use .env
This is the example of what you should include in the database connection:
export DATABASE_URL="mysql://user:password@localhost/database_name?encoding=utf8mb4&collation=utf8mb4_unicode_ci"
Adjusting the Display in CakePHP
In the view file (.ctp or .php), try forcing the correct content display using h() or html_entity_decode():
< ?= h($post->conteudo) ?>
If strange characters still appear, try:
< ?= html_entity_decode($post->conteudo, ENT_QUOTES, 'UTF-8') ?>
Or even:
< ?= mb_convert_encoding($post->conteudo, 'UTF-8', 'HTML-ENTITIES') ?>
At the beginning of the code, I separated just for formatting purposes, but in your actual code, it should be written together as since it is a reserved keyword. That’s why it was formatted this way in this article.
Check the HTML Page Charset
In your default layout (default.ctp or default.php inside src/Template/Layout), make sure the encoding is correct:
< meta charset="UTF-8">
👉 If you liked this article, share it on your social media so more people can learn about this topic! 🚀