The following articles mainly describe the actual operation steps for connecting PHP to the MySQL database and the actual application code. In fact, it is very simple to connect PHP to MySQL, however, we must note that incorrect encoding causes garbled characters.
The database connection code is as follows:
Code
- <? Php
- $ Link = MySQL_connect ("localhost", "root", "123 ")
- Or die ("connect to database failed ");
- $ Result = MySQL_query ("create database trampt ")
- Or die ("query failed ");
- MySQL_select_db ("trampt ");
- MySQL_query ("set names UTF8 ");
- $ Result = MySQL_query ("create table Users (userid int auto_increment primary key, username varchar (50), password varchar (50 ))")
- Or die ("query failed ");
- MySQL_query ("insert into users (username, password) values ('blog service', '123 ')")
- Or die ("insert record failed ");
- MySQL_close ($ link );
- ?>
The read database code is as follows:
- <?php
- require("inc/conn.php");
- $result=MySQL_query("select * from users");
- while($ob=MySQL_fetch_object($result))
- {
- echo "user name is : ".$ob->username."<br/>";
- }
- MySQL_close($link);
- ?>
Note the encoding settings: 1 The database sets UTF-8 encoding. 2 The page encoding is set to UTF-8. 3. Use MySQL_query ("set names UTF8") to avoid garbled code.
The above content is an introduction to the connection of PHP to the MySQL database. I hope you will have some gains.