Question

i am trying to store Chinese character in mysql database,but it store some messy character. Please help.. here is my code-

<?php header("Content-Type: text/html; charset=UTF-8");
if(isset($_POST['submit']))
{
$conn=mysql_connect("localhost","root","") or die("CONNECTION FAILED"); 
 $db=mysql_select_db("mytest",$conn) or die("DATABASE DOES NOT EXISTS");
 mysql_query("SET character_set_client=utf8", $conn);
  mysql_query("SET character_set_connection=utf8", $conn);
mysql_query("INSERT INTO tbl_test(id,name)
VALUES (null, '".$_POST['fname']."')") or die(mysql_error());
?>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="" method="post">
Name: <input type="text" name="fname" />
<input type="submit" name="submit" />
</form> 
</body>
</html>
Was it helpful?

Solution

welcome to Charset Hell.

In PHP, to use a certain character set, absolutely everything has to be in the same character set. If you're intending to use UTF8, then everything needs to be UTF8. The database needs to be using UTF8 as its charset, the connection between the script and the DB needs to be UTF8 (it looks like you've taken care of this already), the PHP script itself needs to be saved as a UTF8 file (without a BOM, because having a BOM will just cause you more trouble later), and the browser has to be viewing the page generated by the script in UTF8 (you should use the header() command to send a content-type header that specifies this).

If any link in the chain is not UTF8, you'll end up getting junk displayed for certain character sequences that are valid in one character encoding, but not another. Whilst PHP has functionality for converting between charsets, it gets messy quickly and is best avoided.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top