To read the database, we need to use the functions in php to connect to the database and then use the SQL statement to query the data in the table and traverse it. next we will look at a simple mysql instance.
The code is as follows:
$ Link = mysql_connect ("localhost", "root", "previous administrator password ");
If (! $ Link) echo "no connection successful! ";
Mysql_select_db ("infosystem", $ link); // select a database
$ Q = "SELECT * FROM info"; // SQL query statement
Mysql_query ("set names GB2312 ");
$ Rs = mysql_query ($ q); // Obtain a dataset
If (! $ Rs) {die ("Valid result! ");}
Echo"
";Echo"
Department name |
Employee Name |
PC name |
";While ($ row = mysql_fetch_array ($ rs) echo"
$ Row [1] |
$ Row [2] |
$ Row [3] |
"; // Display DataEcho"
";
Mysql_free_result ($ rs); // Close the dataset
?>
Garbled characters in Chinese
When we access the MySQL database through PHP in the original way, even if the default character set of the table is set to utf8 and the query is sent through the UTF-8 encoding, you will find that the database is still garbled.
In fact, the simple method is to set it through phpMyAdmin.
Set the following items:
1: language set to chinese (zh-utf-8)
2. MySQL character set: UTF-8 Unicode (utf8)
3: MySQL connection verification: utf8_general_ci
4: When adding a database and a data table, select utf8_general_ci as the sorting item.
Through the above settings, Chinese characters are not garbled during operations and queries in phpMyAdmin.
However, you will find that the results obtained by using the previous SQL statement in the php program are garbled, and the problem lies in the connection layer.
The solution is to send a query statement after successfully connecting to the database:
The code is as follows:
1: $ this-> LinkID = mysql_connect ($ this-> Host, $ this-> User, $ this-> Password );
2: mysql_query ('set names' utf8', $ this-> LinkID );
Or:
DEFINE ('link', mysql_connect (DB_HOST, DB_USER, DB_PASSWORD ));
Mysql_query ("set names 'utf8'", LINK );
Gbk encoded
The code is as follows:
$ Mysql_mylink = mysql_connect ($ mysql_host, $ mysql_user, $ mysql_pass );
Mysql_query ("set names 'gbk '");