Calling SET NAMES on a connection is equivalent to calling set_charset unless you call get_charset and mysql_real_escape_string (and friends).
When you call set_charset , PHP does two things. First, it calls SET NAMES on the connection. Secondly, he remembers what encoding you set. This status information is later only used in the get_charset and mysql_real_escape_string (and friends) functions. Therefore, if you do not use these functions, you can consider two equivalents.
Skip the source code:
- Userland functions mysql_set_charset and
mysqli_set_charset call ... - The
mysql_set_character_set engine mysql_set_character_set calls ... The mysqlnd_set_character_set engine mysqlnd_set_character_set , which is defined as:
#define mysqlnd_set_character_set(conn, cs) \ ((conn)->data)->m->set_charset((conn)->data, (cs)))
and expanding to ...
MYSQLND_METHOD(mysqlnd_conn_data, set_charset) which contains the following code (numbered for discussion, these are not the actual line numbers of the source code):
1 if (PASS == conn->m->local_tx_start(conn, this_func)) { 2 char * query; 3 size_t query_len = mnd_sprintf(&query, 0, "SET NAMES %s", csname); 4 5 if (FAIL == (ret = conn->m->query(conn, query, query_len))) { 6 php_error_docref(NULL, E_WARNING, "Error executing query"); 7 } else if (conn->error_info->error_no) { 8 ret = FAIL; 9 } else { 10 conn->charset = charset; 11 } 12 mnd_sprintf_free(query); 13 14 conn->m->local_tx_end(conn, this_func, ret); 15 }
As you can see, PHP calls SET NAMES on the connection itself (line 3). PHP also tracks only the character set (line 10). The comments further discuss what happens with conn->charset , but suffice it to say that it ends only in get_charset and mysql_real_escape_string (and friends).
So, if you do not care about this state, and you agree to use neither get_charset nor mysql_real_escape_string , you can call SET NAMES on the connection itself without any harmful effect.
Aside, I have never done this, but it seems that compiling PHP using -DPHP_DEBUG=1 will allow for significant debugging using various DBG macros. This can be useful when looking at how your code goes through this block.
bishop Jun 21 '16 at 14:51 2016-06-21 14:51
source share