Home > Article > Backend Development > Solution to garbled characters when php reads and writes mysql data
If garbled characters appear when PHP reads and writes MySQL data, it is usually caused by inconsistencies in database encoding, database table encoding, database table field encoding, and PHP output page encoding. You can refer to the solutions introduced in this article.
This article uses UTF-8 encoding as an example: 1. First, make sure the mysql connection statement contains: mysql_query(“SET NAMES ‘utf8′”); mysql_query(“SET CHARACTER_SET_CLIENT=utf8″); mysql_query(“SET CHARACTER_SET_RESULTS=utf8″); The complete connection code is as follows: $host=”localhost”; $user=”root”; $pwd=”root”; $dbname=”wordpress”; $link = mysql_connect($host, $user, $pwd)or die(“Could not connect: ” . mysql_error()); mysql_select_db($dbname, $link) or die (‘Can’t use wordpress : ‘ . mysql_error()); mysql_query(“SET NAMES ‘utf8′”); mysql_query(“SET CHARACTER_SET_CLIENT=utf8″); mysql_query(“SET CHARACTER_SET_RESULTS=utf8″); 2. Check whether the database coding, database table coding, database field coding, and page coding are consistent 3. If there are still garbled characters, please check the encoding of the PHP file. You can save the file as a file and select UTF-8 encoding when saving. |