Home >Database >Mysql Tutorial >How Can I Store and Display Unicode Strings in MySQL and PHP?

How Can I Store and Display Unicode Strings in MySQL and PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 00:49:11548browse

How Can I Store and Display Unicode Strings in MySQL and PHP?

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

To store and display Unicode strings like "सूर्योदय" in a MySQL database and retrieve them using PHP, follow these steps:

Database Setup:

  • Create a database with UTF-8 encoding and collation (e.g., UTF-8 general_ci).
  • Add a VARCHAR field to your table with the UTF-8 charset property.

Storing the String:

  • Insert the Unicode string directly into the database using a PHP script.
  • Ensure your PHP script sets the character set properties correctly:

    • mysql_set_charset('utf8'); before executing your query
    • Use utf8mb4 as your character set for better Unicode support

Retrieving and Displaying the String:

  • Use mysql_query("SET NAMES utf8"); at the beginning of your PHP script to set the character set for the connection.
  • Fetch the string from the database using a query.
  • To display the Unicode string correctly in a web browser, use echo(utf8_decode($string)). This will convert the encoded UTF-8 string into the corresponding Unicode characters.

Additional Tips:

  • Set the Content-Type for your HTML document to UTF-8 using:

    • or use header('Content-Type: text/html; charset=utf-8'); in PHP
  • Use UTF-8 compatible PHP functions for string manipulation, such as htmlentities() and htmlspecialchars().

Alternative Solution:

  • Store the Unicode string in the database as its UTF-8 encoded counterpart (e.g., सूर्योदय for "सूर्योदय").
  • Retreive the encoded string from the database and then decode it for display using html_entity_decode().

Note:

The provided sample script uses the older mysql_ functions. For newer PHP versions, use the mysqli or PDO extensions for database interactions. The syntax will slightly differ, but the overall principles remain the same.

The above is the detailed content of How Can I Store and Display Unicode Strings in MySQL and PHP?. 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