I'm trying to use UTF-8, but I'm not sure if I'm doing everything correctly. I'm trying to write JSON to a database using PHP, retrieve it via AJAX, and display it in HTML.
So, firstly, I save my PHP & JS files in UTF-8 format.
I add the开发者_如何学编程 UTF-8 header to my PHP files. The database table is created as follows:CREATE TABLE `achieve` (
`id` bigint(20) unsigned NOT NULL,
`json` mediumtext,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
When saving to the database, I use the following PHP code:
$json=$_REQUEST["json"];
...
$result = mysql_query($query);
if ($line = mysql_fetch_assoc($result))
$query = sprintf(
'UPDATE achieve SET json = "%s" WHERE id=%d ',
mysql_real_escape_string($json), $ID
);
else
$query = sprintf(
'INSERT INTO achieve (id, json) VALUES (%d, "%s") ',
$FBID, mysql_real_escape_string($json)
);
mysql_query($query);
When I display the value in HTML, it still seems to be in the wrong encoding. Any idea what I'm missing?
Can you verify that the data is being stored correctly, using a database browser such as PHPMyAdmin or such? Try executing these two queries beforehand:
SET NAMES utf8
SET CHARACTER SET utf8
Sorry for wasting everyone's time here... I figured out the answer to my question eventually! I had been using escape() in JavaScript before saving my JSON to the database. Apparently this only works with ASCII, and one should be using encodeURIComponent() instead. Now it works!
精彩评论