UNIT V USING TRANSACTION AND STORED PROCEDURES IN MYSQL WHAT ARE TRANSACTIONS? Database transactions are sets of queries that must execute in such a way so that if one query fails to execute completely they all fail. For instance, suppose that you have a set of three queries, the second dependent on the results of the first, and the third dependent on the results of the second. If the second query fails, you need to have a way to negate the results of the first query; similarly, if the third query fails, you need to negate the results of the first and second queries, as well. Basic Syntax Used in Transactions You need to understand the following key terms when thinking about using transactions with MySQL: . COMMIT—this command occurs at the end of the series of queries in your transaction and is issued only if all the required queries have executed successfully. . ROLLBACK—this command is used when one or more of the series of queries in your transaction fails and resets the affected tables to their pre-transaction state. Going back to the scenario mentioned at the start of this discussion, of three queries dependent on each other, a sequence of events in the MySQL command-line interface might look something like this: 1. Issue the BEGIN command to begin a new transaction. 2. Select a value from table1 to insert into table2. 3. If a value cannot be selected from table1, issue a ROLLBACK command to ensure that the transaction ends and that the tables return to their previous state. 4. If a value can be selected from table1, insert a value into table2. 5. If the insertion of a record into table2 fails, issue a ROLLBACK command to ensure that the transaction ends and that the tables return to their previous state. 6. If a value can be inserted into table1, insert a value into table2. 7. If the insertion of a record into table3 fails, issue a ROLLBACK command to ensure that the transaction ends and that the tables return to their previous state. 8. However, if the insertion of a record into table3 is successful, issue a COMMIT command to ensure that the transaction ends and that the tables update appropriately.
36
Embed
UNIT V USING TRANSACTION AND STORED PROCEDURES IN MYSQL · PHP but with very old versions of MySQL, you might have used the mysql_* fam ily of functions. You might also find code
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
UNIT V
USING TRANSACTION AND STORED PROCEDURES IN MYSQL
WHAT ARE TRANSACTIONS?
Database transactions are sets of queries that must execute in such a way so that if one query fails to
execute completely they all fail.
For instance, suppose that you have a set of three queries, the second dependent on the results of the
first, and the third dependent on the results of the second. If the second query fails, you need to have a
way to negate the results of the first query; similarly, if the third query fails, you need to negate the
results of the first and second queries, as well.
Basic Syntax Used in Transactions
You need to understand the following key terms when thinking about using transactions with MySQL:
. COMMIT—this command occurs at the end of the series of queries in your transaction and is issued
only if all the required queries have executed successfully.
. ROLLBACK—this command is used when one or more of the series of queries in your transaction fails
and resets the affected tables to their pre-transaction state.
Going back to the scenario mentioned at the start of this discussion, of three queries dependent on each
other, a sequence of events in the MySQL command-line interface might look something like this:
1. Issue the BEGIN command to begin a new transaction.
2. Select a value from table1 to insert into table2.
3. If a value cannot be selected from table1, issue a ROLLBACK command to ensure that
the transaction ends and that the tables return to their previous state.
4. If a value can be selected from table1, insert a value into table2.
5. If the insertion of a record into table2 fails, issue a ROLLBACK command to ensure that
the transaction ends and that the tables return to their previous state.
6. If a value can be inserted into table1, insert a value into table2.
7. If the insertion of a record into table3 fails, issue a ROLLBACK command to ensure that
the transaction ends and that the tables return to their previous state.
8. However, if the insertion of a record into table3 is successful, issue a COMMIT command
to ensure that the transaction ends and that the tables update appropriately.
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the acronym ACID −
Atomicity − This ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled
back to their former state.
Consistency − This ensures that the database properly changes states upon a successfully committed transaction.
Isolation − This enables transactions to operate independently on and transparent to each
other.
Durability − This ensures that the result or effect of a committed transaction persists in case of a system failure.
Working Example Using Transactions
For the purposes of this example, suppose that you’ve created an online storefront with database tables
that hold inventory, sales records, and the line items for the sales records. The CREATE statements
might look something like this:
CREATE TABLE store_inventory (
id int not null primary key auto_increment,
item_name varchar(50),
item_price float(6,2),
item_qty int
) ENGINE=InnoDB;
CREATE TABLE store_orders (
id int not null primary key auto_increment,
purchaser_name varchar(50),
purchase_date datetime
) ENGINE=InnoDB;
CREATE TABLE store_orders_items (
id int not null primary key auto_increment,
order_id int,
inventory_id int,
item_qty int
) ENGINE=InnoDB;
In the store_inventory table for this example, you can find two records:
If a shopper wants to purchase two Great Books and one Awesome CD through your online store, the
process would go something like this:
1. The user completes an online form and attempts to pay for the purchases, so issue a BEGIN command
for the transaction that would be part of the checkout script:
BEGIN;
2. Decrement the quantity of items in the store_inventory table:
UPDATE store_inventory SET item_qty = item_qty - 2 WHERE id = 1;
UPDATE store_inventory SET item_qty = item_qty - 1 WHERE id = 2;
3. Add a record to the store_orders table:
INSERT INTO store_orders (purchaser_name, purchase_date)
VALUES (‘John Smith’, now());
4. If adding the record fails, issue a ROLLBACK command to reset the available quantity of the items:
ROLLBACK;
5. If adding the record succeeds, get the ID of the record just added and use it in your query to add line
items to the sales record by inserting records in the store_orders_items table:
INSERT INTO store_orders_items (order_id, inventory_id, item_qty)
VALUES (‘1’, ‘1’, ‘2’); INSERT INTO store_orders_items (order_id, inventory_id, item_qty)
VALUES (‘1’, ‘2’, ‘1’);
6. If adding the records fails, issue a ROLLBACK command to reset the available quantity of the items and
remove the record in store_orders:
ROLLBACK;
7. If adding the records succeeds but the subsequent charging of a credit card or other payment
method fails, issue a ROLLBACK command to reset the available quantity of the items, remove the
record in store_orders, and remove the records in store_orders_items:
ROLLBACK;
8. If adding the records succeeds and the subsequent charging of a credit card or other payment method
succeeds, issue a COMMIT command to ensure that all the changes are stored and the transaction ends:
COMMIT;
WHAT ARE STORED PROCEDURES?
A stored procedure is a segment of declarative SQL statements stored inside the database catalog. A
stored procedure can be invoked by triggers, other stored procedures, and applications such
as Java, Python, PHP.
You might be thinking that you don’t store any procedures on the web server, but in fact you do.
185: $display_block = “<p>Your entry has been added. Would you
186: like to <a href=\”addentry.php\”>add another</a>?</p>”;
187: }
188: ?>
189: <!DOCTYPE html>
190: <head>
191: <title>Add an Entry</title>
192: </head>
193: <body>
194: <h1>Add an Entry</h1>
195: <?php echo $display_block; ?>
196: </body>
197: </html>
The else condition on Line 90 is invoked if there is a value in $_POST, meaning that the user has
submitted the form. In this simple example, two fields were designated as required fields: the first name
and last name of the person. So, lines 92–95 check for values in $_POST[‘f_name’] and $_POST[‘l_name’] and redirect the user back to the form if either value is missing.
VIEWING RECORDS
Listing 20.4 shows the select-and-view script called selentry.php, which has three parts: the record-
selection form (lines 5–42), the code to display the record contents (lines 43–172), and the HTML
template that displays the dynamically generated strings (lines 176–184). Because this code is long, the
listing is broken into smaller chunks for discussion.
If you verified your work in the preceding section by issuing queries through the MySQL monitor or
other interface, you probably became tired of typing SELECT * FROM... for every table.
LISTING 20.4 Script Called selentry.php for Selecting and Viewing
a Record
1: <?php
2: include ‘ch20_include.php’; 3: doDB();
4:
5: if (!$_POST) {
6: //haven’t seen the selection form, so show it
7: $display_block = “<h1>Select an Entry</h1>”;
8:
9: //get parts of records
10: $get_list_sql = “SELECT id,
11: CONCAT_WS(‘, ‘, l_name, f_name) AS display_name
12: FROM master_name ORDER BY l_name, f_name”; 13: $get_list_res = mysqli_query($mysqli, $get_list_sql)
14: or die(mysqli_error($mysqli));
15:
16: if (mysqli_num_rows($get_list_res) < 1) {
17: //no records
18: $display_block .= “<p><em>Sorry, no records to select!</em></p>”;
19:
20: } else {
21: //has records, so get results and print in a form
Built-in Comments Your blog is your home, and comments provide a space for your friends and
followers to engage with your content.
Search Engine Optimized WordPress is optimized for search engines right out of the box.
Multilingual WordPress is available in more than 70 languages.
Freedom WordPress is licensed under the GPL which was created to protect your freedoms.
Easy Installation and Upgrades WordPress has always been easy to install and upgrade.
ADVANTAGES OF WORDPRESS
As mobile has become the best place to fetch traffic for business websites, they need to be responsive
to reach the potential buyers on the mobile channel. WordPress offers a responsive design which
ensures that your website runs seamlessly on different devices, without having to put in extra effort for
developing separate websites to run on them.
Multiple Theme Options
Themes decide the look and navigation of the site. With WordPress, there are multiple options in
themes that can be customized according to the business requirements. Users can download the
themes according to the category and need and play with them to build appealing websites that
replicate their business brand with an impressive online presence.
Plugins for Customization
Plugins are the backbone of this platform. By making use of plugins, users can customize the site and
add the desired features and functionalities to it. All that is needed to be done for adding a new feature
to the site is to install a plugin. And amazingly, there is a large number available and most of them are
free of cost or reasonably priced.
WooCommerce for E-commerce
WooCommerce, the free eCommerce plugin for WordPress, enables the creation of highly appealing and
feature-packed e-commerce stores. WooCommerce integrates seamlessly with WordPress and serves as
a powerful e-commerce solution which gives complete control to both store owners and developers so
that they can sell their goods online.
Self-Hosted Platform
WordPress is a well-known blogging platform as it offers the choice of going self-hosted. Self-hosting
means that the user can choose any hosting provider and install a software WordPress.org on it. A self-
hosted WordPress blog is easy to use and relatively inexpensive. The user can choose his own custom
domain name instead of sub-domain name.
Community Support
The most interesting and useful part of WordPress is the extensive community support it has. There is
the largest number of developers available for WordPress in the world. The platform provides wide
range options in plugins, themes, and software for developers to use while creating websites with this
platform. The community offers reliable support to developers when needed.
SEO-Friendly
Search engines love WordPress because the code is simple and clean that makes it easy for them to read
and index the content on the site. Additionally, it gives control to customize the SEO components for
each page so that they can secure high search rankings. Also, there are lots of plugins available for
WordPress which can extend the website’s reach.
Easy Social Media Integration
WordPress extends the benefit of easy social media integration too which enables business websites to
extend their reach by harnessing social channels. This means that getting traffic to these sites become
easier by extending the social reach. There is no need to login to the social accounts separately as the
website integrates seamlessly with all of them.
Outstanding Scalability
With WordPress, the site can grow as the business grows because of the outstanding scalability of this
platform. It is possible for the site to have thousands of pages or blog posts added to it, without
compromising its performance at all. For this reason, WordPress serves as an ideal platform for
businesses that foresee extensive growth in the future.
Consider Us As Your Ideal WordPress Partner
Considering all the extensive advantages that WordPress CMS brings, it emerges as an excellent choice
for creating a new business website or revamping a current one as well. After all, having an impressive
online presence is essential for connecting with the potential customers and taking your business to the
next level. At OrangeMantra, we bring a complete range of WordPress services at your doorstep. From
design to development, customization, migration, upgrade, maintenance, and support, our expert
developers cater them all.
In addition to our expertise in WordPress, we also extend services in other popular e-commerce
platforms such as Magento, Shopify, PrestaShop, and more. We also work on high-end web and mobile
technologies. Whether you are looking for advanced enterprise-level applications or smart mobility
solutions for any of the mobile platforms, we provide them all. Our team comprises of seasoned
professionals who are adept at the latest technologies such as Big Data, Blockchain, AR, VR, the IoT and
more. Our track record is exemplary as we have worked on a large number of projects with some
reputed Indian and global brands. OrangeMantra is a one-stop technology destination that designs
versatile IT solutions for diverse business requirements.
Table of Contents
mysql_affected_rows — Get number of affected rows in previous MySQL operation mysql_client_encoding — Returns the name of the character set mysql_close — Close MySQL connection mysql_connect — Open a connection to a MySQL Server mysql_create_db — Create a MySQL database mysql_data_seek — Move internal result pointer mysql_db_name — Retrieves database name from the call to mysql_list_dbs mysql_db_query — Selects a database and executes a query on it mysql_drop_db — Drop (delete) a MySQL database mysql_errno — Returns the numerical value of the error message from previous MySQL
operation mysql_error — Returns the text of the error message from previous MySQL operation mysql_escape_string — Escapes a string for use in a mysql_query mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or
both mysql_fetch_assoc — Fetch a result row as an associative array mysql_fetch_field — Get column information from a result and return as an object mysql_fetch_lengths — Get the length of each output in a result mysql_fetch_object — Fetch a result row as an object mysql_fetch_row — Get a result row as an enumerated array mysql_field_flags — Get the flags associated with the specified field in a result mysql_field_len — Returns the length of the specified field mysql_field_name — Get the name of the specified field in a result mysql_field_seek — Set result pointer to a specified field offset mysql_field_table — Get name of the table the specified field is in mysql_field_type — Get the type of the specified field in a result mysql_free_result — Free result memory mysql_get_client_info — Get MySQL client info mysql_get_host_info — Get MySQL host info mysql_get_proto_info — Get MySQL protocol info mysql_get_server_info — Get MySQL server info mysql_info — Get information about the most recent query mysql_insert_id — Get the ID generated in the last query mysql_list_dbs — List databases available on a MySQL server mysql_list_fields — List MySQL table fields mysql_list_processes — List MySQL processes mysql_list_tables — List tables in a MySQL database mysql_num_fields — Get number of fields in result mysql_num_rows — Get number of rows in result mysql_pconnect — Open a persistent connection to a MySQL server mysql_ping — Ping a server connection or reconnect if there is no connection mysql_query — Send a MySQL query mysql_real_escape_string — Escapes special characters in a string for use in an SQL
statement mysql_result — Get result data mysql_select_db — Select a MySQL database mysql_set_charset — Sets the client character set mysql_stat — Get current system status
mysql_tablename — Get table name of field mysql_thread_id — Return the current thread ID mysql_unbuffered_query — Send an SQL query to MySQL without fetching and uffering