Home >Backend Development >PHP Tutorial >How to Handle Unicode Strings (e.g., Hindi) in PHP and MySQL?

How to Handle Unicode Strings (e.g., Hindi) in PHP and MySQL?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 20:44:04180browse

How to Handle Unicode Strings (e.g., Hindi) in PHP and MySQL?

Storing and Displaying Unicode Strings (हिन्दी) Using PHP and MySQL

Storing and displaying non-Latin character sets like Hindi in a web application can be challenging, but it is essential to support a wider audience. Here's a comprehensive guide on how to achieve this using PHP and MySQL:

Setting Database Parameters

  • Ensure your MySQL database has a correct character set and collation by executing these commands:

    <code class="sql">SET character_set_database=utf8;
    SET collation_database=utf8_unicode_ci;</code>
  • In the table definition, specify the column for storing unicode data as VARCHAR with CHARACTER SET utf8mb4 and COLLATE utf8mb4_unicode_ci.

Data Insertion and Retrieval

  • When inserting data, directly input the Unicode string into the database without any modifications.
  • To retrieve the data in PHP, execute the following query before fetching:

    <code class="php">mysql_query("SET NAMES utf8");</code>
  • Use utf8_encode() to convert the Unicode string to UTF-8 format before displaying it.

PHP Script Example

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

// Database connection
include('connection.php');

// Execute query with UTF-8 encoding
mysql_query("SET NAMES utf8");
$result = mysql_query("SELECT * FROM `hindi`");

// Fetch and display results
while ($row = mysql_fetch_row($result)) {
    echo utf8_encode($row[0]);
}
?></code>

Database Dump

The database dump should resemble the following:

<code class="sql">CREATE TABLE `hindi` (
  `data` VARCHAR(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL
);

INSERT INTO `hindi` VALUES ('सूर्योदय');</code>

Troubleshooting

  • Ensure that the HTML head section includes the correct character set:

    <code class="html"><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></code>
  • Verify that the web server is properly configured to handle Unicode strings.
  • If problems persist, consult relevant documentation or seek assistance from forums like StackOverflow.

The above is the detailed content of How to Handle Unicode Strings (e.g., Hindi) 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