Home  >  Article  >  Backend Development  >  How to Store and Display Unicode (Hindi) Strings in PHP and MySQL?

How to Store and Display Unicode (Hindi) Strings in PHP and MySQL?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 00:56:03113browse

How to Store and Display Unicode (Hindi) Strings in PHP and MySQL?

Storing and Displaying Unicode String (हिन्दी) in PHP and MySQL

When attempting to store and display Hindi text in a MySQL database using PHP, you may encounter encoding issues. To resolve these issues, ensure the following steps are taken:

  • Set MySQL Database Encoding: Configure the MySQL database to use UTF-8 character encoding. This can be done by executing the following SQL commands:
<code class="sql">SET NAMES utf8;
ALTER DATABASE YOUR_DATABASE_NAME CHARACTER SET = utf8 COLLATE = utf8_bin;</code>
  • Create Field with UTF-8 Encoding: In the table, create a VARCHAR field and specify the character set as UTF-8.
  • Insert Hindi Text Directly: Copy the Hindi text directly into the database without encoding.
  • Retrieve Data Using PHP: Fetch the Hindi text using PHP and apply UTF-8 encoding before displaying it on the webpage. For example:
<code class="php">$result = mysql_query("SELECT * FROM your_table");

while ($row = mysql_fetch_assoc($result)) {
  echo utf8_encode($row['hindi_column']);
}</code>
  • Set HTML Header: Include a meta tag in the HTML head section to specify the UTF-8 character set:
<code class="html"><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></code>

Additionally, you can set the content type in your PHP script using:

<code class="php">header('Content-Type: text/html; charset=utf-8');</code>

Understanding the Solution Script:

The provided script works without specifying a meta tag or header info because it explicitly sets the NAMES to utf8 using the mysql_query() function. This ensures that the connection and queries use the UTF-8 character set, enabling proper display of Hindi text.

Tips:

  • Test these settings by inputting unicode data using PhpMyAdmin or directly using a PHP script.
  • Set the NAMES, CHARACTER SET when creating MySQL connections, executing queries, and selecting data to ensure consistent encoding throughout the process.

The above is the detailed content of How to Store and Display Unicode (Hindi) Strings in PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn