Php utf8 mysql select

mysql_client_encoding

Данный модуль устарел, начиная с версии PHP 5.5.0, и удалён в PHP 7.0.0. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API. Альтернативы для данной функции:

Описание

Возвращает значение переменной MySQL character_set .

Список параметров

Соединение MySQL. Если идентификатор соединения не был указан, используется последнее соединение, открытое mysql_connect() . Если такое соединение не было найдено, функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров. Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING .

Возвращаемые значения

Возвращает используемую по умолчанию кодировку для данного соединения.

Примеры

Пример #1 Пример использования mysql_client_encoding()

$link = mysql_connect ( ‘localhost’ , ‘mysql_user’ , ‘mysql_password’ );
$charset = mysql_client_encoding ( $link );

echo «Текущая кодировка: $charset \n» ;
?>

Результатом выполнения данного примера будет что-то подобное:

Смотрите также

  • mysql_set_charset() — Устанавливает кодировку клиента
  • mysql_real_escape_string() — Экранирует специальные символы в строках для использования в выражениях SQL

User Contributed Notes 13 notes

f you think «set names utf8» for each connection is too trouble, you can modify my.cnf of MySQL to solve the problem forever. In my.cnf, add the line «default-character-set=utf8» in both [mysqld] and [client] sections:

The MySQL will use utf8 after you restart it.

I couldn’t get any luck with all the stuff mentioned below, and despite having an unicode DB, and setting all my field to utf8_general_ci.
After looking around, I found that this page: http://dev.mysql.com/tech-resources/articles/4.1/unicode.html was adding the fields with an extra info before each value:

mysql_query(«INSERT INTO table SET field = _utf8’value'»);
?>
Mind the «_utf8» before the field value, and outside of the quotes.

This works for me wether in an Insert or an Update statement.

No need here for a before each query, or to change anything in the config files (that was important since I don’t have access to these).

If you set the encoding in my.cnf like

[mysqld]init_connect=’SET NAMES utf8′

note that the content of init_connect is not executed for users that have the SUPER privilege — ie root!

Notice the difference between following two SQL statements:

SET NAMES ‘charset_name’
SET CHARACTER SET charset_name

All I had to do to save utf8 data with php mysql_query() was to go to the php.ini and put default_charset = «utf-8». Without this I had the same problems some of you have. Plus, all my mysql charsets vars are in ‘utf8’. (Changed them with Mysql Admin Tool)

Didnt use any mysql SET **** command at all.

Hope this help some of you.

The right lines to put in /etc/my.cnf (or other MySQL options file) are:

[client]init-command=»SET NAMES utf8″

Unfortuantely the PHP mysql_connect() function does not use MySQL options files so this is not a sollution for changing the default connection character set for mysqlclient library v4.1+.

Читайте также:  Css select no borders

The only working sollution remains:

mysql_query(«SET NAMES utf8», $conn);

(of course /ext/mysql/php_mysql.c can always be patched ;] )

There’s no ‘character_set’ variable available in MySQL. You can check it yourself in MySQL online documentation or by running MySQL query «SHOW VARIABLES LIKE ‘character_set%’;».
This must be an error in PHP manual, unless I’m missing something.

Please note that even if you set the charset by issuing the two mentioned SQL statements (set names, set character set) mysql_client_encoding still deliveres the old result.

Default for me is latin1. After switching to UTF8 mysql_client_encoding still returns latin1. The charset switched to UTF8 successfully, though.

I have had problems with encoding after export of tables (from hosting — via PhpMyAdmin) and import them to other machine (my notebook — via PhpMyAdmin too). In PhpMyAdmin the encoding of all data was shown correctly, not that good with the web pages (data pulled via php).
The first point is indication, that the data was imported correctly, but php script has got other character set than MySql is sending.

The script’s character set is set in header: . MySql setting was latin1.

Then following code helped me:

mysql_query ( «SET CHARACTER SET ‘latin2′» , $conn );
?>

If you experience weird problems, like some UTF-8 characters (the Unicode character &#x010D and a few others in my case) seemingly being changed to garbage by mysql_query, you may need to do something like this before your actual query:

mysql_query ( «SET NAMES ‘utf8′» , $conn );
?>

Took me days to figure that one out.

Источник

mysqli_set_charset

Задаёт набор символов, который будет использоваться при обмене данными с сервером баз данных.

Список параметров

Только для процедурного стиля: объект mysqli , полученный с помощью mysqli_connect() или mysqli_init() .

Набор символов, который необходимо установить.

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Ошибки

Если уведомления об ошибках mysqli включены ( MYSQLI_REPORT_ERROR ) и запрошенная операция не удалась, выдаётся предупреждение. Если, кроме того, установлен режим MYSQLI_REPORT_STRICT , вместо этого будет выброшено исключение mysqli_sql_exception .

Примеры

Пример #1 Пример использования mysqli::set_charset()

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «test» );

printf ( «Начальный набор символов: %s\n» , $mysqli -> character_set_name ());

/* изменение набора символов на utf8mb4 */
$mysqli -> set_charset ( «utf8mb4» );

printf ( «Текущий набор символов: %s\n» , $mysqli -> character_set_name ());

mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$link = mysqli_connect ( ‘localhost’ , ‘my_user’ , ‘my_password’ , ‘test’ );

printf ( «Начальный набор символов: %s\n» , mysqli_character_set_name ( $link ));

/* изменение набора символов на utf8mb4 */
mysqli_set_charset ( $link , «utf8mb4» );

printf ( «Текущий набор символов: %s\n» , mysqli_character_set_name ( $link ));

Результат выполнения данных примеров:

Начальный набор символов: latin1 Текущий набор символов: utf8mb4

Примечания

Замечание:

Чтобы использовать эту функцию на Windows платформах, вам потребуется клиентская библиотека MySQL версии 4.1.11 или выше (для MySQL 5.0 соответственно 5.0.6 или выше).

Замечание:

Это предпочтительный способ задания набора символов. Использование для этих целей функции mysqli_query() (например SET NAMES utf8 ) не рекомендуется. Дополнительно смотрите Наборы символов в MySQL.

Смотрите также

  • mysqli_character_set_name() — Возвращает текущую кодировку, установленную для соединения с БД
  • mysqli_real_escape_string() — Экранирует специальные символы в строке для использования в SQL-выражении, используя текущий набор символов соединения
  • Концепции кодировок MySQL
  • » Список поддерживаемых MySQL наборов символов
Читайте также:  Sign Up

User Contributed Notes 5 notes

Setting the charset (it’s really the encoding) like this after setting up your connection:
$connection->set_charset(«utf8mb4»)

FAILS to set the proper collation for the connection:

character_set_client: utf8mb4
character_set_connection: utf8mb4
character_set_database: utf8mb4
character_set_filesystem: binary
character_set_results: utf8mb4
character_set_server: utf8mb4
character_set_system: utf8
collation_connection: utf8mb4_general_ci collation_database: utf8mb4_unicode_ci
collation_server: utf8mb4_unicode_ci

If you use SET NAMES, that works:
$connection->query(«SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci»);

character_set_client: utf8mb4
character_set_connection: utf8mb4
character_set_database: utf8mb4
character_set_filesystem: binary
character_set_results: utf8mb4
character_set_server: utf8mb4
character_set_system: utf8
collation_connection: utf8mb4_unicode_ci collation_database: utf8mb4_unicode_ci
collation_server: utf8mb4_unicode_ci

Please note, that I set the following variables on the server:

Set the following to be: utf8mb4_unicode_ci

character-set-client-handshake = FALSE or 0
skip-character-set-client-handshake = TRUE or 1

So in my case, I had tried changing the collation from utf8mb4_unicode_ci for mysql and had to change it to uft8_general_ci.

mysqli_set_charset( $con, ‘utf8’);

right before I did the SELECT command.

This is my code for reading from db :

$con = mysqli_connect($DB_SERVER, $DB_USER_READER, $DB_PASS_READER, $DB_NAME, $DB_PORT);//this is the unique connection for the selection

mysqli_set_charset( $con, ‘utf8’);

$slct_stmnt = «SELECT «.$SELECT_WHAT.» FROM «.$WHICH_TBL.» WHERE «.$ON_WHAT_CONDITION;

$slct_query = mysqli_query($con, $slct_stmnt);

if ($slct_query==true) //Do your stuff here . . .
>

And it worked like a charm. All the best. The above code can work with reading chineese, russian or arabic or any international language from the database’s table column holding such data.

Although the documentation says that using that function is preferred than using SET NAMES, it is not sufficient in case you use a collation different from the default one:

// That will reset collation_connection to latin1_swedish_ci
// (the default collation for latin1):
$mysqli -> set_charset ( ‘latin1’ );

// You have to execute the following statement *after* mysqli::set_charset()
// in order to get the desired value for collation_connection:
$mysqli -> query ( «SET NAMES latin1 COLLATE latin1_german1_ci» );

To align both the character set (e.g., utf8mb4) AND the collation sequence with the schema (database) settings:

$mysqli = new mysqli ( DB_HOST , DB_USER , DB_PASSWORD , DB_SCHEMA , DB_PORT );
if ( 0 !== $mysqli -> connect_errno )
throw new \ Exception ( $mysqli -> connect_error , $mysqli -> connect_errno );

if ( TRUE !== $mysqli -> set_charset ( ‘utf8mb4’ ) )
throw new \ Exception ( $mysql -> error , $mysqli -> errno );

if ( TRUE !== $mysqli -> query ( ‘SET collation_connection = @@collation_database;’ ) )
throw new \ Exception ( $mysql -> error , $mysqli -> errno );
?>

To confirm:

echo ‘character_set_name: ‘ , $mysqli -> character_set_name (), ‘
‘ , PHP_EOL ;
foreach( $mysqli -> query ( «SHOW VARIABLES LIKE ‘%_connection’;» )-> fetch_all () as $setting )
echo $setting [ 0 ], ‘: ‘ , $setting [ 1 ], ‘
‘ , PHP_EOL ;
?>

Читайте также:  Java and kotlin tests

will output something like:
character_set_name: utf8mb4
character_set_connection: utf8mb4
collation_connection: utf8mb4_unicode_520_ci

Note that using utf8mb4 with this function may cause this function to return false, depending on the MySQL client library compiled into PHP. If the client library is older than the introduction of utf8mb4, then PHP’s call of the libraries ‘mysql_set_character_set’ will return an error because it won’t recognise that character set.

The only way you will know there’s an error is by checking the return value, because PHP warnings are not emitted by this function.
mysqli_error will return something like:
«Can’t initialize character set utf8mb4 (path: /usr/share/mysql/charsets/)»
(I don’t think the directory has anything to do with it; I think the utf8mb4 vs utf8 distinction is handled internally)

A workaround is to recall with utf8, then do a ‘SET NAMES’ query with utf8mb4.

If your MySQL server is configured to use utf8 by default, then you may not notice any of this until you get obscure bugs. It seems it will still save into the database correctly in terms of bytes. However, you may get «Data too long for column» errors if you are truncating strings to fit fields, because from MySQL’s point of view during the length check every 4-byte character will actually be multiple individual characters. This caused me hours of debugging.

Источник

Как выбрать кодировку, в которой будет возвращать строки MySQL?

Написал простенькую страницу сегодня, подгружающую из SQL строки. На локалке все работает, но когда перенес на хостинг — SQL стала возвращать вместо UTF-8 строк ASCII строки => все русские символы стали «?».

; sql_connect(); $query = 'SHOW VARIABLES LIKE "character_set_database"'; $result = mysql_query($query); $r = mysql_fetch_array($result); echo $r[1]; echo mb_detect_encoding($r[1]); echo 'Русский пашет?'; ?>

Этот код выдает следующее — utf8ASCIIРусский пашет?.
То есть кодировка БД — utf-8, сайт utf-8, но строки возвращаются в ASCII.
Стоит добавить, что все записи в БД отображаются нормально.
Если что-то совсем глупое — не ругайтесь:3

Вы создали БД сразу в кодировке UTF-8, или создали и потом поменяли кодировку? Может быть такое, что у выводимых вами полей кодировка как раз cp1251, в то время как сама БД в UTF-8. Зайдите в редактирование полей таблицы, там указана кодировку для каждого из полей.

MrHamster

utf_general_ci
Для проверки я даже создавал новую БД с такой же кодировкой, и вытаскиваемые значения все-равно были в ASCII

Владимир Хоменок: интереса ради создал у себя БД с настройками как у вас. Запустил ваш код — выдает то же самое. Создал таблицу и заполнил её русскими данными — вывожу в браузер — все ок.
Правильно я понимаю, что при выводе в браузер данных у вас кракозябры?

Источник

Оцените статью