PHP and MYSQL transaction processing and PHPMYSQL Transaction Processing

Source: Internet
Author: User
Tags table definition

PHP and MYSQL transaction processing and PHPMYSQL Transaction Processing

/*
There are two main methods to process MYSQL transactions.
1. Use begin, rollback, and commit to implement
Start a transaction
Rollback transaction rollback
Commit transaction validation
2. directly use set to change the mysql automatic submission Mode
MYSQL is automatically submitted by default, that is, when you submit a QUERY, It will be executed directly! We can use
Set autocommit = 0 disable automatic submission
Set autocommit = 1 enable automatic submission
To process the transaction.
When you use set autocommit = 0, all your SQL statements will be processed as transactions until you use commit to confirm or roll back.
Note that a new transaction is also started when you end the transaction! In the first method, only the current transaction is used!
The first method is recommended!
In MYSQL, only INNODB and BDB Data Tables support transaction processing! Other types are not supported!
* **: The default MYSQL database engine is MyISAM, which does not support transactions! If you want MYSQL to support transactions, You can manually modify them:
The method is as follows: 1. Modify the c: \ appserv \ mysql \ my. ini file, find skip-InnoDB, add # in front, and save the file.
2. Enter services. msc in the running state to restart the mysql service.
3. in phpmyadmin, mysql-> show engines; (or execute mysql-> show variables like 'have _ % ';). If InnoDB is YES, InnoDB is supported.
This means that transaction is supported.
4. When creating a table, you can select the InnoDB Engine for the Storage Engine. For a previously created table, you can use mysql-> alter table table_name type = InnoDB;
Or mysql-> alter table table_name engine = InnoDB; to change the data table engine to support transactions.
*/
/************** Transaction -- 1 ***************/
$ Conn = mysql_connect ('localhost', 'root', 'root') or die ("data connection Error !!! ");
Mysql_select_db ('test', $ conn );
Mysql_query ("set names 'gbk'"); // use GBK Chinese encoding;
// Start a transaction
Mysql_query ("BEGIN"); // or mysql_query ("start transaction ");
$ SQL = "INSERT INTO 'user' ('id', 'username', 'sex') VALUES (NULL, 'test1', '0 ')";
$ Sql2 = "insert into 'user' ('did', 'username', 'sex') VALUES (NULL, 'test1', '0 ')"; // I intentionally wrote an error.
$ Res = mysql_query ($ SQL );
$ Res1 = mysql_query ($ sql2 );
If ($ res & $ res1 ){
Mysql_query ("COMMIT ");
Echo 'submission successful. ';
} Else {
Mysql_query ("ROLLBACK ");
Echo 'data rollback. ';
}
Mysql_query ("END ");
/*************** Transaction -- 2 *******************/
/* Method 2 */
Mysql_query ("set autocommit = 0"); // sets that mysql is not automatically submitted and must be submitted using the commit statement.
$ SQL = "INSERT INTO 'user' ('id', 'username', 'sex') VALUES (NULL, 'test1', '0 ')";
$ Sql2 = "insert into 'user' ('did', 'username', 'sex') VALUES (NULL, 'test1', '0 ')"; // I intentionally wrote an error.
$ Res = mysql_query ($ SQL );
$ Res1 = mysql_query ($ sql2 );
If ($ res & $ res1 ){
Mysql_query ("COMMIT ");
Echo 'submission successful. ';
} Else {
Mysql_query ("ROLLBACK ");
Echo 'data rollback. ';
}
Mysql_query ("END"); // do not forget mysql_query ("set autocommit = 1") when the transaction is finished; Submit automatically


/****************** For MyISAM engine databases that do not support transactions, you can use the table locking method: ********************/


// MyISAM & InnoDB support,
/*
Lock tables can LOCK the table used for the current thread. If the table is locked by other threads, blocking occurs until all the locks can be obtained.
Unlock tables can release any lock maintained by the current thread. When the thread publishes another lock tables, or when the connection to the server is closed, all TABLES locked by the current thread are implicitly unlocked.
*/

Mysql_query ("lock tables 'user' WRITE"); // LOCK the 'USER' table
$ SQL = "INSERT INTO 'user' ('id', 'username', 'sex') VALUES (NULL, 'test1', '0 ')";
$ Res = mysql_query ($ SQL );
If ($ res ){
Echo 'submission successful .! ';
} Else {
Echo 'failed! ';
}
Mysql_query ("unlock tables"); // UNLOCK

MyISAM is the default storage engine in MySQL. Generally, not many people care about this. It is a tricky thing to decide what storage engine to use, but let's take a look at it. Here we only consider MyISAM and InnoDB, because these two are the most common.

Next let's answer some questions:
◆ Does your database have a foreign key?
◆ Do you need transaction support?
◆ Do you need full-text indexing?
◆ What query mode do you often use?
◆ How big is your data?

Myisam only supports index Cache

Innodb non-index file data file innodb buffer

Myisam can only manage indexes. When the index data is greater than the allocated resources, it is cached by the operating system. Data Files depend on the operating system cache. Innodb is managed by itself, regardless of the index or data.

Thinking about the above questions can help you find the right direction, but that is not absolute. If you need transaction processing or foreign keys, InnoDB may be a good method. If you need full-text indexing, MyISAM is usually a good choice because it is built in the system. However, we do not often test the 2 million rows of records. Therefore, even if it is slower, we can use Sphinx to obtain full-text indexes from InnoDB.

The size of data is an important factor that affects your choice of storage engines. Large-sized data sets tend to use InnoDB because they support transaction processing and fault recovery. The small size of the database determines the duration of fault recovery. InnoDB can use transaction logs to recover data, which is faster. However, MyISAM may take several hours or even a few days to do these tasks. InnoDB only needs a few minutes.

The habit of operating database tables may also be a factor that has a great impact on performance. For example, COUNT () can be very fast in the MyISAM table, but it may be very painful in the InnoDB table. Primary Key query will be quite fast in InnoDB, but be careful that if our primary key is too long, it will also cause performance problems. A large number of inserts statements are faster in MyISAM, but the updates is faster in InnoDB-especially when the concurrency is large.

So which one do you use? Based on experience, if it is a small application or project, MyISAM may be more suitable. Of course, using MyISAM in a large environment can also be very successful, but this is not always the case. If you plan to use a project with a large amount of data and require transaction processing or foreign key support, you should use InnoDB directly. But remember that InnoDB tables require more memory and storage. Converting a 100 GB MyISAM table to an InnoDB table may cause a bad experience.

========================================================== ==============================

MyISAM: This is the default type. It is based on the traditional ISAM type, and ISAM is the abbreviation of Indexed Sequential Access Method (Sequential Access Method with indexes, it is a standard method for storing records and files. compared with other storage engines, MyISAM has most tools for checking and repairing tables. myISAM tables can be compressed and support full-text search. they are not transaction-safe and do not support foreign keys. If a transaction is rolled back, incomplete rollback is not atomic. If you execute a large number of SELECT statements, MyISAM is a better choice.

InnoDB: This type is transaction-safe. it has the same features as the BDB type and supports foreign keys. the InnoDB table is fast. it has more features than BDB. Therefore, if you need a transaction-safe storage engine, we recommend that you use it. if your data executes a large number of INSERT or UPDATE operations, InnoDB tables should be used for performance considerations,

For the InnoDB type labels that support transactions, AUTOCOMMIT is enabled by default, and the program does not explicitly call BEGIN to start the transaction. As a result, each inserted entry is automatically Commit, the speed is seriously affected. You can call begin before executing the SQL statement. Multiple SQL statements form a transaction (even if you open the autocommit statement), which greatly improves the performance.

========================================================== ======================================

InnoDB and MyISAM are the two most commonly used table types in MySQL, each with its own advantages and disadvantages, depending on the specific application. The following are the known differences between the two.

Innodb
InnoDB provides MySQL with a transaction-safe (ACID compliant) table with transaction (commit), rollback, and crash recovery capabilities. InnoDB provides locking on row level and non-locking read in SELECTs ). These features improve the performance of multi-user concurrent operations. In the InnoDB table, no need to expand the lock escalation, because the row level locks of InnoDB is suitable for a very small space. InnoDB is the first MySQL table engine to provide foreign key constraints (foreign key constraints.

InnoDB is designed to handle large-capacity database systems. Its CPU utilization is incomparable to other disk-based relational database engines. Technically, InnoDB is a complete database system on the MySQL background. InnoDB establishes a dedicated buffer pool in the primary memory for high-speed data buffering and indexing. InnoDB stores data and indexes in tablespaces and may contain multiple files, which is different from others. For example, in MyISAM, tables are stored in separate files. The size of the InnoDB table is limited by the file size of the operating system, generally 2 GB.
All InnoDB tables are stored in the same data file ibdata1 (multiple files or independent tablespace files), which is relatively difficult to back up, the free solution can be copying data files, backing up binlogs, or using mysqldump.


MyISAM
MyISAM is the default storage engine of MySQL.

Each MyISAM table is stored in three files. Frm file storage table definition. The data file is MYD (MYData ). The index file is an extension of MYI (MYIndex.

Because MyISAM is relatively simple, it is much more efficient than InnoDB .. It is a good choice for small applications to use MyISAM.

MyISAM tables are saved as files. Using MyISAM storage in cross-platform data transfer saves a lot of trouble.

The following are some differences between details and specific implementations:

1. InnoDB does not support FULLTEXT indexes.
2. innoDB does not store the specific number of rows in the table. That is to say, when you execute select count (*) from table, InnoDB needs to scan the entire table to calculate the number of rows, however, MyISAM simply needs to read the number of lines saved. Note that when the count (*) statement contains the where condition, the operations on the two tables are the same.
3. For fields of the AUTO_INCREMENT type, InnoDB must contain only the index of this field. However, in the MyISAM table, you can create a joint index with other fields.
4. When deleting FROM table, InnoDB does not create a new table, but deletes a row.
5. the load table from master operation does not work for InnoDB. The solution is to first change the InnoDB TABLE to the MyISAM TABLE, and then change the imported data to the InnoDB TABLE, however, it is not applicable to tables that use additional InnoDB features (such as foreign keys.

In addition, the row lock of the InnoDB table is not absolute. If MySQL cannot determine the scope to be scanned when executing an SQL statement, the InnoDB table will also lock the entire table, for example, update table set num = 1 where name like "% aaa %"

Any type of table is not omnipotent. You only need to select a proper table type for the business type to maximize the performance advantage of MySQL.

========================================================== ======================================


The following are some of the relationships and differences between InnoDB and MyISAM!

1. MySQL 4.0 and above support transactions, including non-max versions. 3.23 requires the max version mysqld to support transactions.

2. If no type is specified during table creation, the default value is myisam. transactions are not supported.
You can run the show create table tablename command to view the table type.

2.1 The start/commit operation on a table that does not support transactions has no effect. It has been submitted before the execution of the commit operation. test:
Execute an msyql:
Use test;
Drop table if exists tn;
Create table tn (a varchar (10) type = myisam;
Drop table if exists ty;
Create table ty (a varchar (10) type = innodb;

Begin;
Insert into tn values ('A ');
Insert into ty values ('A ');
Select * from tn;
Select * from ty;
You can see a record.

Execute another mysql:
Use test;
Select * from tn;
Select * from ty;
Only tn can see one record
Then on the other side
Commit;
You can see the record.

3. You can run the following command to switch the non-transaction table to the transaction (data will not be lost). The innodb table is safer than the myisam table:
Alter table tablename type = innodb;

3.1 innodb tables cannot use the repair table command and myisamchk-r table_name
However, you can use check table and mysqlcheck [OPTIONS] database [tables]

========================================================== ======================================

For mysql to use select for update, it must be for InnoDb and be in a transaction.

The select conditions are different. The Row-level locks and table-level locks are also used.
Instructions for transferring http://www.neo.com.tw/archives/900

Because InnoDB defaults to Row-Level Lock, MySQL will only execute Row lock (only Lock the selected data example) If a specified Primary Key is specified explicitly ), otherwise, MySQL will execute Table Lock (Lock the entire data form ).


For example:

Assume that there is a form products, which contains two columns: id and name. id is the primary key.

Example 1: (specify the primary key and use this document, row lock)

SELECT * FROM products WHERE id = '3' for update;

Example 2: (specify a primary key. If no data is found, no lock is required)

SELECT * FROM products WHERE id = '-1' for update;

Example 2: (no primary key, table lock)

SELECT * FROM products WHERE name = 'mouse 'for update;

Example 3: (the primary key is not clear, table lock)

SELECT * FROM products WHERE id <> '3' for update;

Example 4: (the primary key is not clear, table lock)

SELECT * FROM products WHERE id LIKE '3' for update;

Note 1:
For update only applies to InnoDB and takes effect only in the transaction block (BEGIN/COMMIT ).

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.