2.6.1.3.1. Incorrect encoding when retrieving data from database

Please note that these settings are required if the database and site use different character encodings. If any files were modified before the issue arose, you should first double-check the character encoding of the files themselves and change it to the correct one, if necessary.

If the encoding of the site and the database do not match (some text on the site displays correctly, while some text from the database appears as garbled characters), you need to add commands to the script that connects to the database to specify the encoding in which the text should be displayed to the MySQL server. Depending on which PHP library you are using, the commands will look like this:

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

In commands:

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

    (1)