Php+mysql do web site development is usually encountered in the browser output Chinese characters garbled, this problem is mainly due to HTML content encoding, PHP file encoding and MySQL database encoding these three inconsistencies caused. Let's take UTF-8 as an example to explain how to unify the relationship between the three.
Add a php file named test_charset.php and save the following code to the file:
<?php $charset = "UTF8"; $con = mysql_connect ("localhost", "root", ""); mysql_query ("SET character_set_connection= $charset, character_set_results= $charset, Character_set_client=binary", $con); mysql_select_db ("Ecshop", $con); $sql = "Select user_name, email from ecs_admin_user WHERE user_id = 4"; $result = mysql_query ($sql, $con); $array = Mysql_fetch_array ($result, MYSQL_ASSOC); Mysql_close ($con); $name = $array ["user_name"]; $email = $array ["email"];? >
HTML content Encoding
The 22nd line above:
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
Here we specify that the browser uses UTF-8 encoding when parsing the HTML. If this is not specified, the browser will use its own default encoding. Different browser default codes will vary, such as IE6 is Gb2312,firefox is UTF-8. Therefore, the above code if there is no 22nd line, in Firefox will show normal, in IE6 will show garbled.
PHP file encoding
The PHP file itself also needs to have a consistent encoding. How to check your PHP file is what kind of encoding it? Windows is easy to handle with Notepad. Open the php file with Notepad and choose Save As ... from the File menu, such as:
At the bottom of the dialog box that opens, there is an "encoding" option, and the current encoding of the file is now visible. If you want to change to another encoding, select it from the drop-down list box and click the "Save" button.
MySQL database encoding
After the database connection succeeds, you should execute a set encoding instruction the first time, such as line 7th of the code above. Here is a point to pay special attention, UTF-8 is the normal wording, but in MySQL, Jane wrote UTF8, there is no horizontal line in the middle. The 7th line above is to set the connection encoding to UTF8 ($charset = "UTF8") instead of utf-8. Attached here is a complete implementation of the Ecshop Setup connection code for your reference. The file is includes/cls_mysql.php.
function Set_mysql_charset ($charset) {/ * If the MySQL version is 4.1+ or higher, you need to initialize the character set * /if ($this->version > ' 4.1 ') c2/>{ if (In_array (Strtolower ($charset), Array (' GBK ', ' Big5 ', ' utf-8 ', ' UTF8 '))) { $charset = Str_replace ('-', ', $charset); } if ($charset! = ' latin1 ') { mysql_query ("SET character_set_connection= $charset, character_set_results=$ CharSet, Character_set_client=binary ", $this->link_id);}}}