Cannot store emoji in database - php

THE SITUATION:
Sorry in advance if this question has already been asked, but the solutions aren't working for me.
No matter what I try, I cannot store emoji in my database. They are saved as ????.
The only emojis that are properly saved are the ones that require only 3 bytes, like the shy face or the sun.
The actual utf8mb4 is not working.
It has been tested on both Android and Ios. With same results.
VERSIONS:
Mysql: 5.5.49
CodeIgniter: 3.0.0
THE STEPS:
I have modified database character set and collation properties.
ALTER DATABASE my_database CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci
I have modified table character set and collation properties.
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
I have set each field of the table, where possible, as Encoding: UTF-8(ut8mb4) and Collation: utf8mb4_unicode_ci
I have modified the database connection in the CodeIgniter app.
I have run the following: SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci
Lastly I have also tried this:
REPAIR TABLE table_name;
OPTIMIZE TABLE table_name;
Everything should have been setup properly but yet it doesn't work.
DATABASE SETTINGS:
This is the outcome running the following command:
`SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';`
TABLE SETTINGS:
A screeshot of the table structure:
DATABASE CONNECTION:
These are the database connection settings inside database.php (note this is not the only database, there are also others that connect using utf8)
$db['my_database'] = array(
'dsn' => '',
'hostname' => PROJECT_DATABASE_HOSTNAME,
'username' => PROJECT_DATABASE_USERNAME,
'password' => PROJECT_DATABASE_PASSWORD,
'database' => PROJECT_DATABASE_NAME,
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8mb4',
'dbcollat' => 'utf8mb4_unicode_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
MY.CNF SETTINGS:
This is the whole content of the file my.cnf:
[mysqld]
default-storage-engine=MyISAM
innodb_file_per_table=1
max_allowed_packet=268435456
open_files_limit=10000
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
[client]
default-character-set = utf8mb4
[mysql]
default-character-set = utf8mb4
THE QUESTION:
Do you know why is not working? Am I missing something?
HYPHOTESIS 1:
I am not sure, but the cause of the problem may be this:
As you can see in my.cnf character-set-server is clearly set as utf8mb4:
But after running the query in the database:
SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';
The outcome is that character-set-server = latin1
Do you know why is that? Why is not actually updating?
HYPHOTESIS 2:
The application use several different databases.
This one is set to utf8mb4 but all the others are set to utf8. It may be a problem even if they are separated databases?
Thank you!
EDIT:
This is the outcome of SHOW CREATE TABLE app_messages;
CREATE TABLE `app_messages` (
`message_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`project_id` bigint(20) NOT NULL,
`sender_id` bigint(20) NOT NULL,
`receiver_id` bigint(20) NOT NULL,
`message` text COLLATE utf8mb4_unicode_ci,
`timestamp` bigint(20) DEFAULT NULL,
`is_read` enum('x','') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`message_id`)
) ENGINE=InnoDB AUTO_INCREMENT=496 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
EDIT 2:
I have run the following command:
INSERT INTO app_messages (message_id, project_id, sender_id, receiver_id, message, timestamp, is_read)
VALUES ('496','322','77','188', '😜' ,'1473413606','x');
And other two similar with πŸ˜‚ and πŸ‘»
They were inserted in the table without problems:
But in the actual app what i really see is: ? (this time only one ? and not 4)

Okay I finally managed to make it working!
Thanks to everybody that tried to help me, especially #Rick James and #Gerard Roche.
SUGGESTION:
If you need to work with emoji first of all make simple tests on localhost. Create a new database and make a fresh app for testing purpose.
If you follow the steps I wrote in the question or if you follow this tutorial: https://mathiasbynens.be/notes/mysql-utf8mb4#utf8-to-utf8mb4 it must work.
Working locally on a fresh basic app you will have more control and more room to make all the test you need.
SOLUTION:
In my case the problem was in the configuration of the database in CodeIgniter. It was not properly setting up the char_set and the collation for a stupid overlooking: I was overriding the database settings in the function that save messages to be sure it was working with the mobile database.
BEFORE:
function message_save ( $data = FALSE )
{
$project_db_config = array();
$project_db_config['hostname'] = 'MY_HOST';
$project_db_config['username'] = 'MY_USERNAME';
$project_db_config['password'] = 'MY_PASSWORD';
$project_db_config['database'] = 'MY_DATABASE';
$mobile_db = $this->load->database( $project_db_config, TRUE );
// other code to save message
}
AFTER:
function message_save ( $data = FALSE )
{
$mobile_db_connection = $this->load->database('admin_mobile_mh', TRUE);
// other code to save message
}
CONCLUSION:
The app must set the connection to the database properly.
If you have the database properly setup but you don't make the proper connection with your app, it won't work.
So if you encounter similar problems make sure the api properly setup the char_set as utf8mb4 and db_collat as utf8mb4_unicode_ci.

The only way I know of to get ???? for an Emoji is to not have the column declared utf8mb4. I understand that you have apparently determined that the column is declared that way, but please run SHOW CREATE TABLE table_name; to further confirm it.
The system default, the database default, and the table default are irrelevant if the column overrides the CHARACTER SET.
A note to all the other attempted answers: The COLLATION is irrelevant, only the CHARACTER SET is relevant for this question.

my.cnf is loaded first, then conf.d/*.cnf.
Instead of modifying my.cnf *(which may be overridden by configurations in conf.d/*.cnf), create a custom override configuration e.g. conf.d/90-my.cnf.
Prefixing 90 ensures the custom settings are loaded last which means they overwrite any earlier set settings.
To ensure the new configuration is reloaded, see Reload Without Restarting the MySQL service.
Example Configuration Structure (Linux)
.
β”œβ”€β”€ conf.d
β”‚Β Β  β”œβ”€β”€ 90-my.cnf
β”‚Β Β  β”œβ”€β”€ conn.cnf
β”‚Β Β  β”œβ”€β”€ my5.6.cnf
β”‚Β Β  └── mysqld_safe_syslog.cnf
β”œβ”€β”€ debian.cnf
β”œβ”€β”€ debian-start
└── my.cnf
conf.d/90-my.cnf
# https://mathiasbynens.be/notes/mysql-utf8mb4
# http://stackoverflow.com/q/3513773/934739
[client]
default-character-set = utf8mb4
[mysql]
default-character-set = utf8mb4
[mysqld]
character-set-client-handshake = FALSE
# The server character set and collation are used as default values if the
# database character set and collation are not specified in CREATE DATABASE
# statements. They have no other purpose.
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

Instead of the varchar you can change the Table filed value as follows to utf8mb4
Make sure all your tables' default character sets and text fields are converted to utf8mb4, in addition to setting the client & server character sets, e.g. ALTER TABLE mytable charset=utf8mb4, MODIFY COLUMN textfield1 VARCHAR(255) CHARACTER SET utf8mb4,MODIFY COLUMN textfield2 VARCHAR(255) CHARACTER SET utf8mb4; and so on.

hi i have used EMOJI in android and i stored it to orm database using EMOJI_INDEX.I saved in db in normal message in string form but when i get that time i check if there is any emoji then convert it into there processemoji.
textMessage.setText(getItem(pos).file != null ? "":EmojiUtil.getInstance(context).processEmoji(getItem(pos).message, textMessage.getTextSize()));
Take a look from here how i changed Emoji_Index to process
if (emojiImages == null || emojiImages.isRecycled()) {
InputStream localInputStream;
try {
localInputStream = context.getAssets().open("emoji/emoji_2x.png");
Options opts = new Options();
opts.inPurgeable = true;
opts.inInputShareable = true;
emojiImages = BitmapFactory.decodeStream(localInputStream, null, opts);
} catch (IOException e) {
return Html.fromHtml(paramString);
}
}
For more information take a look from here.
Thanks hope this will help you.

I had a problem with the server version, on linux. I had to change the file database_interface.lib.php manually and around this
if (!PMA_DRIZZLE) {
if (! empty($GLOBALS['collation_connection'])) {
change it so that, is becomes this: ( note the utf8mb4_unicode_ci references )
// Skip charsets for Drizzle
if (!PMA_DRIZZLE) {
if (! empty($GLOBALS['collation_connection'])) {
PMA_DBI_query("SET CHARACTER SET 'utf8mb4';", $link, PMA_DBI_QUERY_STORE);
$set_collation_con_query = "SET collation_connection = '"
. PMA_Util::sqlAddSlashes($GLOBALS['collation_connection']) . "';";
PMA_DBI_query(
$set_collation_con_query,
$link,
PMA_DBI_QUERY_STORE
);
} else {
PMA_DBI_query(
"SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';",
$link,
PMA_DBI_QUERY_STORE
);
}
}

Updated answer
You can try charset utf8 collation utf8_unicode_ci instead of utf8mb4_unicode_ci.
run this query
ALTER TABLE table_name CHANGE `column_name` `column_name` TEXT CHARSET utf8 COLLATE utf8_unicode_ci;
old answer
You should use collation utf8mb4_bin instead of utf8mb4_unicode_ci.
run this query
ALTER TABLE table_name CHANGE `column_name` `column_name` TEXT CHARSET utf8mb4 COLLATE utf8mb4_bin;
Emojis will be stored as code and converted into emojis again in Android and iOS apps. I have used this code in my projects as well.

Related

Not able to insert πŸ‘ŒπŸ» into comments in WordPress [duplicate]

I have a MySQL database configured with the default collation utf8mb4_general_ci. When I try to insert a row containing an emoji character in the text using the following query
insert into tablename
(column1,column2,column3,column4,column5,column6,column7)
values
('273','3','HdhdhdhπŸ˜œπŸ˜€πŸ˜ŠπŸ˜ƒhzhzhzzhjzj ζˆ‘ηˆ±δ½  ❌',49,1,'2016-09-13 08:02:29','2016-09-13 08:02:29');
MySQL is raising the following error
1366 Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column
'comment' at row 1
1) Database: Change Database default collation as utf8mb4.
2) Table: Change table collation as CHARACTER SET utf8mb4 COLLATE utf8mb4_bin.
Query:
ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
3) Code:
INSERT INTO tablename (column1, column2, column3, column4, column5, column6, column7)
VALUES ('273', '3', 'HdhdhdhπŸ˜œπŸ˜€πŸ˜ŠπŸ˜ƒhzhzhzzhjzj ζˆ‘ηˆ±δ½  ❌', 49, 1, '2016-09-13 08:02:29', '2016-09-13 08:02:29')
4) Set utf8mb4 in database connection:
$database_connection = new mysqli($server, $user, $password, $database_name);
$database_connection->set_charset('utf8mb4');
Step 1, change your database's default charset:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
if the db is not created yet, create it with correct encodings:
CREATE DATABASE database_name DEFAULT CHARSET = utf8mb4 DEFAULT COLLATE = utf8mb4_unicode_ci;
Step 2, set charset when creating table:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or alter table
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE table_name MODIFY field_name TEXT CHARSET utf8mb4;
The command to modify the column is:
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME TYPE;
And we need to use type = BLOB
Example to modify is as under:-
ALTER TABLE messages MODIFY content BLOB;
I checked that latest mySQL and other databases don't need '' to use in command on table_name, column_name etc.
Fetch and Save data:
Directly save the chat content to column and to retrieve data, fetch data as byte array (byte[]) from db column and then convert it to string e.g. (Java code)
new String((byte[]) arr)
Both the databases and tables should have character set utf8mb4 and collation utf8mb4_unicode_ci.
When creating a new database you should use:
CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
If you have an existing database and you want to add support:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
You also need to set the correct character set and collation for your tables:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or change it if you've got existing tables with a lot of data:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Note that utf8_general_ci is no longer recommended best practice. See the related Q & A:
What's the difference between utf8_general_ci and utf8_unicode_ci on Stack Overflow.
If you are using Solr + Mysql + Java, you can use:
This can be Used :
case1: When you don`t want to alter DB.
case2: when you have to import emoticons from your Mysql to Solr core.
In above case this is one of the solutions to store your emoticons in your system.
Steps to use it:
Library used: import java.net.URLDecoder;
import java.net.URLEncoder;
Use urlEncoder to encode your String having emoticons.
Store it in DB without altering the MysqlDB.
You can store it in solr core(decoded form)if you want or you can store
encoded form.
When fetching these emoticons from DB or Solr core you can now decode it
Using urlDecoder.
Code example:
import java.net.URLDecoder;
import java.net.URLEncoder;
public static void main(String[] args) {
//SpringApplication.run(ParticipantApplication.class, args);
System.out.println(encodeStringUrl("πŸ‡ΊπŸ‡ΈπŸ‡¨πŸ‡³πŸ‡―πŸ‡΅πŸ‡©πŸ‡ͺπŸ”³πŸ”ΊπŸ†”πŸ†”πŸ†‘3⃣5⃣3βƒ£β€Όγ€½βž—βž—πŸŽ¦πŸ”†πŸŽ¦πŸ”†β™‹β™β™‹β™β¬…β¬†β¬…β¬…πŸ›‚πŸšΉπŸ›‚πŸ›„πŸš³πŸš¬πŸ’ŠπŸ”§πŸ’ŠπŸ—Ώ "));
System.out.println(decodeStringUrl("Hello+emoticons%2C%2C%F0%9F%98%80%F0%9F%98%81%F0%9F%98%8A%F0%9F%98%8B%F0%9F%98%8E%F0%9F%98%8A%F0%9F%98%8D%E2%98%BA%F0%9F%98%98%E2%98%BA%F0%9F%98%91%F0%9F%98%87%F0%9F%98%98%F0%9F%98%8B%F0%9F%90%84"));
}
public static String encodeStringUrl(String url) {
String encodedUrl =null;
try {
encodedUrl = URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
return encodedUrl;
}
return encodedUrl;
}
public static String decodeStringUrl(String encodedUrl) {
String decodedUrl =null;
try {
decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
return decodedUrl;
}
return decodedUrl;
}
I have updated my database and table to upgraded from utf8 to utf8mb4. But nothing works for me. Then I tried to update column datatype to blob, luckily it worked for me and data has been saved. Even my database and table both are CHARACTER SET utf8 COLLATE utf8_unicode
My answer only adds to Selvamani P answer.
You might also need to change any SET NAMES utf8 queries with SET NAMES utf8mb4. That did the trick for me.
Also, this is a great article to port your website from utf8 to utf8mb4. In particular the article makes 2 good points on indexes and repairing tables after converting them to utf8mb4:
INDEXES
When converting from utf8 to utf8mb4, the maximum length of a column
or index key is unchanged in terms of bytes. Therefore, it is smaller
in terms of characters, because the maximum length of a character is
now four bytes instead of three. [...] The InnoDB storage engine has a maximum index length of 767 bytes, so for utf8 or utf8mb4 columns, you can index a maximum of 255 or 191 characters, respectively. If you currently have utf8 columns with indexes longer than 191 characters, you will need to index a smaller number of characters when using utf8mb4.
REPAIRING TABLES
After upgrading the MySQL server and making the necessary changes
explained above, make sure to repair and optimize all databases and
tables. I didn’t do this right away after upgrading (I didn’t think it
was necessary, as everything seemed to work fine at first glance), and
ran into some weird bugs where UPDATE statements didn’t have any
effect, even though no errors were thrown.
Read more about the queries to repair tables on the article.
I have a good solution to save your time. I also meet the same problem but I could not solve this problem by the first answer.
Your defualt character is utf-8. But emoji needs utf8mb4 to support it.
If you have the permission to revise the configure file of mysql, you can follow this step.
Therefore, do this following step to upgrade your character set ( from utf-8 to utf8mb4).
step 1. open your my.cnf for mysql, add these following lines to your my.cnf.
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
init_connect='SET NAMES utf8mb4'
[mysql]
default-character-set = utf8mb4
[client]
default-character-set = utf8mb4
step2. stop your mysql service, and start mysql service
mysql.server stop
mysql.server start
Finished!
Then you can check your character are changed into utf8mb4.
mysql> SHOW VARIABLES LIKE 'character_set%';
+--------------------------+----------------------------------------------------------+
| Variable_name | Value |
+--------------------------+----------------------------------------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| character_sets_dir | /usr/local/Cellar/mysql#5.7/5.7.29/share/mysql/charsets/ |
+--------------------------+----------------------------------------------------------+
8 rows in set (0.00 sec)
Well, you need not to change the Whole DB Charset. Instead of that you can do it by changing column to blob type.
ALTER TABLE messages MODIFY content BLOB;
There are two ways-->
# Way one
The simplest is to follow below steps:
Step 1:
SET NAMES utf8mb4;
Step 2:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
Step 3:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Step 4:
ALTER TABLE table_name CHANGE column column VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
That's all!!
#Way Two (For Python)
This is a hack and its work like a charm
Step 1:
Encode your string and decode it in ASCII, and save it to your database.
content = 'πŸ₯³πŸ₯³ Content to be save in πŸ₯³πŸ₯³ Database πŸ₯³πŸ₯³'
encoded_content = content.encode('unicode-escape').decode('ASCII'))
This simply store encoded_content string in DB
Step 2:
While fetch this column data to show your user, simply convert it,
here content is the data, fetched from the database.
c = bytes(encoded_content, 'utf-8')
original_content = c.decode('unicode-escape')
Done!!
Emoji support for application having tech stack - mysql, java, springboot, hibernate
Apply below changes in mysql for unicode support.
ALTER DATABASE <database-name> CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE <table-name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
DB Connection - jdbc url change:
jdbc:mysql://localhost:3306/<database-name>?useUnicode=yes&characterEncoding=UTF-8
Note - If the above step is not working please update mysql-connector version to 8.0.15. (mysql 5.7 works with connector version 8.0.15 for unicode support)
The main point hasn't been mentioned in the above answers that,
We need to pass query string with the options "useUnicode=yes" and "characterEncoding=UTF-8" in connection string
Something like this
mysql://USERNAME:PASSWORD#HOSTNAME:PORT/DATABASE_NAME?useUnicode=yes&characterEncoding=UTF-8
The simplest solution what works for me is to store the data as json_encode.
later when you retrieve just make sure you json_decode it.
Here you don't have to change the collation or the character set of the database and the table.
For Rails, next to the accepted answer, don't forget to add:
encoding: utf8mb4
collation: utf8mb4_bin
to your database.yml
For anyone trying to solve this on a managed MySQL instance (in my case on AWS RDS), the easiest way was to modify the parameter group and set the server character set and collation to be utf8mb4 and utf8mb4_bin, respectively. After rebooting the server, a quick query verifies the settings for system databases and any newly created ones:
SELECT * FROM information_schema.SCHEMATA S;
If you are inserting using PHP, and you have followed the various ALTER database and ALTER table options above, make sure your php connection's charset is utf8mb4.
Example of connection string:
$this->pdo = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8mb4", etc etc
Notice the "charset" is utf8mb4, not just utf8!
Today I am facing the same question, but solutions in other answers don't work for me. Here is my solution.
First of all, changing charset in mysql/my.ini, database, and the table is necessary, as described in other answers.
Second, if you have created your tables before you want to saving emoji, you can use
SHOW FULL COLUMNS FROM `yourcolumn`;
To check whether the column you want to save emoji is set in utf8mb4. You can find that most of your columns are still in utf8 charset.
Use
ALTER TABLE `yourtable` CHANGE `yourcolumn` `yourcolumn` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
I'm facing this issue when upgrading MySQL 5.0 to MySQL 8.0 AWS RDS, trying many things finally what works for me share with you folks.
Error:
Warning: PDOStatement::execute(): SQLSTATE[HY000]: General error:
3988 Conversion from collation utf8_unicode_ci into utf8mb4_general_ci
impossible for parameter in /var/www/html/pdo_con.php on line 87
Array (
[0] => HY000
[1] => 3988
[2] => Conversion from collation utf8_unicode_ci into utf8mb4_general_ci impossible for parameter )
Backend: PHP5/php7 + PDO is giving trouble.
Solution: only two thing needs to do
Add a code in line after your pdo connection
$conn->exec("set names utf8mb4");
where $conn is connection handler in PDO
Alter the table and set charset utf8mb4 and collate utf8mb4_unicode_ci.
ALTER TABLE mytable CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
This command will change your every column charset to utf8mb4 and collation too.
Put this right before your database call:
mysqli_set_charset($db, "utf8mb4");
This will allow you to input emojis directly into the database table that has been set to Collation: utfmb4_bin. Make sure to set your column to utfmb4 as well.
Hi my friends
This is how I solved this problem and I was happy to teach it to you as well
I am in the Android application
I encrypt a string containing text and emoj and send it to the server and save it in the mysql table and after receiving it from the server I decrypt it and display it in the textview.
encoded and decoded my message before request and after response:
I send Android app messages to mysql via pdo through this method and receive them with pdo. And I have no problem.
I think it was a good way. Please like
Thankful
public void main()
{
String message="hi mester ali moradi 🌦️🌦️ how are you ?";
String encoded_message=encodeStringUrl(message);
String decode_message=decodeStringUrl(encoded_message);
}
public static String encodeStringUrl(String message) {
String encodedUrl =null;
try {
encodedUrl = URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
return encodedUrl;
}
return encodedUrl;
}
public static String decodeStringUrl(String message) {
String decodedUrl =null;
try {
decodedUrl = URLDecoder.decode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
return decodedUrl;
}
return decodedUrl;
}
message : hi mester ali moradi 🌦️🌦️ how are you ?
encoded : ghgh%F0%9F%98%AE%F0%9F%A4%90%F0%9F%98%A5
decoded :hi mester ali moradi 🌦️🌦️ how are you ?
If you use command line interface for inserting sql file to database.
Be sure your table charset utf8mb4 and column collation utf8mb4_unicode_ci or utf8mb4_bin
mysql -u root -p123456 my_database < profiles.sql
ERROR 1366 (HY000) at line 1679: Incorrect string value: '\xF0\x9F\x98\x87\xF0\x9F...' for column 'note' at row 328
we can solve the problem with this parameter
--default-character-set=name (Set the default character set)
mysql -u root -p123456 --default-character-set=utf8mb4 my_database < profiles.sql
Actually i'm using mysql Ver 8.0.23
I had created the both Database and the Table, without Altering them :
mysql> CREATE DATABASE tp2;
Query OK, 1 row affected (0.30 sec)
mysql> INSERT INTO tweetsRep(username, content) VALUES ('ibrahim', '🀣 oh my god');
Then after select, i thing it just worked fine !
I don't know if it is requested to enter Emoji as a hexadecimal or other encoding string or just copy it as it is... just correct me if i'm wrong, thank you !
I tried different methods and approaches and found a way that worked for me.
The SQL for the update query:
ALTER DATABASE YOUR_DB_NAME_HERE CHARACTER SET = utf8mb4 COLLATE =
utf8mb4_unicode_ci;
You can see in the table, the emoji's are present
And if you go to this page: https://www.thecookingcat.com/recipes/thai-green-curry.php#comments
You can see the emojis in the comments.
I also have an RSS feed on the site and the emojis are included in the RSS feed XML code.
If anyone searching this in 2022 just follow these steps and no need to do any modification on Database
Name Space
using System.Web;
Your normal text like this :
String encode = "thank you 😊"
encode = HttpUtility.UrlEncode(encode);
It will store in Database like this : "thank+you+%f0%9f%98%8a"
And next fetch that data form your Database and do UrlDecode like this
DataSet ds = "Fetch your Encoded data form your Database";
String decode = HttpUtility.UrlDecode(ds.Tables[0].Rows[i]["YourColumnName"].ToString().Trim());
And your output is :-
decode = "thank you 😊".
It is working fine for me and saved time.

PHP 7 & Doctrine 2.4.3 : Changing column charset from utf8 to utf8mb4

I'm working on a project using Doctrine 2.4.3 with a MySQL 5.7.21 database with utf8 as default charset.
Recently, I've been looking to implement emoji support. To overcome MySQL's limitation of 3 bytes for utf8, I need to change the columns that can receive emojis to the utf8mb4 charset (see https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html).
However, I have not found a way to reflect this in my entities (using annotations).
My database connection config is the following :
$data = array(
'driver' => 'pdo_mysql',
'host' => $dbhost,
'port' => $dbport,
'dbname' => $dbname,
'user' => $dbuser,
'password' => $dbpw,
'charset' => 'utf8mb4'
);
I tried adding annotations to the table :
/* #Entity(repositoryClass="path\to\DAO") #Table(name="post", indexes={#Index(name="uid", columns={"uid"})}, options={"charset":"utf8mb4", "collation":"utf8mb4_unicode_ci"})
* #HasLifecycleCallbacks */
class Post extends BaseEntity
{
...
}
In the same fashion, tried adding annotations to the column (in the same table) itself :
/* #Column(type="text", options={"charset":"utf8mb4", collation":"utf8mb4_unicode_ci"}) */
protected $text;
None of the above worked. I expected an ALTER TABLE query when executing doctrine orm:schema-tool:update --dump-sql but Doctrine sees no change, and I still can't insert 4 bytes emojis.
If I update the column's charset myself directly in MySQL, emojis do get supported, but when I do run orm:schema-tool:update, Doctrine sees a difference between my entity and the schema, but seems to not know what to make of it since the output I get is the following :
ALTER TABLE post CHANGE text text LONGTEXT NOT NULL ;
I also tried to add SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci as driverOptions in my database connection config array, alas to no result either.
Unfortunately, I could not find anything regarding this matter in Doctrine's documentation.
If any of you has any clue regarding this matter, feel free to hit me up! Thanks in advance.
To convert the whole table:
ALTER TABLE tbl CONVERT TO CHARACTER SET utf8mb4;
Please provide
SHOW CREATE TABLE ...
For more troubleshooting: Trouble with UTF-8 characters; what I see is not what I stored
As I have legacy requirements and cannot update Doctrine's lib as of right now, I had to find a workaround.
What I did was manually convert my tables to utf8mb4 with SQL queries, which is not overwritten by Doctrine back to utf8 when executing orm:schema-tool:update --force after the charset conversion.
For the record, I generated the update statements with the following script :
SELECT CONCAT('ALTER TABLE ', t.table_schema, '.', t.table_name, ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;')
FROM information_schema.tables t
WHERE t.table_schema LIKE {your_schema};
^ Do not execute this blindly - check beforehand if existing data will fit while utf8mb4 encoded. For more details check the very good article from Mathias Bynens on the matter : https://mathiasbynens.be/notes/mysql-utf8mb4#column-index-length
I also changed the database's charset settings.
ALTER DATABASE {database_name} CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
I did keep the 'charset' => 'utf8mb4' in the Doctrine's database connection settings array for correct transmission of the data.
For new entities (tables), annotating them with correct settings in table options does create them with the right charset and collation :
#Entity #Table(name="table", options={"charset":"utf8mb4", "collate":"utf8mb4_unicode_ci"})
Cheers.

😍 into mysql database not working [duplicate]

I have a MySQL database configured with the default collation utf8mb4_general_ci. When I try to insert a row containing an emoji character in the text using the following query
insert into tablename
(column1,column2,column3,column4,column5,column6,column7)
values
('273','3','HdhdhdhπŸ˜œπŸ˜€πŸ˜ŠπŸ˜ƒhzhzhzzhjzj ζˆ‘ηˆ±δ½  ❌',49,1,'2016-09-13 08:02:29','2016-09-13 08:02:29');
MySQL is raising the following error
1366 Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column
'comment' at row 1
1) Database: Change Database default collation as utf8mb4.
2) Table: Change table collation as CHARACTER SET utf8mb4 COLLATE utf8mb4_bin.
Query:
ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
3) Code:
INSERT INTO tablename (column1, column2, column3, column4, column5, column6, column7)
VALUES ('273', '3', 'HdhdhdhπŸ˜œπŸ˜€πŸ˜ŠπŸ˜ƒhzhzhzzhjzj ζˆ‘ηˆ±δ½  ❌', 49, 1, '2016-09-13 08:02:29', '2016-09-13 08:02:29')
4) Set utf8mb4 in database connection:
$database_connection = new mysqli($server, $user, $password, $database_name);
$database_connection->set_charset('utf8mb4');
Step 1, change your database's default charset:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
if the db is not created yet, create it with correct encodings:
CREATE DATABASE database_name DEFAULT CHARSET = utf8mb4 DEFAULT COLLATE = utf8mb4_unicode_ci;
Step 2, set charset when creating table:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or alter table
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE table_name MODIFY field_name TEXT CHARSET utf8mb4;
The command to modify the column is:
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME TYPE;
And we need to use type = BLOB
Example to modify is as under:-
ALTER TABLE messages MODIFY content BLOB;
I checked that latest mySQL and other databases don't need '' to use in command on table_name, column_name etc.
Fetch and Save data:
Directly save the chat content to column and to retrieve data, fetch data as byte array (byte[]) from db column and then convert it to string e.g. (Java code)
new String((byte[]) arr)
Both the databases and tables should have character set utf8mb4 and collation utf8mb4_unicode_ci.
When creating a new database you should use:
CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
If you have an existing database and you want to add support:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
You also need to set the correct character set and collation for your tables:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or change it if you've got existing tables with a lot of data:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Note that utf8_general_ci is no longer recommended best practice. See the related Q & A:
What's the difference between utf8_general_ci and utf8_unicode_ci on Stack Overflow.
If you are using Solr + Mysql + Java, you can use:
This can be Used :
case1: When you don`t want to alter DB.
case2: when you have to import emoticons from your Mysql to Solr core.
In above case this is one of the solutions to store your emoticons in your system.
Steps to use it:
Library used: import java.net.URLDecoder;
import java.net.URLEncoder;
Use urlEncoder to encode your String having emoticons.
Store it in DB without altering the MysqlDB.
You can store it in solr core(decoded form)if you want or you can store
encoded form.
When fetching these emoticons from DB or Solr core you can now decode it
Using urlDecoder.
Code example:
import java.net.URLDecoder;
import java.net.URLEncoder;
public static void main(String[] args) {
//SpringApplication.run(ParticipantApplication.class, args);
System.out.println(encodeStringUrl("πŸ‡ΊπŸ‡ΈπŸ‡¨πŸ‡³πŸ‡―πŸ‡΅πŸ‡©πŸ‡ͺπŸ”³πŸ”ΊπŸ†”πŸ†”πŸ†‘3⃣5⃣3βƒ£β€Όγ€½βž—βž—πŸŽ¦πŸ”†πŸŽ¦πŸ”†β™‹β™β™‹β™β¬…β¬†β¬…β¬…πŸ›‚πŸšΉπŸ›‚πŸ›„πŸš³πŸš¬πŸ’ŠπŸ”§πŸ’ŠπŸ—Ώ "));
System.out.println(decodeStringUrl("Hello+emoticons%2C%2C%F0%9F%98%80%F0%9F%98%81%F0%9F%98%8A%F0%9F%98%8B%F0%9F%98%8E%F0%9F%98%8A%F0%9F%98%8D%E2%98%BA%F0%9F%98%98%E2%98%BA%F0%9F%98%91%F0%9F%98%87%F0%9F%98%98%F0%9F%98%8B%F0%9F%90%84"));
}
public static String encodeStringUrl(String url) {
String encodedUrl =null;
try {
encodedUrl = URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
return encodedUrl;
}
return encodedUrl;
}
public static String decodeStringUrl(String encodedUrl) {
String decodedUrl =null;
try {
decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
return decodedUrl;
}
return decodedUrl;
}
I have updated my database and table to upgraded from utf8 to utf8mb4. But nothing works for me. Then I tried to update column datatype to blob, luckily it worked for me and data has been saved. Even my database and table both are CHARACTER SET utf8 COLLATE utf8_unicode
My answer only adds to Selvamani P answer.
You might also need to change any SET NAMES utf8 queries with SET NAMES utf8mb4. That did the trick for me.
Also, this is a great article to port your website from utf8 to utf8mb4. In particular the article makes 2 good points on indexes and repairing tables after converting them to utf8mb4:
INDEXES
When converting from utf8 to utf8mb4, the maximum length of a column
or index key is unchanged in terms of bytes. Therefore, it is smaller
in terms of characters, because the maximum length of a character is
now four bytes instead of three. [...] The InnoDB storage engine has a maximum index length of 767 bytes, so for utf8 or utf8mb4 columns, you can index a maximum of 255 or 191 characters, respectively. If you currently have utf8 columns with indexes longer than 191 characters, you will need to index a smaller number of characters when using utf8mb4.
REPAIRING TABLES
After upgrading the MySQL server and making the necessary changes
explained above, make sure to repair and optimize all databases and
tables. I didn’t do this right away after upgrading (I didn’t think it
was necessary, as everything seemed to work fine at first glance), and
ran into some weird bugs where UPDATE statements didn’t have any
effect, even though no errors were thrown.
Read more about the queries to repair tables on the article.
I have a good solution to save your time. I also meet the same problem but I could not solve this problem by the first answer.
Your defualt character is utf-8. But emoji needs utf8mb4 to support it.
If you have the permission to revise the configure file of mysql, you can follow this step.
Therefore, do this following step to upgrade your character set ( from utf-8 to utf8mb4).
step 1. open your my.cnf for mysql, add these following lines to your my.cnf.
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
init_connect='SET NAMES utf8mb4'
[mysql]
default-character-set = utf8mb4
[client]
default-character-set = utf8mb4
step2. stop your mysql service, and start mysql service
mysql.server stop
mysql.server start
Finished!
Then you can check your character are changed into utf8mb4.
mysql> SHOW VARIABLES LIKE 'character_set%';
+--------------------------+----------------------------------------------------------+
| Variable_name | Value |
+--------------------------+----------------------------------------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| character_sets_dir | /usr/local/Cellar/mysql#5.7/5.7.29/share/mysql/charsets/ |
+--------------------------+----------------------------------------------------------+
8 rows in set (0.00 sec)
Well, you need not to change the Whole DB Charset. Instead of that you can do it by changing column to blob type.
ALTER TABLE messages MODIFY content BLOB;
There are two ways-->
# Way one
The simplest is to follow below steps:
Step 1:
SET NAMES utf8mb4;
Step 2:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
Step 3:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Step 4:
ALTER TABLE table_name CHANGE column column VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
That's all!!
#Way Two (For Python)
This is a hack and its work like a charm
Step 1:
Encode your string and decode it in ASCII, and save it to your database.
content = 'πŸ₯³πŸ₯³ Content to be save in πŸ₯³πŸ₯³ Database πŸ₯³πŸ₯³'
encoded_content = content.encode('unicode-escape').decode('ASCII'))
This simply store encoded_content string in DB
Step 2:
While fetch this column data to show your user, simply convert it,
here content is the data, fetched from the database.
c = bytes(encoded_content, 'utf-8')
original_content = c.decode('unicode-escape')
Done!!
Emoji support for application having tech stack - mysql, java, springboot, hibernate
Apply below changes in mysql for unicode support.
ALTER DATABASE <database-name> CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE <table-name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
DB Connection - jdbc url change:
jdbc:mysql://localhost:3306/<database-name>?useUnicode=yes&characterEncoding=UTF-8
Note - If the above step is not working please update mysql-connector version to 8.0.15. (mysql 5.7 works with connector version 8.0.15 for unicode support)
The main point hasn't been mentioned in the above answers that,
We need to pass query string with the options "useUnicode=yes" and "characterEncoding=UTF-8" in connection string
Something like this
mysql://USERNAME:PASSWORD#HOSTNAME:PORT/DATABASE_NAME?useUnicode=yes&characterEncoding=UTF-8
The simplest solution what works for me is to store the data as json_encode.
later when you retrieve just make sure you json_decode it.
Here you don't have to change the collation or the character set of the database and the table.
For Rails, next to the accepted answer, don't forget to add:
encoding: utf8mb4
collation: utf8mb4_bin
to your database.yml
For anyone trying to solve this on a managed MySQL instance (in my case on AWS RDS), the easiest way was to modify the parameter group and set the server character set and collation to be utf8mb4 and utf8mb4_bin, respectively. After rebooting the server, a quick query verifies the settings for system databases and any newly created ones:
SELECT * FROM information_schema.SCHEMATA S;
If you are inserting using PHP, and you have followed the various ALTER database and ALTER table options above, make sure your php connection's charset is utf8mb4.
Example of connection string:
$this->pdo = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8mb4", etc etc
Notice the "charset" is utf8mb4, not just utf8!
Today I am facing the same question, but solutions in other answers don't work for me. Here is my solution.
First of all, changing charset in mysql/my.ini, database, and the table is necessary, as described in other answers.
Second, if you have created your tables before you want to saving emoji, you can use
SHOW FULL COLUMNS FROM `yourcolumn`;
To check whether the column you want to save emoji is set in utf8mb4. You can find that most of your columns are still in utf8 charset.
Use
ALTER TABLE `yourtable` CHANGE `yourcolumn` `yourcolumn` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
I'm facing this issue when upgrading MySQL 5.0 to MySQL 8.0 AWS RDS, trying many things finally what works for me share with you folks.
Error:
Warning: PDOStatement::execute(): SQLSTATE[HY000]: General error:
3988 Conversion from collation utf8_unicode_ci into utf8mb4_general_ci
impossible for parameter in /var/www/html/pdo_con.php on line 87
Array (
[0] => HY000
[1] => 3988
[2] => Conversion from collation utf8_unicode_ci into utf8mb4_general_ci impossible for parameter )
Backend: PHP5/php7 + PDO is giving trouble.
Solution: only two thing needs to do
Add a code in line after your pdo connection
$conn->exec("set names utf8mb4");
where $conn is connection handler in PDO
Alter the table and set charset utf8mb4 and collate utf8mb4_unicode_ci.
ALTER TABLE mytable CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
This command will change your every column charset to utf8mb4 and collation too.
Put this right before your database call:
mysqli_set_charset($db, "utf8mb4");
This will allow you to input emojis directly into the database table that has been set to Collation: utfmb4_bin. Make sure to set your column to utfmb4 as well.
Hi my friends
This is how I solved this problem and I was happy to teach it to you as well
I am in the Android application
I encrypt a string containing text and emoj and send it to the server and save it in the mysql table and after receiving it from the server I decrypt it and display it in the textview.
encoded and decoded my message before request and after response:
I send Android app messages to mysql via pdo through this method and receive them with pdo. And I have no problem.
I think it was a good way. Please like
Thankful
public void main()
{
String message="hi mester ali moradi 🌦️🌦️ how are you ?";
String encoded_message=encodeStringUrl(message);
String decode_message=decodeStringUrl(encoded_message);
}
public static String encodeStringUrl(String message) {
String encodedUrl =null;
try {
encodedUrl = URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
return encodedUrl;
}
return encodedUrl;
}
public static String decodeStringUrl(String message) {
String decodedUrl =null;
try {
decodedUrl = URLDecoder.decode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
return decodedUrl;
}
return decodedUrl;
}
message : hi mester ali moradi 🌦️🌦️ how are you ?
encoded : ghgh%F0%9F%98%AE%F0%9F%A4%90%F0%9F%98%A5
decoded :hi mester ali moradi 🌦️🌦️ how are you ?
If you use command line interface for inserting sql file to database.
Be sure your table charset utf8mb4 and column collation utf8mb4_unicode_ci or utf8mb4_bin
mysql -u root -p123456 my_database < profiles.sql
ERROR 1366 (HY000) at line 1679: Incorrect string value: '\xF0\x9F\x98\x87\xF0\x9F...' for column 'note' at row 328
we can solve the problem with this parameter
--default-character-set=name (Set the default character set)
mysql -u root -p123456 --default-character-set=utf8mb4 my_database < profiles.sql
Actually i'm using mysql Ver 8.0.23
I had created the both Database and the Table, without Altering them :
mysql> CREATE DATABASE tp2;
Query OK, 1 row affected (0.30 sec)
mysql> INSERT INTO tweetsRep(username, content) VALUES ('ibrahim', '🀣 oh my god');
Then after select, i thing it just worked fine !
I don't know if it is requested to enter Emoji as a hexadecimal or other encoding string or just copy it as it is... just correct me if i'm wrong, thank you !
I tried different methods and approaches and found a way that worked for me.
The SQL for the update query:
ALTER DATABASE YOUR_DB_NAME_HERE CHARACTER SET = utf8mb4 COLLATE =
utf8mb4_unicode_ci;
You can see in the table, the emoji's are present
And if you go to this page: https://www.thecookingcat.com/recipes/thai-green-curry.php#comments
You can see the emojis in the comments.
I also have an RSS feed on the site and the emojis are included in the RSS feed XML code.
If anyone searching this in 2022 just follow these steps and no need to do any modification on Database
Name Space
using System.Web;
Your normal text like this :
String encode = "thank you 😊"
encode = HttpUtility.UrlEncode(encode);
It will store in Database like this : "thank+you+%f0%9f%98%8a"
And next fetch that data form your Database and do UrlDecode like this
DataSet ds = "Fetch your Encoded data form your Database";
String decode = HttpUtility.UrlDecode(ds.Tables[0].Rows[i]["YourColumnName"].ToString().Trim());
And your output is :-
decode = "thank you 😊".
It is working fine for me and saved time.

How to save emoji in mySQL? [duplicate]

I have a MySQL database configured with the default collation utf8mb4_general_ci. When I try to insert a row containing an emoji character in the text using the following query
insert into tablename
(column1,column2,column3,column4,column5,column6,column7)
values
('273','3','HdhdhdhπŸ˜œπŸ˜€πŸ˜ŠπŸ˜ƒhzhzhzzhjzj ζˆ‘ηˆ±δ½  ❌',49,1,'2016-09-13 08:02:29','2016-09-13 08:02:29');
MySQL is raising the following error
1366 Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column
'comment' at row 1
1) Database: Change Database default collation as utf8mb4.
2) Table: Change table collation as CHARACTER SET utf8mb4 COLLATE utf8mb4_bin.
Query:
ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
3) Code:
INSERT INTO tablename (column1, column2, column3, column4, column5, column6, column7)
VALUES ('273', '3', 'HdhdhdhπŸ˜œπŸ˜€πŸ˜ŠπŸ˜ƒhzhzhzzhjzj ζˆ‘ηˆ±δ½  ❌', 49, 1, '2016-09-13 08:02:29', '2016-09-13 08:02:29')
4) Set utf8mb4 in database connection:
$database_connection = new mysqli($server, $user, $password, $database_name);
$database_connection->set_charset('utf8mb4');
Step 1, change your database's default charset:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
if the db is not created yet, create it with correct encodings:
CREATE DATABASE database_name DEFAULT CHARSET = utf8mb4 DEFAULT COLLATE = utf8mb4_unicode_ci;
Step 2, set charset when creating table:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or alter table
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE table_name MODIFY field_name TEXT CHARSET utf8mb4;
The command to modify the column is:
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME TYPE;
And we need to use type = BLOB
Example to modify is as under:-
ALTER TABLE messages MODIFY content BLOB;
I checked that latest mySQL and other databases don't need '' to use in command on table_name, column_name etc.
Fetch and Save data:
Directly save the chat content to column and to retrieve data, fetch data as byte array (byte[]) from db column and then convert it to string e.g. (Java code)
new String((byte[]) arr)
Both the databases and tables should have character set utf8mb4 and collation utf8mb4_unicode_ci.
When creating a new database you should use:
CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
If you have an existing database and you want to add support:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
You also need to set the correct character set and collation for your tables:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or change it if you've got existing tables with a lot of data:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Note that utf8_general_ci is no longer recommended best practice. See the related Q & A:
What's the difference between utf8_general_ci and utf8_unicode_ci on Stack Overflow.
If you are using Solr + Mysql + Java, you can use:
This can be Used :
case1: When you don`t want to alter DB.
case2: when you have to import emoticons from your Mysql to Solr core.
In above case this is one of the solutions to store your emoticons in your system.
Steps to use it:
Library used: import java.net.URLDecoder;
import java.net.URLEncoder;
Use urlEncoder to encode your String having emoticons.
Store it in DB without altering the MysqlDB.
You can store it in solr core(decoded form)if you want or you can store
encoded form.
When fetching these emoticons from DB or Solr core you can now decode it
Using urlDecoder.
Code example:
import java.net.URLDecoder;
import java.net.URLEncoder;
public static void main(String[] args) {
//SpringApplication.run(ParticipantApplication.class, args);
System.out.println(encodeStringUrl("πŸ‡ΊπŸ‡ΈπŸ‡¨πŸ‡³πŸ‡―πŸ‡΅πŸ‡©πŸ‡ͺπŸ”³πŸ”ΊπŸ†”πŸ†”πŸ†‘3⃣5⃣3βƒ£β€Όγ€½βž—βž—πŸŽ¦πŸ”†πŸŽ¦πŸ”†β™‹β™β™‹β™β¬…β¬†β¬…β¬…πŸ›‚πŸšΉπŸ›‚πŸ›„πŸš³πŸš¬πŸ’ŠπŸ”§πŸ’ŠπŸ—Ώ "));
System.out.println(decodeStringUrl("Hello+emoticons%2C%2C%F0%9F%98%80%F0%9F%98%81%F0%9F%98%8A%F0%9F%98%8B%F0%9F%98%8E%F0%9F%98%8A%F0%9F%98%8D%E2%98%BA%F0%9F%98%98%E2%98%BA%F0%9F%98%91%F0%9F%98%87%F0%9F%98%98%F0%9F%98%8B%F0%9F%90%84"));
}
public static String encodeStringUrl(String url) {
String encodedUrl =null;
try {
encodedUrl = URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
return encodedUrl;
}
return encodedUrl;
}
public static String decodeStringUrl(String encodedUrl) {
String decodedUrl =null;
try {
decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
return decodedUrl;
}
return decodedUrl;
}
I have updated my database and table to upgraded from utf8 to utf8mb4. But nothing works for me. Then I tried to update column datatype to blob, luckily it worked for me and data has been saved. Even my database and table both are CHARACTER SET utf8 COLLATE utf8_unicode
My answer only adds to Selvamani P answer.
You might also need to change any SET NAMES utf8 queries with SET NAMES utf8mb4. That did the trick for me.
Also, this is a great article to port your website from utf8 to utf8mb4. In particular the article makes 2 good points on indexes and repairing tables after converting them to utf8mb4:
INDEXES
When converting from utf8 to utf8mb4, the maximum length of a column
or index key is unchanged in terms of bytes. Therefore, it is smaller
in terms of characters, because the maximum length of a character is
now four bytes instead of three. [...] The InnoDB storage engine has a maximum index length of 767 bytes, so for utf8 or utf8mb4 columns, you can index a maximum of 255 or 191 characters, respectively. If you currently have utf8 columns with indexes longer than 191 characters, you will need to index a smaller number of characters when using utf8mb4.
REPAIRING TABLES
After upgrading the MySQL server and making the necessary changes
explained above, make sure to repair and optimize all databases and
tables. I didn’t do this right away after upgrading (I didn’t think it
was necessary, as everything seemed to work fine at first glance), and
ran into some weird bugs where UPDATE statements didn’t have any
effect, even though no errors were thrown.
Read more about the queries to repair tables on the article.
I have a good solution to save your time. I also meet the same problem but I could not solve this problem by the first answer.
Your defualt character is utf-8. But emoji needs utf8mb4 to support it.
If you have the permission to revise the configure file of mysql, you can follow this step.
Therefore, do this following step to upgrade your character set ( from utf-8 to utf8mb4).
step 1. open your my.cnf for mysql, add these following lines to your my.cnf.
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
init_connect='SET NAMES utf8mb4'
[mysql]
default-character-set = utf8mb4
[client]
default-character-set = utf8mb4
step2. stop your mysql service, and start mysql service
mysql.server stop
mysql.server start
Finished!
Then you can check your character are changed into utf8mb4.
mysql> SHOW VARIABLES LIKE 'character_set%';
+--------------------------+----------------------------------------------------------+
| Variable_name | Value |
+--------------------------+----------------------------------------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| character_sets_dir | /usr/local/Cellar/mysql#5.7/5.7.29/share/mysql/charsets/ |
+--------------------------+----------------------------------------------------------+
8 rows in set (0.00 sec)
Well, you need not to change the Whole DB Charset. Instead of that you can do it by changing column to blob type.
ALTER TABLE messages MODIFY content BLOB;
There are two ways-->
# Way one
The simplest is to follow below steps:
Step 1:
SET NAMES utf8mb4;
Step 2:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
Step 3:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Step 4:
ALTER TABLE table_name CHANGE column column VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
That's all!!
#Way Two (For Python)
This is a hack and its work like a charm
Step 1:
Encode your string and decode it in ASCII, and save it to your database.
content = 'πŸ₯³πŸ₯³ Content to be save in πŸ₯³πŸ₯³ Database πŸ₯³πŸ₯³'
encoded_content = content.encode('unicode-escape').decode('ASCII'))
This simply store encoded_content string in DB
Step 2:
While fetch this column data to show your user, simply convert it,
here content is the data, fetched from the database.
c = bytes(encoded_content, 'utf-8')
original_content = c.decode('unicode-escape')
Done!!
Emoji support for application having tech stack - mysql, java, springboot, hibernate
Apply below changes in mysql for unicode support.
ALTER DATABASE <database-name> CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE <table-name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
DB Connection - jdbc url change:
jdbc:mysql://localhost:3306/<database-name>?useUnicode=yes&characterEncoding=UTF-8
Note - If the above step is not working please update mysql-connector version to 8.0.15. (mysql 5.7 works with connector version 8.0.15 for unicode support)
The main point hasn't been mentioned in the above answers that,
We need to pass query string with the options "useUnicode=yes" and "characterEncoding=UTF-8" in connection string
Something like this
mysql://USERNAME:PASSWORD#HOSTNAME:PORT/DATABASE_NAME?useUnicode=yes&characterEncoding=UTF-8
The simplest solution what works for me is to store the data as json_encode.
later when you retrieve just make sure you json_decode it.
Here you don't have to change the collation or the character set of the database and the table.
For Rails, next to the accepted answer, don't forget to add:
encoding: utf8mb4
collation: utf8mb4_bin
to your database.yml
For anyone trying to solve this on a managed MySQL instance (in my case on AWS RDS), the easiest way was to modify the parameter group and set the server character set and collation to be utf8mb4 and utf8mb4_bin, respectively. After rebooting the server, a quick query verifies the settings for system databases and any newly created ones:
SELECT * FROM information_schema.SCHEMATA S;
If you are inserting using PHP, and you have followed the various ALTER database and ALTER table options above, make sure your php connection's charset is utf8mb4.
Example of connection string:
$this->pdo = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8mb4", etc etc
Notice the "charset" is utf8mb4, not just utf8!
Today I am facing the same question, but solutions in other answers don't work for me. Here is my solution.
First of all, changing charset in mysql/my.ini, database, and the table is necessary, as described in other answers.
Second, if you have created your tables before you want to saving emoji, you can use
SHOW FULL COLUMNS FROM `yourcolumn`;
To check whether the column you want to save emoji is set in utf8mb4. You can find that most of your columns are still in utf8 charset.
Use
ALTER TABLE `yourtable` CHANGE `yourcolumn` `yourcolumn` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
I'm facing this issue when upgrading MySQL 5.0 to MySQL 8.0 AWS RDS, trying many things finally what works for me share with you folks.
Error:
Warning: PDOStatement::execute(): SQLSTATE[HY000]: General error:
3988 Conversion from collation utf8_unicode_ci into utf8mb4_general_ci
impossible for parameter in /var/www/html/pdo_con.php on line 87
Array (
[0] => HY000
[1] => 3988
[2] => Conversion from collation utf8_unicode_ci into utf8mb4_general_ci impossible for parameter )
Backend: PHP5/php7 + PDO is giving trouble.
Solution: only two thing needs to do
Add a code in line after your pdo connection
$conn->exec("set names utf8mb4");
where $conn is connection handler in PDO
Alter the table and set charset utf8mb4 and collate utf8mb4_unicode_ci.
ALTER TABLE mytable CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
This command will change your every column charset to utf8mb4 and collation too.
Put this right before your database call:
mysqli_set_charset($db, "utf8mb4");
This will allow you to input emojis directly into the database table that has been set to Collation: utfmb4_bin. Make sure to set your column to utfmb4 as well.
Hi my friends
This is how I solved this problem and I was happy to teach it to you as well
I am in the Android application
I encrypt a string containing text and emoj and send it to the server and save it in the mysql table and after receiving it from the server I decrypt it and display it in the textview.
encoded and decoded my message before request and after response:
I send Android app messages to mysql via pdo through this method and receive them with pdo. And I have no problem.
I think it was a good way. Please like
Thankful
public void main()
{
String message="hi mester ali moradi 🌦️🌦️ how are you ?";
String encoded_message=encodeStringUrl(message);
String decode_message=decodeStringUrl(encoded_message);
}
public static String encodeStringUrl(String message) {
String encodedUrl =null;
try {
encodedUrl = URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
return encodedUrl;
}
return encodedUrl;
}
public static String decodeStringUrl(String message) {
String decodedUrl =null;
try {
decodedUrl = URLDecoder.decode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
return decodedUrl;
}
return decodedUrl;
}
message : hi mester ali moradi 🌦️🌦️ how are you ?
encoded : ghgh%F0%9F%98%AE%F0%9F%A4%90%F0%9F%98%A5
decoded :hi mester ali moradi 🌦️🌦️ how are you ?
If you use command line interface for inserting sql file to database.
Be sure your table charset utf8mb4 and column collation utf8mb4_unicode_ci or utf8mb4_bin
mysql -u root -p123456 my_database < profiles.sql
ERROR 1366 (HY000) at line 1679: Incorrect string value: '\xF0\x9F\x98\x87\xF0\x9F...' for column 'note' at row 328
we can solve the problem with this parameter
--default-character-set=name (Set the default character set)
mysql -u root -p123456 --default-character-set=utf8mb4 my_database < profiles.sql
Actually i'm using mysql Ver 8.0.23
I had created the both Database and the Table, without Altering them :
mysql> CREATE DATABASE tp2;
Query OK, 1 row affected (0.30 sec)
mysql> INSERT INTO tweetsRep(username, content) VALUES ('ibrahim', '🀣 oh my god');
Then after select, i thing it just worked fine !
I don't know if it is requested to enter Emoji as a hexadecimal or other encoding string or just copy it as it is... just correct me if i'm wrong, thank you !
I tried different methods and approaches and found a way that worked for me.
The SQL for the update query:
ALTER DATABASE YOUR_DB_NAME_HERE CHARACTER SET = utf8mb4 COLLATE =
utf8mb4_unicode_ci;
You can see in the table, the emoji's are present
And if you go to this page: https://www.thecookingcat.com/recipes/thai-green-curry.php#comments
You can see the emojis in the comments.
I also have an RSS feed on the site and the emojis are included in the RSS feed XML code.
If anyone searching this in 2022 just follow these steps and no need to do any modification on Database
Name Space
using System.Web;
Your normal text like this :
String encode = "thank you 😊"
encode = HttpUtility.UrlEncode(encode);
It will store in Database like this : "thank+you+%f0%9f%98%8a"
And next fetch that data form your Database and do UrlDecode like this
DataSet ds = "Fetch your Encoded data form your Database";
String decode = HttpUtility.UrlDecode(ds.Tables[0].Rows[i]["YourColumnName"].ToString().Trim());
And your output is :-
decode = "thank you 😊".
It is working fine for me and saved time.

How to make full support of emoji in MySQL? [duplicate]

I have a MySQL database configured with the default collation utf8mb4_general_ci. When I try to insert a row containing an emoji character in the text using the following query
insert into tablename
(column1,column2,column3,column4,column5,column6,column7)
values
('273','3','HdhdhdhπŸ˜œπŸ˜€πŸ˜ŠπŸ˜ƒhzhzhzzhjzj ζˆ‘ηˆ±δ½  ❌',49,1,'2016-09-13 08:02:29','2016-09-13 08:02:29');
MySQL is raising the following error
1366 Incorrect string value: '\xF0\x9F\x98\x83\xF0\x9F...' for column
'comment' at row 1
1) Database: Change Database default collation as utf8mb4.
2) Table: Change table collation as CHARACTER SET utf8mb4 COLLATE utf8mb4_bin.
Query:
ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
3) Code:
INSERT INTO tablename (column1, column2, column3, column4, column5, column6, column7)
VALUES ('273', '3', 'HdhdhdhπŸ˜œπŸ˜€πŸ˜ŠπŸ˜ƒhzhzhzzhjzj ζˆ‘ηˆ±δ½  ❌', 49, 1, '2016-09-13 08:02:29', '2016-09-13 08:02:29')
4) Set utf8mb4 in database connection:
$database_connection = new mysqli($server, $user, $password, $database_name);
$database_connection->set_charset('utf8mb4');
Step 1, change your database's default charset:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
if the db is not created yet, create it with correct encodings:
CREATE DATABASE database_name DEFAULT CHARSET = utf8mb4 DEFAULT COLLATE = utf8mb4_unicode_ci;
Step 2, set charset when creating table:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or alter table
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE table_name MODIFY field_name TEXT CHARSET utf8mb4;
The command to modify the column is:
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME TYPE;
And we need to use type = BLOB
Example to modify is as under:-
ALTER TABLE messages MODIFY content BLOB;
I checked that latest mySQL and other databases don't need '' to use in command on table_name, column_name etc.
Fetch and Save data:
Directly save the chat content to column and to retrieve data, fetch data as byte array (byte[]) from db column and then convert it to string e.g. (Java code)
new String((byte[]) arr)
Both the databases and tables should have character set utf8mb4 and collation utf8mb4_unicode_ci.
When creating a new database you should use:
CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
If you have an existing database and you want to add support:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
You also need to set the correct character set and collation for your tables:
CREATE TABLE IF NOT EXISTS table_name (
...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;
or change it if you've got existing tables with a lot of data:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Note that utf8_general_ci is no longer recommended best practice. See the related Q & A:
What's the difference between utf8_general_ci and utf8_unicode_ci on Stack Overflow.
If you are using Solr + Mysql + Java, you can use:
This can be Used :
case1: When you don`t want to alter DB.
case2: when you have to import emoticons from your Mysql to Solr core.
In above case this is one of the solutions to store your emoticons in your system.
Steps to use it:
Library used: import java.net.URLDecoder;
import java.net.URLEncoder;
Use urlEncoder to encode your String having emoticons.
Store it in DB without altering the MysqlDB.
You can store it in solr core(decoded form)if you want or you can store
encoded form.
When fetching these emoticons from DB or Solr core you can now decode it
Using urlDecoder.
Code example:
import java.net.URLDecoder;
import java.net.URLEncoder;
public static void main(String[] args) {
//SpringApplication.run(ParticipantApplication.class, args);
System.out.println(encodeStringUrl("πŸ‡ΊπŸ‡ΈπŸ‡¨πŸ‡³πŸ‡―πŸ‡΅πŸ‡©πŸ‡ͺπŸ”³πŸ”ΊπŸ†”πŸ†”πŸ†‘3⃣5⃣3βƒ£β€Όγ€½βž—βž—πŸŽ¦πŸ”†πŸŽ¦πŸ”†β™‹β™β™‹β™β¬…β¬†β¬…β¬…πŸ›‚πŸšΉπŸ›‚πŸ›„πŸš³πŸš¬πŸ’ŠπŸ”§πŸ’ŠπŸ—Ώ "));
System.out.println(decodeStringUrl("Hello+emoticons%2C%2C%F0%9F%98%80%F0%9F%98%81%F0%9F%98%8A%F0%9F%98%8B%F0%9F%98%8E%F0%9F%98%8A%F0%9F%98%8D%E2%98%BA%F0%9F%98%98%E2%98%BA%F0%9F%98%91%F0%9F%98%87%F0%9F%98%98%F0%9F%98%8B%F0%9F%90%84"));
}
public static String encodeStringUrl(String url) {
String encodedUrl =null;
try {
encodedUrl = URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
return encodedUrl;
}
return encodedUrl;
}
public static String decodeStringUrl(String encodedUrl) {
String decodedUrl =null;
try {
decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
return decodedUrl;
}
return decodedUrl;
}
I have updated my database and table to upgraded from utf8 to utf8mb4. But nothing works for me. Then I tried to update column datatype to blob, luckily it worked for me and data has been saved. Even my database and table both are CHARACTER SET utf8 COLLATE utf8_unicode
My answer only adds to Selvamani P answer.
You might also need to change any SET NAMES utf8 queries with SET NAMES utf8mb4. That did the trick for me.
Also, this is a great article to port your website from utf8 to utf8mb4. In particular the article makes 2 good points on indexes and repairing tables after converting them to utf8mb4:
INDEXES
When converting from utf8 to utf8mb4, the maximum length of a column
or index key is unchanged in terms of bytes. Therefore, it is smaller
in terms of characters, because the maximum length of a character is
now four bytes instead of three. [...] The InnoDB storage engine has a maximum index length of 767 bytes, so for utf8 or utf8mb4 columns, you can index a maximum of 255 or 191 characters, respectively. If you currently have utf8 columns with indexes longer than 191 characters, you will need to index a smaller number of characters when using utf8mb4.
REPAIRING TABLES
After upgrading the MySQL server and making the necessary changes
explained above, make sure to repair and optimize all databases and
tables. I didn’t do this right away after upgrading (I didn’t think it
was necessary, as everything seemed to work fine at first glance), and
ran into some weird bugs where UPDATE statements didn’t have any
effect, even though no errors were thrown.
Read more about the queries to repair tables on the article.
I have a good solution to save your time. I also meet the same problem but I could not solve this problem by the first answer.
Your defualt character is utf-8. But emoji needs utf8mb4 to support it.
If you have the permission to revise the configure file of mysql, you can follow this step.
Therefore, do this following step to upgrade your character set ( from utf-8 to utf8mb4).
step 1. open your my.cnf for mysql, add these following lines to your my.cnf.
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_general_ci
init_connect='SET NAMES utf8mb4'
[mysql]
default-character-set = utf8mb4
[client]
default-character-set = utf8mb4
step2. stop your mysql service, and start mysql service
mysql.server stop
mysql.server start
Finished!
Then you can check your character are changed into utf8mb4.
mysql> SHOW VARIABLES LIKE 'character_set%';
+--------------------------+----------------------------------------------------------+
| Variable_name | Value |
+--------------------------+----------------------------------------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| character_sets_dir | /usr/local/Cellar/mysql#5.7/5.7.29/share/mysql/charsets/ |
+--------------------------+----------------------------------------------------------+
8 rows in set (0.00 sec)
Well, you need not to change the Whole DB Charset. Instead of that you can do it by changing column to blob type.
ALTER TABLE messages MODIFY content BLOB;
There are two ways-->
# Way one
The simplest is to follow below steps:
Step 1:
SET NAMES utf8mb4;
Step 2:
ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
Step 3:
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Step 4:
ALTER TABLE table_name CHANGE column column VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
That's all!!
#Way Two (For Python)
This is a hack and its work like a charm
Step 1:
Encode your string and decode it in ASCII, and save it to your database.
content = 'πŸ₯³πŸ₯³ Content to be save in πŸ₯³πŸ₯³ Database πŸ₯³πŸ₯³'
encoded_content = content.encode('unicode-escape').decode('ASCII'))
This simply store encoded_content string in DB
Step 2:
While fetch this column data to show your user, simply convert it,
here content is the data, fetched from the database.
c = bytes(encoded_content, 'utf-8')
original_content = c.decode('unicode-escape')
Done!!
Emoji support for application having tech stack - mysql, java, springboot, hibernate
Apply below changes in mysql for unicode support.
ALTER DATABASE <database-name> CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE <table-name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
DB Connection - jdbc url change:
jdbc:mysql://localhost:3306/<database-name>?useUnicode=yes&characterEncoding=UTF-8
Note - If the above step is not working please update mysql-connector version to 8.0.15. (mysql 5.7 works with connector version 8.0.15 for unicode support)
The main point hasn't been mentioned in the above answers that,
We need to pass query string with the options "useUnicode=yes" and "characterEncoding=UTF-8" in connection string
Something like this
mysql://USERNAME:PASSWORD#HOSTNAME:PORT/DATABASE_NAME?useUnicode=yes&characterEncoding=UTF-8
The simplest solution what works for me is to store the data as json_encode.
later when you retrieve just make sure you json_decode it.
Here you don't have to change the collation or the character set of the database and the table.
For Rails, next to the accepted answer, don't forget to add:
encoding: utf8mb4
collation: utf8mb4_bin
to your database.yml
For anyone trying to solve this on a managed MySQL instance (in my case on AWS RDS), the easiest way was to modify the parameter group and set the server character set and collation to be utf8mb4 and utf8mb4_bin, respectively. After rebooting the server, a quick query verifies the settings for system databases and any newly created ones:
SELECT * FROM information_schema.SCHEMATA S;
If you are inserting using PHP, and you have followed the various ALTER database and ALTER table options above, make sure your php connection's charset is utf8mb4.
Example of connection string:
$this->pdo = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8mb4", etc etc
Notice the "charset" is utf8mb4, not just utf8!
Today I am facing the same question, but solutions in other answers don't work for me. Here is my solution.
First of all, changing charset in mysql/my.ini, database, and the table is necessary, as described in other answers.
Second, if you have created your tables before you want to saving emoji, you can use
SHOW FULL COLUMNS FROM `yourcolumn`;
To check whether the column you want to save emoji is set in utf8mb4. You can find that most of your columns are still in utf8 charset.
Use
ALTER TABLE `yourtable` CHANGE `yourcolumn` `yourcolumn` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
I'm facing this issue when upgrading MySQL 5.0 to MySQL 8.0 AWS RDS, trying many things finally what works for me share with you folks.
Error:
Warning: PDOStatement::execute(): SQLSTATE[HY000]: General error:
3988 Conversion from collation utf8_unicode_ci into utf8mb4_general_ci
impossible for parameter in /var/www/html/pdo_con.php on line 87
Array (
[0] => HY000
[1] => 3988
[2] => Conversion from collation utf8_unicode_ci into utf8mb4_general_ci impossible for parameter )
Backend: PHP5/php7 + PDO is giving trouble.
Solution: only two thing needs to do
Add a code in line after your pdo connection
$conn->exec("set names utf8mb4");
where $conn is connection handler in PDO
Alter the table and set charset utf8mb4 and collate utf8mb4_unicode_ci.
ALTER TABLE mytable CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
This command will change your every column charset to utf8mb4 and collation too.
Put this right before your database call:
mysqli_set_charset($db, "utf8mb4");
This will allow you to input emojis directly into the database table that has been set to Collation: utfmb4_bin. Make sure to set your column to utfmb4 as well.
Hi my friends
This is how I solved this problem and I was happy to teach it to you as well
I am in the Android application
I encrypt a string containing text and emoj and send it to the server and save it in the mysql table and after receiving it from the server I decrypt it and display it in the textview.
encoded and decoded my message before request and after response:
I send Android app messages to mysql via pdo through this method and receive them with pdo. And I have no problem.
I think it was a good way. Please like
Thankful
public void main()
{
String message="hi mester ali moradi 🌦️🌦️ how are you ?";
String encoded_message=encodeStringUrl(message);
String decode_message=decodeStringUrl(encoded_message);
}
public static String encodeStringUrl(String message) {
String encodedUrl =null;
try {
encodedUrl = URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
return encodedUrl;
}
return encodedUrl;
}
public static String decodeStringUrl(String message) {
String decodedUrl =null;
try {
decodedUrl = URLDecoder.decode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
return decodedUrl;
}
return decodedUrl;
}
message : hi mester ali moradi 🌦️🌦️ how are you ?
encoded : ghgh%F0%9F%98%AE%F0%9F%A4%90%F0%9F%98%A5
decoded :hi mester ali moradi 🌦️🌦️ how are you ?
If you use command line interface for inserting sql file to database.
Be sure your table charset utf8mb4 and column collation utf8mb4_unicode_ci or utf8mb4_bin
mysql -u root -p123456 my_database < profiles.sql
ERROR 1366 (HY000) at line 1679: Incorrect string value: '\xF0\x9F\x98\x87\xF0\x9F...' for column 'note' at row 328
we can solve the problem with this parameter
--default-character-set=name (Set the default character set)
mysql -u root -p123456 --default-character-set=utf8mb4 my_database < profiles.sql
Actually i'm using mysql Ver 8.0.23
I had created the both Database and the Table, without Altering them :
mysql> CREATE DATABASE tp2;
Query OK, 1 row affected (0.30 sec)
mysql> INSERT INTO tweetsRep(username, content) VALUES ('ibrahim', '🀣 oh my god');
Then after select, i thing it just worked fine !
I don't know if it is requested to enter Emoji as a hexadecimal or other encoding string or just copy it as it is... just correct me if i'm wrong, thank you !
I tried different methods and approaches and found a way that worked for me.
The SQL for the update query:
ALTER DATABASE YOUR_DB_NAME_HERE CHARACTER SET = utf8mb4 COLLATE =
utf8mb4_unicode_ci;
You can see in the table, the emoji's are present
And if you go to this page: https://www.thecookingcat.com/recipes/thai-green-curry.php#comments
You can see the emojis in the comments.
I also have an RSS feed on the site and the emojis are included in the RSS feed XML code.
If anyone searching this in 2022 just follow these steps and no need to do any modification on Database
Name Space
using System.Web;
Your normal text like this :
String encode = "thank you 😊"
encode = HttpUtility.UrlEncode(encode);
It will store in Database like this : "thank+you+%f0%9f%98%8a"
And next fetch that data form your Database and do UrlDecode like this
DataSet ds = "Fetch your Encoded data form your Database";
String decode = HttpUtility.UrlDecode(ds.Tables[0].Rows[i]["YourColumnName"].ToString().Trim());
And your output is :-
decode = "thank you 😊".
It is working fine for me and saved time.

Categories