PHP5 basic MySQL database operation code

Source: Internet
Author: User

1. Establish a database connection
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "root", "", "mydb ");
?>

To establish a database connection, four parameters are required: Database address, database access username, database access password, and database name. In addition to using the above mysqli object constructor to establish a database connection, you can also call its connect method to establish a database connection.
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ();
$ Mysqli-> connect ("localhost", "root", "", "mydb ");
?>

You can also use the mysqli object constructor to establish a data connection and use the select_db method to specify the database to be accessed.
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "root ","");
$ Mysqli-> select_db ("mydb ");
?>

Get the error code of the current connection through the errno attribute of the mysqli object. If there is no error in the current connection, the error code is returned as 0.
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "root ","");
$ Mysqli-> select_db ("mydb ");
If ($ mysqli-> errno = 0) // checks whether the current connection is successful.
{
}
Else
{
Echo "The Connection is Error! ";
Exit ();
}
?>

Of course, you can use the error attribute of the mysqli object to get the error message of the current connection. If there is no error, "" is returned.
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "rootsss ","");
$ Mysqli-> select_db ("mydb ");
If ($ mysqli-> errno = 0) // checks whether the current connection is successful.
{
}
Else
{
Echo $ mysqli-> error; // output the current error message
Exit ();
}
?>

2. query the database
You can use the query method of the mysqli object to query a database. This method returns the result set of the database.
Syntax: $ mysqli-> query (query statement, query mode );
There are two query modes:
① MYSQLI_STORE_RESULT. Return results as a cache set, which means you can immediately navigate the entire result set. This is the default setting. After the result set is queried, it is put into the memory, which means that if the data volume in the result set is large, it will occupy a large amount of memory. However, using this method, we can easily know how many rows of records are returned by a query or want to jump to a row in the result set immediately.
② MYSQLI_USE_RESULT. Return the result set as a non-Cache set. This means that the result set will be obtained from the database server as needed. This can improve the performance of large result set data. However, many operations on the result set are restricted, such as obtaining the number of queried rows.
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "root ","");
$ Mysqli-> select_db ("mydb ");
If ($ mysqli-> errno = 0) // checks whether the current connection is successful.
{
$ SQL = "SELECT * FROM student ";
$ Result = $ mysqli-> query ($ SQL );
Echo "Result row nums:". $ result-> num_rows. "<br>"; // displays the number of Result sets.
// Iteration result set
While (list ($ id, $ name, $ age, $ address) = $ result-> fetch_row ())
{
Echo "$ id: $ name: $ age: $ address". "<br> ";
}
}
Else
{
Echo $ mysqli-> error; // output the current error message
Exit ();
}
?>

Use the fetch_row method of the result set object to obtain each row of data in the result set. each row of data is an associated array. Use the list method to output each row of data. You can also use an output object to output each row in the result set.
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "root ","");
$ Mysqli-> select_db ("mydb ");
If ($ mysqli-> errno = 0) // checks whether the current connection is successful.
{
$ SQL = "SELECT * FROM student ";
$ Result = $ mysqli-> query ($ SQL );
Echo "Result row nums:". $ result-> num_rows. "<br>"; // displays the number of Result sets.
// Iteration result set
While ($ rowObject = $ result-> fetch_object ())
{
Echo "$ rowObject-> id: $ rowObject-> name: $ rowObject-> age: $ rowObject-> address". "<br> ";
}
}
Else
{
Echo $ mysqli-> error; // output the current error message
Exit ();
}
?>

The fetch_object method is used to encapsulate data in each row as an object. In the preceding example, this object is $ rowObject, and each column in the database becomes the attribute of this object, you can call the property name of this object to obtain the corresponding field value. For example, get the Student name $ rowObject-> name.
You can also use the fetch_array method to return each row of data as an associated array or an index array, or return both the associated array and the index array. The mode parameter of the fetch_array method to specify the mode of the currently returned array:
① MYSQLI_ASSOC. Returns the joined array, where key is the field name and value is the field value.
② MYSQLI_NUM. Returns an index array. The returned order is the same as the query field order.
③ MYSQLI_BOTH. Returns the associated array and index array. Default settings.
Copy codeThe Code is as follows:
<? Php
While ($ row = $ result-> fetch_array (MYSQLI_ASSOC) // returns the associated array
{
Echo $ row ['id']. $ row ['name']. $ row ['age']. $ row ['address']. "<br> ";
}
?>

Or
Copy codeThe Code is as follows:
<? Php
While ($ row = $ result-> fetch_array (MYSQLI_NUM) // returns the Index Array
{
Echo $ row [0]. $ row [1]. $ row [2]. $ row [3]. "<br> ";
}
?>

3. release memory
If the data volume in the result set is large and used, the free Method of the result set object is used to release the memory occupied by the result set. Once the free method is called, The result set is no longer available.
Copy codeThe Code is as follows:
<? Php
...
$ Result-> free (); // release memory
?>

4. Add, modify, and delete operations
The query method of the mysqli object can still be used to add, modify, and delete databases, except that SQL statements are different. Let's take adding data as an example:
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "root ","");
$ Mysqli-> select_db ("mydb ");
If ($ mysqli-> errno = 0) // checks whether the current connection is successful.
{
$ SQL = "INSERT INTO student (id, name, age, address) VALUES ('8', 'kay ', '23', 'xian ')";
$ Result = $ mysqli-> query ($ SQL );
Echo $ mysqli-> affected_rows; // Number of affected rows
}
Else
{
Echo $ mysqli-> error; // output the current error message
Exit ();
}
?>

You can call the affected_rows attribute of the mysqli object to obtain the number of affected rows.
5. Close database connection
After a database connection is used, call the close method of the mysqli object to close it.
Copy codeThe Code is as follows:
<? Php
...
$ Mysqli-> close ();
?>

6. Bind Parameters
The binding parameters in PHP are the same as those in the pre-processing SQL statements in Java. When an SQL statement is executed repeatedly, You can bind parameters to improve the SQL Execution speed.
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "root ","");
$ Mysqli-> select_db ("mydb ");
If ($ mysqli-> errno = 0) // checks whether the current connection is successful.
{
$ SQL = "INSERT INTO student (id, name, age, address) VALUES (?,?,?,?) ";
$ Stmt = $ mysqli-> stmt_init (); // create a preprocessing object
$ Stmt-> prepare ($ SQL); // preprocessing SQL
$ Stmt-> bind_param ("isis", $ id, $ name, $ age, $ address); // set the first parameter of the bound variable to the Data Type of the variable.
For ($ I = 12; I I <100; $ I ++)
{
$ Id = $ I + 1;
$ Name = "Fan Kai ";
$ Age = 23;
$ Address = "xian ";
$ Stmt-> execute (); // execute an SQL statement
}
Echo $ mysqli-> affected_rows; // Number of affected rows
$ Stmt-> close (); // release the memory occupied by the preprocessing object
$ Mysqli-> close (); // close the database connection
}
Else
{
Echo $ mysqli-> error; // output the current error message
Exit ();
}
?>

Note that the first parameter of the bind_param method specifies the Data Type of the variable that follows. The data types are as follows:
① I: All Integer types.
② D: All double and float types.
③ B: Blob type.
④ S: Other data types include strings.
7. Result binding
Result binding is used to bind query results to some variables.
Copy codeThe Code is as follows:
<? Php
$ Mysqli = new mysqli ("localhost", "root ","");
$ Mysqli-> select_db ("mydb ");
If ($ mysqli-> errno = 0) // checks whether the current connection is successful.
{
$ SQL = "SELECT * FROM student ";
$ Stmt = $ mysqli-> stmt_init (); // create a preprocessing object
$ Stmt-> prepare ($ SQL); // preprocessing SQL
$ Stmt-> bind_result ($ id, $ name, $ age, $ address); // bind the query result field to the variable
$ Stmt-> execute (); // execute an SQL statement
While ($ stmt-> fetch () // The fetch method is used to obtain each row in the result set and assign the corresponding field value to the variable.
{
Echo "$ id: $ name: $ age: $ address". "<br> ";
}
$ Stmt-> close (); // release the memory occupied by the preprocessing object
$ Mysqli-> close (); // close the database connection
}
Else
{
Echo $ mysqli-> error; // output the current error message
Exit ();
}
?>

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.