I'm trying to insert a Cyrillic value in the MySQL table, but there is a problem with encoding.
Php:
<?php
$servername = "localhost";
$username = "a";
$password = "b";
$dbname = "c";
$conn = new mysqli($servername, $username, $password, $dbname);
mysql_query("SET NAMES 'utf8';");
mysql_query("SET CHARACTER SET 'utf8';");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci';");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `c`.`mainp` SET `search` = 'test тест' WHERE `mainp`.`id` =1;";
if ($conn->query($sql) === TRUE) {
}
$conn->close();
?>
MySQL:
| id | search |
| 1 | test ав |
Note: PHP file is utf-8
, database collation utf8_general_ci
Solution:
mysql_query("SET NAMES 'utf8';");
>$mysqli->set_charset('utf8');
Your actual issue is a charset problem somewhere. Here's a few pointers which can help you get the right charset for your application. This covers most of the general problems one can face when developing a PHP/MySQL application.
Format
->Convert to UTF-8 w/o BOM
)The header in both PHP and HTML should be set to UTF-8
HTML (inside
<head></head>
tags):PHP (at the top of your file, before any output):
Upon connecting to the database, set the charset to UTF-8 for your connection-object, like this (directly after connecting)
This is for
mysqli_*
, there are similar ones formysql_*
and PDO (see bottom of this answer).Also make sure your database and tables are set to UTF-8, you can do that like this:
(Any data already stored won't be converted to the proper charset, so you'll need to do this with a clean database, or update the data after doing this if there are broken characters).
json_encode()
, you might need to apply theJSON_UNESCAPED_UNICODE
flag, otherwise it will convert special characters to their hexadecimal equivalent.Remember that EVERYTHING in your entire pipeline of code needs to be set to UFT-8, otherwise you might experience broken characters in your application.
In addition to this list, there may be functions that has a specific parameter for specifying a charset. The manual will tell you about this (an example is
htmlspecialchars()
).There are also special functions for multibyte characters, example:
strtolower()
won't lower multibyte characters, for that you'll have to usemb_strtolower()
, see this live demo.Setting UTF-8 with
mysql_
and PDOPDO: This is done in the DSN of your object. Note the
charset
attribute,mysql_
: This is done very similar tomysqli_*
, but it doesn't take the connection-object as the first argument.