Home > Backend Development > PHP Problem > Database php Chinese characters garbled

Database php Chinese characters garbled

藏色散人
Release: 2023-02-27 15:18:01
Original
2172 people have browsed it

Database php Chinese characters garbled

The problem of using UTF-8 encoding for MYSQL database

1. Use phpmyadmin to create the database and data table

Create the database When creating a data table, please set "Organization" to: "utf8_general_ci" or execute the statement:

CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
Copy after login

When creating a data table: If the field stores Chinese, you need to set "Organization" to: " utf8_general_ci",

If this field stores English or numbers, the default is fine.

Corresponding SQL statement, for example:

CREATE TABLE `test` ( 
`id` INT NOT NULL , 
`name` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , 
PRIMARY KEY ( `id` ) 
) ENGINE = MYISAM ;
Copy after login

2. Use PHP to read and write the database

After connecting to the database:

$connection = mysql_connect($host_name, $host_user, $host_pass);
Copy after login

Add two lines:

mysql_query("set character set 'utf8'");//读库 
mysql_query("set names 'utf8'");//写库 
//其实读写都可以只加入
mysql_query("set names 'utf8'");
Copy after login

Then you can read and write the MYSQL database normally.

The environment made using appserv-win32-2.5.10 uses the default utf8 encoding when installing this package.

When writing the database connection file, write:

$conn = mysql_connect("$host","$user","$password"); 
mysql_query("SET NAMES 'UTF8'"); 
mysql_select_db("$database",$conn);
Copy after login

Then when making the page, pay attention to this sentence:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Copy after login

In this way, regardless of the Chinese input into the database, or the page display, It's all normal.

In the DW CS4 version, the utf8 page is also generated by default.

Similarly, if you first write the database connection file as: mysql_query("SET NAMES 'GBK'");

Then the page will also change accordingly:

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
Copy after login

For more PHP-related knowledge, please visit PHP中文网!

The above is the detailed content of Database php Chinese characters garbled. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template