Wrong encoding when outputting data from the database

Please note that these settings are required in case of a mismatch between the database and site encoding. If any files were changed before the problem appeared, then you should initially double-check the encoding of the files themselves and change it to the desired one, if required.

If the encoding of the site and the database does not match (some of the text on the site is displayed normally, and some of the text from the database is in the form of incomprehensible characters), you need to add commands in the script that connects to the database that will indicate the encoding to the MySQL server in which you want to display the text. Depending on which PHP library you are using, the commands will look like this:

  • For the library mysql:
    mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
    mysql_query("SET CHARACTER SET 'utf8'");
  • For the library mysqli:
    mysqli_query($link, "SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
    mysqli_query($link, "SET CHARACTER SET 'utf8'");

In commands:

  • Instead utf8 you must specify the desired encoding (for example, cp1251).
  • Instead utf8_general_ci — the desired encoding mapping (for example, cp1251_general_ci). A complete list of MySQL encodings and collations is available at official documentation.
  • For the library mysqli the first parameter specifies a pointer to the connection to the database — in your script it may be different from $link (you can find it out by looking in the source code for the name of the variable to which the result of the function is assigned mysqli_connect()).