Set encoding to UTF-8 for current MySQL connection [duplicate]

Good afternoon.

The result of the sql query is not returned in UTF-8encoding. I tried to set the character set using the function mysql_set_charset('utf8',$db), but apparently the function does not work, despite the fact that MySQL version 5.0.7. How else can I set the connection encoding other than using SET NAMES?

Z.Y. When working with the same table using PDO, when setting encoding:

$db->exec('SET CHARACTER SET utf8')

Fields were returned in UTF-8.

Answer 1, authority 100%

The most 100% code for 100% UTF-8 😀

mysql_query("SET NAMES 'utf8'"); 
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci'");

Answer 2, authority 75%

  1. The original MySQL API (mysql_functions) has been deprecated since PHP 5.5.0 and removed in PHP 7.0.0.
  2. For MySQL Improved, the preferred way is to use set_charset().



    mysqli_set_charset($link, 'utf8');

    Using the query()method for this purpose (for example: SET NAMES 'utf8') not recommended.

  3. In PDO, you must specify the connection encoding in the dsnparameter when creating an instance of the database class:

    $dsn = 'mysql:dbname=DB;host=HOST;charset=utf8';
    $pdo = new \PDO($dsn, $user, $password, $options);

P.S. To work with four-byte UTF-8 (for example, to save emoji to the database), instead of encoding utf8, you should use encoding utf8mb4. The base must also be configured using utf8mb4.

Answer 3, authority 17%

SET NAMES 'utf-8'

Answer 4, authority 17%

If the problem with the mysql_query(“SET NAMES utf8”) function failing on the local denwer web server is due to the fact that the cp1251 encoding is set by default in the denwer parameters – I racked my brain for days.

Answer 5, authority 8%

mysql_query('SET NAMES utf8 COLLATE utf8_general_ci');