PHP Code Description for connecting to the MySQL database

Source: Internet
Author: User

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

 
 
  1. <? Php
  2. $ Link = MySQL_connect ("localhost", "root", "123 ")
  3. Or die ("connect to database failed ");
  4. $ Result = MySQL_query ("create database trampt ")
  5. Or die ("query failed ");
  6. MySQL_select_db ("trampt ");
  7. MySQL_query ("set names UTF8 ");
  8. $ Result = MySQL_query ("create table Users (userid int auto_increment primary key, username varchar (50), password varchar (50 ))")
  9. Or die ("query failed ");
  10. MySQL_query ("insert into users (username, password) values ('blog service', '123 ')")
  11. Or die ("insert record failed ");
  12. MySQL_close ($ link );
  13. ?>

The read database code is as follows:

 
 
  1. <?php 
  2. require("inc/conn.php");  
  3. $result=MySQL_query("select * from users");  
  4. while($ob=MySQL_fetch_object($result))  
  5. {  
  6. echo "user name is : ".$ob->username."<br/>";  
  7. }  
  8. MySQL_close($link);  
  9. ?> 

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.