简体   繁体   中英

PHP Encoding (Guess UTF-8)

I'm programming a system so an user can edit what he posts. Simplified it's a textarea/input field which stores in a database and a page that retrieves it. The problem is, I think the encoding isn't okay, because strings are stored in the database like "é" or something (phpmyadmin view).

Insert page:

  1. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  2. I insert mysql_real_escape_string($_POST['field']);

Output page:

  1. Object from database.
  2. htmlspecialchars($object->field);

But expected is: Output page:

  1. Object from database.
  2. htmlentities($object->field); , right?

Why isn't the data stored in MySql properly?

If your database encoding is set to utf-8, you need to set the tranfer encoding to utf-8, too. To do that you have to query

SET NAMES utf8;

before inserting into the table.

Is the database connection UTF-8 ? Bear in mind, that's not the default encoding, you have to explicitly set it yourself.

You have to tell htmlentities that you feed it UTF-8:

htmlentities($text, ENT_COMPAT, "UTF-8");

Otherwise it assumes it gets ISO-8859-1.

This site http://developer.loftdigital.com/blog/php-utf-8-cheatsheet should give you an idea of whats needed for UTF-8 in PHP and MySQL.

Oh and dont forget to use these after connecting to your DB:

mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET 'utf8'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM