Storing Unicode Data for Hindi Language in MySQL
When dealing with data that includes non-English characters, such as Hindi, it becomes crucial to store and retrieve it accurately in Unicode format to maintain its readability.
Choosing the Right Character Set and Collation
To ensure compatibility with Hindi characters, opt for the 'utf8' character set and 'utf8_general_ci' collation. This allows MySQL to store and manipulate Unicode data correctly.
Altering Table Field for Unicode Support
If you have a table with an existing field that needs to accommodate Hindi text, modify its definition using the following syntax:
ALTER TABLE `<table_name>` CHANGE `<field_name>` `<field_name>` VARCHAR(100) CHARSET utf8 COLLATE utf8_general_ci DEFAULT '' NOT NULL;
Setting Character Set for Connection
Before interacting with the database, establish the 'utf8' character set to ensure proper encoding:
mysql_set_charset('utf8');
Inserting and Retrieving Hindi Text
With the character set set, insert Hindi text into your database:
mysql_query("INSERT INTO ...."); // Replace with your query
Retrieve the inserted text by executing:
mysql_query("SELECT * FROM ...."); // Replace with your query
Handling Unicode Output
To display Hindi text correctly in a web browser, set the content type of the page using a meta tag:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Example
The following code snippet demonstrates the storage and retrieval of Hindi text in the database:
// Set character set mysql_set_charset('utf8'); // Insert Hindi text mysql_query("INSERT INTO `hindi_text` (`text`) VALUES ('नवीन खेतिहर उपकरण')"); // Retrieve Hindi text $result = mysql_query("SELECT `text` FROM `hindi_text`"); $hindiText = mysql_fetch_assoc($result)['text']; // Output Hindi text with proper content type echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . $hindiText . '
';
By following these steps, you can ensure the accurate storage and readability of Hindi language data in MySQL.
The above is the detailed content of How to Store and Retrieve Hindi Language Data in MySQL Using Unicode?. For more information, please follow other related articles on the PHP Chinese website!