# PHP PDO 事務與自動提交
現在通過 PDO 連接上了,在開始進行查詢前,必須先理解 PDO 是如何管理事務的。
事務支持四大特性(ACID):
* 原子性(Atomicity)
* 一致性(Consistency)
* 隔離性(Isolation)
* 持久性(Durability)
通俗地講,在一個事務中執行的任何操作,即使是分階段執行的,也能保證安全地應用于數據庫,并在提交時不會受到來自其他連接的干擾。
事務操作也可以根據請求自動撤銷(假設還沒有提交),這使得在腳本中處理錯誤更加容易。
事務通常是通過把一批更改"積蓄"起來然后使之同時生效而實現的;這樣做的好處是可以大大地提供這些更改的效率。
換句話說,事務可以使腳本更快,而且可能更健壯(不過需要正確地使用事務才能獲得這樣的好處)。
不幸的是,并非每種數據庫都支持事務,因此當第一次打開連接時,PDO 需要在所謂的"自動提交"模式下運行。
自動提交模式意味著,如果數據庫支持,運行的每個查詢都有它自己的隱式事務,如果數據庫不支持事務,則沒有。
如果需要一個事務,則必須用 PDO::beginTransaction() 方法來啟動。如果底層驅動不支持事務,則拋出一個 PDOException 異常(不管錯誤處理設置是怎樣的,這都是一個嚴重的錯誤狀態)。
一旦開始了事務,可用 PDO::commit() 或 PDO::rollBack()來完成,這取決于事務中的代碼是否運行成功。
**注意:** PDO 僅在驅動層檢查是否具有事務處理能力。如果某些運行時條件意味著事務不可用,且數據庫服務接受請求去啟動一個事務,PDO::beginTransaction() 將仍然返回 TRUE 而且沒有錯誤。 試著在 MySQL 數據庫的 MyISAM 數據表中使用事務就是一個很好的例子。
當腳本結束或連接即將被關閉時,如果尚有一個未完成的事務,那么 PDO 將自動回滾該事務。這種安全措施有助于在腳本意外終止時避免出現不一致的情況——如果沒有顯式地提交事務,那么假設是某個地方出錯了,所以執行回滾來保證數據安全。
**注意:** 只有通過 PDO::beginTransaction() 啟動一個事務后,才可能發生自動回滾。如果手動發出一條查詢啟動事務, 則 PDO 無法知曉,從而在必要時不能進行回滾。
在事務中執行批處理:
在下面例子中,假設為新員工創建一組條目,分配一個為23的ID。除了登記此人的基本數據之外,還需要記錄他的工資。
兩個更新分別完成起來很簡單,但通過封閉在 PDO::beginTransaction() 和PDO::commit() 調用中,可以保證在更改完成之前,其他人無法看到這些更改。
如果發生了錯誤,catch 塊回滾自事務啟動以來發生的所有更改,并輸出一條錯誤信息。
```
<?php
try {
$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
$dbh->exec("insert into salarychange (id, amount, changedate)
values (23, 50000, NOW())");
$dbh->commit();
} catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
?>
```
并不局限于在事務中更改,也可以發出復雜的查詢來提取數據,還可以使用那些信息來構建更多的更改和查詢;當事務激活時,可以保證其他人在操作進行當中無法作出更改。
- PHP Array 函數
- PHP array()
- PHP array_change_key_case() 函數
- PHP array_chunk() 函數
- PHP array_combine() 函數
- PHP array_count_values() 函數
- PHP array_diff() 函數
- PHP array_diff_assoc() 函數
- PHP array_diff_key() 函數
- PHP array_diff_uassoc() 函數
- PHP array_diff_ukey() 函數
- PHP array_fill() 函數
- PHP array_filter() 函數
- PHP array_flip() 函數
- PHP array_intersect() 函數
- PHP array_intersect_assoc() 函數
- PHP array_intersect_key() 函數
- PHP array_intersect_uassoc() 函數
- PHP array_intersect_ukey() 函數
- PHP array_key_exists() 函數
- PHP array_keys() 函數
- PHP array_map() 函數
- PHP array_merge() 函數
- PHP array_merge_recursive() 函數
- PHP array_multisort() 函數
- PHP array_pad() 函數
- PHP array_pop() 函數
- PHP array_product() 函數
- PHP array_push() 函數
- PHP array_rand() 函數
- PHP array_reduce() 函數
- PHP array_reverse() 函數
- PHP array_search() 函數
- PHP array_shift() 函數
- PHP array_slice() 函數
- PHP array_splice() 函數
- PHP array_sum() 函數
- PHP array_udiff() 函數
- PHP array_udiff_assoc() 函數
- PHP array_udiff_uassoc() 函數
- PHP array_uintersect() 函數
- PHP array_uintersect_assoc() 函數
- PHP array_uintersect_uassoc() 函數
- PHP array_unique() 函數
- PHP array_unshift() 函數
- PHP array_values() 函數
- PHP array_walk() 函數
- PHP array_walk_recursive() 函數
- PHP arsort() 函數
- PHP asort() 函數
- PHP compact() 函數
- PHP count() 函數
- PHP current() 函數
- PHP each() 函數
- PHP extract() 函數
- PHP in_array() 函數
- PHP key() 函數
- PHP krsort() 函數
- PHP ksort() 函數
- PHP list() 函數
- PHP natcasesort() 函數
- PHP natsort() 函數
- PHP next() 函數
- PHP pos() 函數
- PHP prev() 函數
- PHP range() 函數
- PHP reset() 函數
- PHP rsort() 函數
- PHP shuffle() 函數
- PHP sizeof() 函數
- PHP sort() 函數
- PHP uasort() 函數
- PHP uksort() 函數
- PHP usort() 函數
- PHP Calendar 函數
- PHP cal_days_in_month() 函數
- PHP cal_from_jd() 函數
- PHP cal_info() 函數
- PHP cal_to_jd() 函數
- PHP easter_date() 函數
- PHP easter_days() 函數
- PHP FrenchToJD() 函數
- PHP GregorianToJD() 函數
- PHP JDDayOfWeek() 函數
- PHP JDMonthName() 函數
- PHP JDToFrench() 函數
- PHP JDToGregorian() 函數
- PHP JDToJewish() 函數
- PHP JDToJulian() 函數
- PHP JDToUnix() 函數
- PHP JewishToJD() 函數
- PHP JulianToJD() 函數
- PHP UnixToJD() 函數
- PHP cURL 函數
- PHP curl_close函數
- PHP curl_copy_handle函數
- PHP curl_errno函數
- PHP curl_error函數
- PHP curl_escape函數
- PHP curl_exec函數
- PHP curl_file_create函數
- PHP curl_getinfo函數
- PHP curl_init函數
- PHP curl_multi_add_handle函數
- PHP curl_multi_close函數
- PHP curl_multi_exec函數
- PHP curl_multi_getcontent函數
- PHP curl_multi_info_read函數
- PHP curl_multi_init函數
- PHP curl_multi_remove_handle函數
- PHP curl_multi_select函數
- PHP curl_multi_setopt函數
- PHP curl_multi_strerror函數
- PHP curl_pause函數
- PHP curl_reset函數
- PHP curl_setopt_array函數
- PHP curl_setopt函數
- PHP curl_share_close函數
- PHP curl_share_init函數
- PHP curl_share_setopt函數
- PHP curl_strerror函數
- PHP curl_unescape函數
- PHP curl_version函數
- PHP Date / Time 函數
- PHP checkdate() 函數
- PHP date_default_timezone_get() 函數
- PHP date_default_timezone_set() 函數
- PHP date_sunrise() 函數
- PHP date_sunset() 函數
- PHP date() 函數
- PHP getdate() 函數
- PHP gettimeofday() 函數
- PHP gmdate() 函數
- PHP gmmktime() 函數
- PHP gmstrftime() 函數
- PHP idate() 函數
- PHP localtime() 函數
- PHP microtime() 函數
- PHP mktime() 函數
- PHP strftime() 函數
- PHP strptime() 函數
- PHP strtotime() 函數
- PHP time() 函數
- PHP Directory 函數
- PHP chdir() 函數
- PHP chroot() 函數
- PHP dir() 函數
- PHP closedir() 函數
- PHP getcwd() 函數
- PHP opendir() 函數
- PHP readdir() 函數
- PHP rewinddir() 函數
- PHP scandir() 函數
- PHP Error 和 Logging 函數
- PHP debug_backtrace() 函數
- PHP debug_print_backtrace() 函數
- PHP error_get_last() 函數
- PHP error_log() 函數
- PHP error_reporting() 函數
- PHP restore_error_handler() 函數
- PHP restore_exception_handler() 函數
- PHP set_error_handler() 函數
- PHP set_exception_handler() 函數
- PHP trigger_error() 函數
- PHP Filesystem 函數
- PHP basename() 函數
- PHP chgrp() 函數
- PHP chmod() 函數
- PHP chown() 函數
- PHP clearstatcache() 函數
- PHP copy() 函數
- PHP dirname() 函數
- PHP disk_free_space() 函數
- PHP disk_total_space() 函數
- PHP diskfreespace() 函數
- PHP fclose() 函數
- PHP feof() 函數
- PHP fflush() 函數
- PHP fgetc() 函數
- PHP fgetcsv() 函數
- PHP fgets() 函數
- PHP fgetss() 函數
- PHP file() 函數
- PHP file_exists() 函數
- PHP file_get_contents() 函數
- PHP file_put_contents() 函數
- PHP fileatime() 函數
- PHP filectime() 函數
- PHP filegroup() 函數
- PHP fileinode() 函數
- PHP filemtime() 函數
- PHP fileowner() 函數
- PHP fileperms() 函數
- PHP filesize() 函數
- PHP filetype() 函數
- PHP flock() 函數
- PHP fnmatch() 函數
- PHP fopen() 函數
- PHP fpassthru() 函數
- PHP fputcsv() 函數
- PHP fputs() 函數
- PHP fread() 函數
- PHP fscanf() 函數
- PHP fseek() 函數
- PHP fstat() 函數
- PHP ftell() 函數
- PHP ftruncate() 函數
- PHP fwrite() 函數
- PHP glob() 函數
- PHP is_dir() 函數
- PHP is_executable() 函數
- PHP is_file() 函數
- PHP is_link() 函數
- PHP is_readable() 函數
- PHP is_uploaded_file() 函數
- PHP is_writable() 函數
- PHP is_writeable() 函數
- PHP link() 函數
- PHP linkinfo() 函數
- PHP lstat() 函數
- PHP mkdir() 函數
- PHP move_uploaded_file() 函數
- PHP parse_ini_file() 函數
- PHP pathinfo() 函數
- PHP pclose() 函數
- PHP popen() 函數
- PHP readfile() 函數
- PHP readlink() 函數
- PHP realpath() 函數
- PHP rename() 函數
- PHP rewind() 函數
- PHP rmdir() 函數
- PHP set_file_buffer() 函數
- PHP stat() 函數
- PHP symlink() 函數
- PHP tempnam() 函數
- PHP tmpfile() 函數
- PHP touch() 函數
- PHP umask() 函數
- PHP unlink() 函數
- PHP Filter 函數
- PHP filter_has_var() 函數
- PHP filter_id() 函數
- PHP filter_input() 函數
- PHP filter_input_array() 函數
- PHP filter_list() 函數
- PHP filter_var_array() 函數
- PHP filter_var() 函數
- PHP FTP 函數
- PHP ftp_alloc() 函數
- PHP ftp_cdup() 函數
- PHP ftp_chdir() 函數
- PHP ftp_chmod() 函數
- PHP ftp_close() 函數
- PHP ftp_connect() 函數
- PHP ftp_delete() 函數
- PHP ftp_exec() 函數
- PHP ftp_fget() 函數
- PHP ftp_fput() 函數
- PHP ftp_get_option() 函數
- PHP ftp_get() 函數
- PHP ftp_login() 函數
- PHP ftp_mdtm() 函數
- PHP ftp_mkdir() 函數
- PHP ftp_nb_continue() 函數
- PHP ftp_nb_fget() 函數
- PHP ftp_nb_put() 函數
- PHP ftp_nlist() 函數
- PHP ftp_pasv() 函數
- PHP ftp_put() 函數
- PHP ftp_pwd() 函數
- PHP ftp_quit() 函數
- PHP ftp_raw() 函數
- PHP ftp_rawlist() 函數
- PHP ftp_rename() 函數
- PHP ftp_rmdir() 函數
- PHP ftp_set_option() 函數
- PHP ftp_site() 函數
- PHP ftp_size() 函數
- PHP ftp_ssl_connect() 函數
- PHP ftp_systype() 函數
- PHP HTTP 函數
- PHP header() 函數
- PHP headers_list() 函數
- PHP headers_sent() 函數
- PHP setcookie() 函數
- PHP setrawcookie() 函數
- PHP libxml 函數
- PHP libxml_clear_errors() 函數
- PHP libxml_get_errors() 函數
- PHP libxml_get_last_error() 函數
- PHP libxml_use_internal_errors() 函數
- PHP Mail 函數
- PHP mail() 函數
- PHP Math 函數
- PHP abs() 函數
- PHP acos() 函數
- PHP acosh() 函數
- PHP asin() 函數
- PHP asinh() 函數
- PHP atan() 和 atan2() 函數
- PHP atanh() 函數
- PHP base_convert() 函數
- PHP bindec() 函數
- PHP ceil() 函數
- PHP cos() 函數
- PHP cosh() 函數
- PHP decbin() 函數
- PHP dechex() 函數
- PHP decoct() 函數
- PHP deg2rad() 函數
- PHP exp() 函數
- PHP expm1() 函數
- PHP floor() 函數
- PHP fmod() 函數
- PHP hexdec() 函數
- PHP hypot() 函數
- PHP is_finite() 函數
- PHP is_infinite() 函數
- PHP is_nan() 函數
- PHP lcg_value() 函數
- PHP log() 函數
- PHP log10() 函數
- PHP log1p() 函數
- PHP max() 函數
- PHP min() 函數
- PHP mt_getrandmax() 函數
- PHP mt_rand() 函數
- PHP mt_srand() 函數
- PHP octdec() 函數
- PHP pi() 函數
- PHP pow() 函數
- PHP rad2deg() 函數
- PHP rand() 函數
- PHP round() 函數
- PHP sin() 函數
- PHP sinh() 函數
- PHP sqrt() 函數
- PHP srand() 函數
- PHP tan() 函數
- PHP tanh() 函數
- PHP 5 MySQLi 函數
- PHP mysqli_affected_rows() 函數
- PHP mysqli_autocommit() 函數
- PHP mysqli_change_user() 函數
- PHP mysqli_character_set_name() 函數
- PHP mysqli_close() 函數
- PHP mysqli_commit() 函數
- PHP mysqli_connect_errno() 函數
- PHP mysqli_connect_error() 函數
- PHP mysqli_connect() 函數
- PHP mysqli_data_seek() 函數
- PHP mysqli_debug() 函數
- PHP mysqli_dump_debug_info() 函數
- PHP mysqli_errno() 函數
- PHP mysqli_error_list() 函數
- PHP mysqli_error() 函數
- PHP mysqli_fetch_all() 函數
- PHP mysqli_fetch_array() 函數
- PHP mysqli_fetch_assoc() 函數
- PHP mysqli_fetch_field_direct() 函數
- PHP mysqli_fetch_field() 函數
- PHP mysqli_fetch_fields() 函數
- PHP mysqli_fetch_lengths() 函數
- PHP mysqli_fetch_object() 函數
- PHP mysqli_fetch_row() 函數
- PHP mysqli_field_count() 函數
- PHP mysqli_field_seek() 函數
- PHP mysqli_field_tell() 函數
- PHP mysqli_free_result() 函數
- PHP mysqli_get_charset() 函數
- PHP mysqli_get_client_info() 函數
- PHP mysqli_get_client_stats() 函數
- PHP mysqli_get_client_version() 函數
- PHP mysqli_get_connection_stats() 函數
- PHP mysqli_get_connection_stats() 函數
- PHP mysqli_get_host_info() 函數
- PHP mysqli_get_proto_info() 函數
- PHP mysqli_get_server_info() 函數
- PHP mysqli_get_server_version() 函數
- PHP mysqli_info() 函數
- PHP mysqli_init() 函數
- PHP mysqli_insert_id() 函數
- PHP mysqli_kill() 函數
- PHP mysqli_more_results() 函數
- PHP mysqli_multi_query() 函數
- PHP mysqli_next_result() 函數
- PHP mysqli_num_fields() 函數
- PHP mysqli_num_rows() 函數
- PHP mysqli_options() 函數
- PHP mysqli_ping() 函數
- PHP mysqli_query() 函數
- PHP mysqli_real_connect() 函數
- PHP mysqli_real_escape_string() 函數
- PHP mysqli_refresh() 函數
- PHP mysqli_rollback() 函數
- PHP mysqli_select_db() 函數
- PHP mysqli_set_charset() 函數
- PHP mysqli_sqlstate() 函數
- PHP mysqli_ssl_set() 函數
- PHP mysqli_stat() 函數
- PHP mysqli_stmt_init() 函數
- PHP mysqli_thread_id() 函數
- PHP mysqli_thread_safe() 函數
- PHP PDO
- PHP PDO預定義常量
- PHP PDO連接
- PHP PDO 事務與自動提交
- PHP PDO 預處理語句與存儲過程
- PHP PDO 錯誤與錯誤處理
- PHP PDO 大對象 (LOBs)
- PDO::beginTransaction
- PDO::commit
- PDO::__construct
- PDO::errorCode
- PDO::errorInfo
- PDO::exec
- PDO::getAttribute
- PDO::getAvailableDrivers
- PDO::inTransaction
- PDO::lastInsertId
- PDO::prepare
- PDO::query
- PDO::quote
- PDO::rollBack
- PDO::setAttribute
- PDOStatement::bindColumn
- PDOStatement::bindParam
- PDOStatement::bindValue
- PDOStatement::closeCursor
- PDOStatement::columnCount
- PDOStatement::debugDumpParams
- PDOStatement::errorCode
- PDOStatement::errorInfo
- PDOStatement::execute
- PDOStatement::fetch
- PDOStatement::fetchAll
- PDOStatement::fetchColumn
- PDOStatement::fetchObject
- PDOStatement::getAttribute
- PDOStatement::getColumnMeta
- PDOStatement::nextRowset
- PDOStatement::rowCount
- PDOStatement::setAttribute
- PDOStatement::setFetchMode
- PHP SimpleXML 函數
- PHP __construct() 函數
- PHP addAttribute() 函數
- PHP addChild() 函數
- PHP asXML() 函數
- PHP attributes() 函數
- PHP children() 函數
- PHP getDocNamespaces() 函數
- PHP getName() 函數
- PHP getNamespace() 函數
- PHP registerXPathNamespace() 函數
- PHP simplexml_import_dom() 函數
- PHP simplexml_load_file() 函數
- PHP simplexml_load_string() 函數
- PHP xpath() 函數
- PHP String 函數
- PHP addcslashes() 函數
- PHP addslashes() 函數
- PHP bin2hex() 函數
- PHP chop() 函數
- PHP chr() 函數
- PHP chunk_split() 函數
- PHP convert_cyr_string() 函數
- PHP convert_uudecode() 函數
- PHP convert_uuencode() 函數
- PHP count_chars() 函數
- PHP crc32() 函數
- PHP crypt() 函數
- PHP echo() 函數
- PHP explode() 函數
- PHP fprintf() 函數
- PHP get_html_translation_table() 函數
- PHP hebrev() 函數
- PHP hebrevc() 函數
- PHP html_entity_decode() 函數
- PHP htmlentities() 函數
- PHP htmlspecialchars_decode() 函數
- PHP htmlspecialchars() 函數
- PHP implode() 函數
- PHP join() 函數
- PHP levenshtein() 函數
- PHP localeconv() 函數
- PHP ltrim() 函數
- PHP md5() 函數
- PHP md5_file() 函數
- PHP money_format() 函數
- PHP nl_langinfo() 函數
- PHP nl2br() 函數
- PHP number_format() 函數
- PHP ord() 函數
- PHP parse_str() 函數
- PHP print() 函數
- PHP printf() 函數
- PHP quoted_printable_decode() 函數
- PHP quotemeta() 函數
- PHP rtrim() 函數
- PHP setlocale() 函數
- PHP sha1() 函數
- PHP sha1_file() 函數
- PHP similar_text() 函數
- PHP soundex() 函數
- PHP sprintf() 函數
- PHP sscanf() 函數
- PHP str_ireplace() 函數
- PHP str_pad() 函數
- PHP str_repeat() 函數
- PHP str_replace() 函數
- PHP str_rot13() 函數
- PHP str_shuffle() 函數
- PHP str_split() 函數
- PHP str_word_count() 函數
- PHP strcasecmp() 函數
- PHP strchr() 函數
- PHP strcmp() 函數
- PHP strcoll() 函數
- PHP strcspn() 函數
- PHP strip_tags() 函數
- PHP stripcslashes() 函數
- PHP stripslashes() 函數
- PHP stripos() 函數
- PHP stristr() 函數
- PHP strlen() 函數
- PHP strnatcasecmp() 函數
- PHP strnatcmp() 函數
- PHP strncasecmp() 函數
- PHP strncmp() 函數
- PHP strpbrk() 函數
- PHP strpos() 函數
- PHP strrchr() 函數
- PHP strrev() 函數
- PHP strripos() 函數
- PHP strrpos() 函數
- PHP strspn() 函數
- PHP strstr() 函數
- PHP strtok() 函數
- PHP strtolower() 函數
- PHP strtoupper() 函數
- PHP strtr() 函數
- PHP substr() 函數
- PHP substr_compare() 函數
- PHP substr_count() 函數
- PHP substr_replace() 函數
- PHP trim() 函數
- PHP ucfirst() 函數
- PHP ucwords() 函數
- PHP vfprintf() 函數
- PHP vprintf() 函數
- PHP vsprintf() 函數
- PHP wordwrap() 函數
- PHP XML Parser 函數
- PHP utf8_decode() 函數
- PHP utf8_encode() 函數
- PHP xml_error_string() 函數
- PHP xml_get_current_byte_index() 函數
- PHP xml_get_current_line_number() 函數
- PHP xml_get_error_code() 函數
- PHP xml_parse() 函數
- PHP xml_parse_into_struct() 函數
- PHP xml_parser_create_ns() 函數
- PHP xml_parser_create() 函數
- PHP xml_parser_free() 函數
- PHP xml_parser_get_option() 函數
- PHP xml_parser_set_option() 函數
- PHP xml_set_character_data_handler() 函數
- PHP xml_set_default_handler() 函數
- PHP xml_set_element_handler() 函數
- PHP xml_set_external_entity_ref_handler() 函數
- PHP xml_set_notation_decl_handler() 函數
- PHP xml_set_object() 函數
- PHP xml_set_processing_instruction_handler() 函數
- PHP xml_set_unparsed_entity_decl_handler() 函數
- PHP Zip File 函數
- PHP zip_close() 函數
- PHP zip_entry_close() 函數
- PHP zip_entry_compressedsize() 函數
- PHP zip_entry_compressionmethod() 函數
- PHP zip_entry_filesize() 函數
- PHP zip_entry_name() 函數
- PHP zip_entry_open() 函數
- PHP zip_entry_read() 函數
- PHP zip_open() 函數
- PHP zip_read() 函數
- PHP 雜項函數
- PHP connection_aborted() 函數
- PHP connection_status() 函數
- PHP constant() 函數
- PHP define() 函數
- PHP defined() 函數
- PHP die() 函數
- PHP eval() 函數
- PHP exit() 函數
- PHP get_browser() 函數
- PHP highlight_file() 函數
- PHP highlight_string() 函數
- PHP ignore_user_abort() 函數
- PHP pack() 函數
- PHP strip_whitespace() 函數
- PHP show_source() 函數
- PHP sleep() 函數
- PHP time_nanosleep() 函數
- PHP time_sleep_until() 函數
- PHP uniqid() 函數
- PHP unpack() 函數
- PHP usleep() 函數
- PHP 5 時區
- 免責聲明