php - "set names" vs mysqli_set_charset — besides affecting mysqli_escape_string, are they identical? -


To do this / instead of using a direct MySQL query

The frequently cited reason is that the set name is unsafe because / the encoding used for mysql_set_charset / mysqli :: set_charset Will be determined by the call. (Another reason is to say that PHP docs says that this is "not recommended").

However, to directly use MySQL query set names Is secure if we use the prepared statement mysql_real_escape_string / mysqli :: real_escape_string /? In addition to affecting the encoding of mysql_real_escape_string / mysqli :: other than , what Is there a difference between set name vs mysql_set_charset / mysqli :: set_charset ?

Calling on connection SET NAMES is equivalent to calling < Code> set_charset , unless you either call get_charset and mysql_real_escape_string (and friend).


When you call set_charset , PHP does two things First of all, call SET NAMES on this connection Does. Second, it remembers which setset you set up, this state information is later used only in get_charset and mysql_real_escape_string (and friend) tasks, so if If you do not use these tasks, then you can consider two counterparts.

Let's go to source:

  1. User country's work mysql_set_charset and mysqli_set_charset call ...
  2. Engine function mysql_set_character_set call ...
  3. Engine macro Mysqlnd_set_character_set , which is defined as: < / P>

    #define mysqlnd_set_character_set (conn, cs) \ ((conn) -> data) -> M-> Set_charset (conn

  4. MYSQLND_METHOD (mysqlnd_conn_data, set_charset)

    and

  5. The following codes (These are not actual source line numbers counted for discussion):

  1 if (PASS == conn-> m-> ; Local_tx_start (conn, this_func)) {2 char * query; 3 size_t query_len = mnd_sprintf (and query, 0, "SET NAMES% s", csname); 4 5 if (FAIL == (ret = conn- & gt; M-& gt; query (conn, query, query_len)) {6 php_error_docref (NULL, E_WARNING, "error in query execution"); 7} and if (conn-> error_info-> error_no) { 8 ret = FAIL; 9} and (10 conn- & gt; charset = charset; 11} 12 mnd_sprintf_free (query); 13 14 Conn- & gt; m- & gt; local_tex_end (conn, this_func, ret); 15}  

As you can see, the PHP call SET NAMES < / Code> On the connection itself (line3). PHP only tracks charsets (line 10). Comments further discuss what happens with conn- & gt; charsets , but It is enough to say that it is only get_charset and mysql_real_escape_string (and friends).

Therefore, if you do not care about this situation, and you agree to use get_charset and mysql_real_escape_string , then you SET NAMES with no ill effects as well as on connection.

As one side, and I've never done this, but it looks like compiling with PHP - DPHP_DEBUG = 1 different DBG Enabling sufficient debugging via macros will be useful in seeing how your code is passing through this block.


Comments