MySQL - insert japanese from PHP - Encoding Troubl

2019-02-26 05:50发布

问题:

I'm trying to insert some japanese words in a mysql table! If I insert 'こんにちは' using phpMyAdmin, the word is displayed fine from phpMyAdmin. But if I try to insert it through php, as follow:

mysql_connect($Host, $User, $Password);
mysql_select_db($Database);

$qry = "INSERT INTO table VALUES (0 , 'こんにちは')";

echo mysql_query($qry);

In phpMyAdmin i see "ã“ã‚“ã«ã¡ã¯" ... why?

And if I try to fetch from the database:

$arr = mysql_fetch_array(mysql_query("SELECT * FROM table where id = 1"));

echo $arr[1];

The browser shows nothing!!!

How can I solve?

Thank you in advance for your help!!!


~EDIT~

My database collation is setup to utf8_general_ci


~EDIT 2~

I don't need to display the output on an HTML page, but the japanese words are printed on a XML page whose encoding is setup to UTF-8.

$plist = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$plist .= "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n";
$plist .= "<plist version=\"1.0\">\n";
$plist .= "<array>\n";
$plist .= "\t<dict>\n";
$plist .= "\t\t<key>test</key>\n";
$plist .= "\t\t<string>".$arr[1]."</string>\n";
$plist .= "\t</dict>\n";
$plist .= "</array>\n";
$plist .= "</plist>";

echo $plist;

the output of this code is:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>test</key>
        <string></string>
    </dict>
</array>
</plist>

So, there is no value for the key "test" ... what can I do? Thanks!


~ SOLVED ~

Problems solved using the function mysql_set_charset() after connecting to the database!

回答1:

try this before the insert query

mysql_query("SET NAMES utf8");

Also not sure if you set the proper charset of the database, and of the web page.

Charset in HTML Head section?

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

and/or something like

   header( 'Content-Type: text/html; charset=utf-8' );

Followings will help you get more ideas how to do it .. if something doesnt work commment back.

check more here on SO

Storing and displaying unicode string (हिन्दी) using PHP and MySQL

How to make MySQL handle UTF-8 properly

setting utf8 with mysql through php

PHP/MySQL with encoding problems



回答2:

you must set you Database Charset to utf8 and database collation to utf8_general_ci (or other utf8 collation) then I think your problem solved