In php, the insert and update methods are the two most commonly used data storage methods for mysql databases. Next I will introduce the mysql Data Storage Methods for beginners.
PHP writes data to the MySQL database in three steps:
1. Establish a connection between PHP and MySQL
2. Open the MySQL database
3. Accept page data. Input PHP Data to the specified table.
Steps 1 and 2 can directly use a database link file: conn. php
The Code is as follows: |
Copy code |
<? Php Mysql_connect ("localhost", "root", ""); // connect to MySQL Mysql_select_db ("mythroad"); // select a database ?> |
Of course, the premise is that you have installed the WEB server, PHP, and MySQL, and created the MySQL table "mythroad"
The three parameters of mysql_connect () are MySQL address, MySQL user name, and MySQL password.
Then, data is transmitted through the WEB page, so that PHP can write data to a table specified by the MySQL database through SQL statements, such as creating a file.
Post. php
The Code is as follows: |
Copy code |
<? Php Require_once ("conn. php"); // reference the database link file $ Uname = $ _ GET ['n']; // The GET method is passed as a URL parameter. $ Pwd = $ _ GET ['P']; $ Pwd = md5 ($ pwd); // use MD5 encryption directly $ SQL = "insert into mythroad (username, password) values ('$ uname',' $ pwd ')"; Mysql_query ($ SQL); // use SQL statements to insert data Mysql_close (); // close the MySQL connection Echo "successfully entered data "; ?> |
Test page: http: // 127.0.0.1/post. php? N = mythroad & p = mythroad
You can insert the new data "mythroad" to the username field and "mythroad" to the password field into the members table of MySQL database hello.
If form post is used, we can accept it by using post.Update Data
Example:
The Code is as follows: |
Copy code |
<? Php $ Conn = @ mysql_connect ("localhost", "root", "root123 "); If (! $ Conn ){ Die ("failed to connect to database:". mysql_error ()); } Mysql_select_db ("test", $ conn ); Mysql_query ("set names 'gbk '"); $ SQL = "UPDATE user SET email = 'xiaoming @ 163.com 'WHERE username = 'xiaoming '"; If (mysql_query ($ SQL, $ conn )){ Echo "data updated! "; } Else { Echo "failed to update data:". mysql_error (); } ?> |