php reads mysql scrambled code and shares the principles of set names XXX

  • 2020-05-10 17:51:49
  • OfStack

Let's start with the MySQL character set. Windows can be modified by my.ini

PHP code
 
[mysql] 

default-character-set=utf8 // The client's default character set  
[mysqld] 

default-character-set=utf8 // The default character set on the server side  

Let's say we set both of them to utf8, and then in MySQL Command Line Client enter "show variebles like" character_set_% "; , you can see the following characters:
 
character_set_client latin1 
character_set_connection latin1 
character_set_database utf8 
character_set_results latin1 
character_set_server utf8 
character_set_system utf8 

If we were to read data from the database using UTF-8's PHP program, it would most likely be a string of "... Or something like that.

The solution is to, after connecting to the database, execute a query "SET NAMES UTF8" before reading the data, i.e., "SET NAMES UTF8" in PHP

mysql_query("SET NAMES UTF8");

$connection=mysql_connect($db_host,$db_user,$db_psw)or die(" connection to server failed "); after

Displays normally (as long as the characters in the database are normal).

Go to the MySQL command line and type "SET NAMES UTF8;" , and then "show variebles like" character_set_% ";" , found that the original latin1 variables "character_set_client", "character_set_connection", "character_set_results" values have all changed to utf8, the original is these three variables in mischief.

Look in the manual, and the sentence above is equal to:

SET character_set_client = utf8;

SET character_set_results = utf8;

SET character_set_connection = utf8;

Look at the three variables at work:
Information input path: client→connection→server;
Information output path: server→connection→results.
In other words, each path goes through three changes in character set encoding. For example, the output of utf8 in server was transferred to latin1, results to latin1, and utf-8 was transferred to results. If two character sets are incompatible, such as latin1 and utf8, the conversion process is irreversible and destructive.

But just to make a point, the "SET NAMES UTF8" effect is only temporary, and the default will be restored when MySQL is restarted.

This brings us to the configuration of MySQL on the server. Wouldn't we have to add "SET NAMESUTF8" every time we read or write to a database to ensure that the data is transmitted in code 1? Is it possible to configure MySQL so that the three variables default to the desired character set? It wasn't in the manual, and I couldn't find the answer online. So, from a server configuration point of view, there's no way to leave out that line of code.
Summary: in order for your web pages to display properly on more servers, add "SET NAMES UTF8", even if you don't add it now.

Related articles: