Home Database Mysql Tutorial 深入理解SET NAMES和mysql(i)_set_charset的区别_MySQL

深入理解SET NAMES和mysql(i)_set_charset的区别_MySQL

Jun 01, 2016 pm 01:50 PM
mysql

bitsCN.com

  最近公司组织了个PHP安全编程的培训, 其中涉及到一部分关于Mysql的”SET NAMES”和mysql_set_charset (mysqli_set_charset)的内容:

  说到, 尽量使用mysqli_set_charset(mysqli:set_charset)而不是”SET NAMES”, 当然, 这个内容在PHP手册中也有叙及, 但是却没有解释为什么.

  最近有好几个朋友问我这个问题, 到底为什么?

  问的人多了, 我也就觉得可以写篇blog, 专门介绍下这部分的内容了.

  首先, 很多人都不知道”SET NAMES”到底是做了什么,

  我之前的文章深入MySQL字符集设置中, 曾经介绍过character_set_client/character_set_connection/character_set_results这三个MySQL的”环境变量”, 这里再简单介绍下,

  这三个变量, 分别告诉MySQL服务器, 客户端的编码集, 在传输给MySQL服务器的时候的编码集, 以及期望MySQL返回的结果的编码集.

  比如, 通过使用”SET NAMES utf8″, 就告诉服务器, 我用的是utf-8编码, 我希望你也给我返回utf-8编码的查询结果.

  一般情况下, 使用”SET NAMES”就足够了, 也是可以保证正确的. 那么为什么手册又要说推荐使用mysqli_set_charset(PHP>=5.0.5)呢?

  首先, 我们看看mysqli_set_charset到底做了什么(注意星号注释处, mysql_set_charset类似):

 

  //php-5.2.11-SRC/ext/mysqli/mysqli_nonapi.c line 342

  PHP_FUNCTION(mysqli_set_charset)

  {

  MY_MYSQL *mysql;

  zval *mysql_link;

  char *cs_name = NULL;

  unsigned int len;

  if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis()

  , "Os", &mysql_link, mysqli_link_class_entry, &cs_name, &len) == FAILURE) {

  return;

  }

  MYSQLI_FETCH_RESOURCE(mysql, MY_MYSQL*, &mysql_link, "mysqli_link"

  , MYSQLI_STATUS_VALID);

  if (mysql_set_character_set(mysql->mysql, cs_name)) {

  //** 调用libmysql的对应函数

  RETURN_FALSE;

  }

  RETURN_TRUE;

  }

 

  那mysql_set_character_set又做了什么呢?

 

  //mysql-5.1.30-SRC/libmysql/client.c, line 3166:

  int STDCALL mysql_set_character_set(MYSQL *mysql, const char *cs_name)

  {

  struct charset_info_st *cs;

  const char *save_csdir= charsets_dir;

  if (mysql->options.charset_dir)

  charsets_dir= mysql->options.charset_dir;

  if (strlen(cs_name)

  (cs= get_charset_by_csname(cs_name, MY_CS_PRIMARY, MYF(0))))

  {

  char buff[MY_CS_NAME_SIZE + 10];

  charsets_dir= save_csdir;

  /* Skip execution of "SET NAMES" for pre-4.1 servers */

  if (mysql_get_server_version(mysql)

  return 0;

  sprintf(buff, "SET NAMES %s", cs_name);

  if (!mysql_real_query(mysql, buff, strlen(buff)))

  {

  mysql->charset= cs;

  }

  }

  //以下省略

 

  我们可以看到, mysqli_set_charset除了做了”SET NAMES”以外, 还多做了一步:

 

  sprintf(buff, "SET NAMES %s", cs_name);

  if (!mysql_real_query(mysql, buff, strlen(buff)))

  {

  mysql->charset= cs;

  }

 

  而对于mysql这个核心结构的成员charset又有什么作用呢?

  这就要说说mysql_real_escape_string()了, 这个函数和mysql_escape_string的区别就是, 它会考虑”当前”字符集. 那么这个当前字符集从哪里来呢?

  对了, 你猜的没错, 就是mysql->charset.

  mysql_real_string在判断宽字符集的字符的时候, 就根据这个成员变量来分别采用不同的策略, 比如如果是utf-8, 那么就会采用libmysql/ctype-utf8.c.

  看个实例, 默认mysql连接字符集是latin-1, (经典的5c问题):

 

  

  $db = mysql_connect('localhost:3737', 'root' ,'123456');

  mysql_select_db("test");

  $a = "/x91/x5c";//"

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to set up MySQL connection pool using PHP? How to set up MySQL connection pool using PHP? Jun 04, 2024 pm 03:28 PM

Setting up a MySQL connection pool using PHP can improve performance and scalability. The steps include: 1. Install the MySQLi extension; 2. Create a connection pool class; 3. Set the connection pool configuration; 4. Create a connection pool instance; 5. Obtain and release connections. With connection pooling, applications can avoid creating a new database connection for each request, thereby improving performance.

How to delete data from MySQL table using PHP? How to delete data from MySQL table using PHP? Jun 05, 2024 pm 12:40 PM

PHP provides the following methods to delete data in MySQL tables: DELETE statement: used to delete rows matching conditions from the table. TRUNCATETABLE statement: used to clear all data in the table, including auto-incremented IDs. Practical case: You can delete users from the database using HTML forms and PHP code. The form submits the user ID, and the PHP code uses the DELETE statement to delete the record matching the ID from the users table.

See all articles