Home  >  Article  >  Backend Development  >  What to do if php sql is garbled

What to do if php sql is garbled

藏色散人
藏色散人Original
2022-11-04 10:37:001878browse

Solution to php sql garbled code: 1. Select ANSI encoding when saving the PHP file; 2. Add "header("Content-Type: text/html; CHARSET=GBK");" to the PHP file header; 3. Transcode the SQL before querying; 4. Just transcode the query results containing Chinese columns.

What to do if php sql is garbled

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.

What should I do if php sql is garbled?

Solve the problem of PHP connection to SQLSERVER and Chinese garbled characters

1. Chinese characters in the SQL statement will cause the query to fail;

2.Query The result will be garbled characters in Chinese.

Solution one (simpler, recommended):

1. Select ANSI encoding when saving the PHP file;

Attachment: VS Code changes Default text encoding, File->Preferences->Usersettings, search encoding, change utf8 to gbk

2, add

header("Content-Type: text/html; CHARSET=GBK");
## to the PHP file header

#Solution 2 (more troublesome):

1. Keep the default UTF-8 encoding for PHP files;

2. Code SQL before querying Transcoding

$sql = "SELECT '是'='是'"; 
$sql=iconv('UTF-8','GBK',$sql);

3. Query results for transcoding columns containing Chinese

$stmt = sqlsrv_query( $conn, $sql);
if($stmt){
    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
        echo iconv('GBK','UTF-8',$row[0])."
"; } }

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of What to do if php sql is garbled. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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