Dynamic websites lec3


Published on

PLSQL slides describes procedures, triggers and functions in a simple way

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Dynamic websites lec3

  1. 1. Dynamic WebsitesPHP with Oracle DB By Belal Arfa
  2. 2. Section 3In this section will discuss1- Quiz 1 Notes2- Quiz 23- Install Oracle 11g ex4- SqlDev5- PL/SQL6- Stored Procedure7- Function8- Triggers9- HTML
  3. 3. Quiz (2)Relations:Classes(class, type, country, numGuns, bore, displacement)Ships(name, class, launched)Battles(name, date)Outcomes(ship, battle, result)Queries:a) Find the countries whose ships had the largest number of guns.b) Find the classes of ships at least one of which was sunk in a battle.c) Find the names of the ships with a 16-inch bore.d) Find the battles in which ships of the Kongo class participated.
  4. 4. Quiz (2) Answera) SELECT country FROM classes WHERE numGuns = (SELECT MAX(numGuns) from classes);b) SELECT DISTINCT class FROM Ships WHERE name IN (SELECT ship FROM Outcomes WHERE result = ‘sunk’);c) SELECT name FROM ships WHERE class IN (SELECT class from classes where bore = 16); - SELECT name FROM ships, classes WHERE ships.class = classes.class AND bore = 16;d) SELECT DISTINCT battle FROM ships, outcomes WHERE class = ‘Kongo’;
  5. 5. Install Oracle 11g exBe aware of OS type, Processor type and Oracle version type.Download it from Oracle● Start Setup● Next.....● Enter Password be aware of this password because it will the system password● Next....● Install....● Finish
  6. 6. Sql Developer How to connect to your Database
  7. 7. PL/SQLWhat is PL/SQL?PL/SQL stands for Procedural Language extension of SQL.PL/SQL is a combination of SQL along with the procedural features of programming languages.It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.Advantages ● Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and reused. ● Procedural Language Capability: PL SQL consists of procedural language constructs such as conditional statements (if else statements) and loops like (FOR loops). ● Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single block, thereby reducing network traffic. ● Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a PL/SQL program. Once an exception is caught, specific actions can be taken depending upon the type of the exception or it can be displayed to the user with a message.
  8. 8. Stored ProceduresA stored procedure is a named PL/SQL block which performs one or morespecific task. This is similar to a procedure in other programming languages.We can pass parameters to procedures in three ways.1) IN-parameters2) OUT-parameters3) IN OUT-parametersA procedure may or may not return any value.
  9. 9. Stored ProcedureSyntaxCREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]IS Declaration sectionBEGIN Execution sectionEXCEPTION Exception sectionEND;IS - marks the beginning of the body of the procedure and is similar to DECLARE inanonymous PL/SQL Blocks.The code between IS and BEGIN forms the Declaration section.The syntax within the brackets [ ] indicate they are optional. By using CREATE ORREPLACE together the procedure is created if no other procedure with the same nameexists or the existing procedure is replaced with the current code.
  10. 10. Stored ProcedureExampleCREATE OR REPLACE PROCEDURE insertDBUSERISBEGIN INSERT INTO DBUSER (USER_ID, USERNAME, PASSWORD, CREATED_DATE) VALUES (1, Belal,123, SYSDATE); COMMIT;END;/How to execute a Stored Procedure?There are two ways to execute a procedure.1) From the SQL prompt: EXECUTE [or EXEC] procedure_name;2) Within another procedure – simply use the procedure name: procedure_name;NOTE: In the examples given above, we are using backward slash ‘/’ at the end of the program. Thisindicates the oracle engine that the PL/SQL program has ended and it can begin processing thestatements.
  11. 11. FunctionWhat is a Function in PL/SQL?A function is a named PL/SQL Block which is similar to a procedure. The major differencebetween a procedure and a function is, a function must always return a value, but aprocedure may or may not return a value.SyntaxCREATE [OR REPLACE] FUNCTION function_name [parameters]RETURN return_datatype;ISDeclaration_sectionBEGINExecution_sectionReturn return_variable;EXCEPTIONexception sectionReturn return_variable;END;
  12. 12. Function1) Return Type: The header section defines the return type of the function. The returndatatype can be any of the oracle datatypes like varchar, number etc.2) The execution and exception section both should return a value which is of the datatype defined in the header section.For example, let’s create a function called employer_details_funcCREATE OR REPLACE FUNCTION employer_details_func RETURN VARCHAR(20); IS emp_name VARCHAR(20); BEGIN SELECT first_name INTO emp_name FROM emp_tbl WHERE empID = 100; RETURN emp_name; END; /
  13. 13. FunctionHow to execute a PL/SQL Function?A function can be executed in the following ways.1) Since a function returns a value we can assign it to a variable.employee_name := employer_details_func;If ‘employee_name’ is of datatype varchar we can store the name of the employeeby assigning the return type of the function to it.2) As a part of a SELECT statementSELECT employer_details_func FROM dual;3) In a PL/SQL Statements like,dbms_output.put_line(employer_details_func);This line displays the value returned by the function.
  14. 14. TriggersA trigger is a pl/sql block structure which is fired when a DMLstatements like Insert, Delete, Update is executed on adatabase table.A trigger is triggered automatically when an associated DMLstatement is executed.
  15. 15. TriggersSyntax: CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS old NEW AS new] [FOR EACH ROW] WHEN (condition) BEGIN --- sql statements END;
  16. 16. Triggers● CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given name or overwrites an existing trigger with the same name.● {BEFORE | AFTER } - This clause indicates at what time should the trigger get fired. i.e for example: before or after updating a table.● {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More than one triggering events can be used together separated by OR keyword. The trigger gets fired at all the specified triggering event.● [OF col_name] - This clause is used with update triggers. This clause is used when you want to trigger an event only when a specific column is updated.
  17. 17. Triggers● [ON table_name] - This clause identifies the name of the table to which the trigger is associated.● [REFERENCING OLD AS old NEW AS new] - This clause is used to reference the old and new values of the data being changed. By default, you reference the values as :old.column_name or :new. column_name. The reference names can also be changed from old (or new) to any other user-defined name. You cannot reference old values when inserting a record, or new values when deleting a record, because they do not exist.● [FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is executed(i.e.statement level Trigger).● WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for rows that satisfy the condition specified.
  18. 18. TriggersFor Example: The price of a product changes constantly. It is important to maintain thehistory of the prices of the products.We can create a trigger to update the product_price_history table when the price of theproduct is updated in the product table.1) Create the product table and product_price_history tableCREATE TABLE product_price_history(product_id number(5),product_name varchar2(32),supplier_name varchar2(32),unit_price number(7,2) );CREATE TABLE product(product_id number(5),product_name varchar2(32),supplier_name varchar2(32),unit_price number(7,2) );
  19. 19. Triggers2) Create the price_history_trigger and execute it.CREATE or REPLACE TRIGGER price_history_triggerBEFORE UPDATE OF unit_priceON productFOR EACH ROWBEGININSERT INTO product_price_historyVALUES(:old.product_id,:old.product_name,:old.supplier_name,:old.unit_price);END;/
  20. 20. Triggers3) Lets update the price of a product.UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100Once the above update query is executed, the trigger fires and updates theproduct_price_history table.4)If you ROLLBACK the transaction before committing to the database, the data insertedto the table is also rolled back.
  21. 21. HTMLHTML or Hypertext Markup Language is the most widely used language on Web.Technically, HTML is not a programming language, but rather a markuplanguage.Before beginning:its important that you know Windows. A working knowledge of Windowsmakes it much easier to learn HTML.You should be familiar with:Basic word processing using any text editor..Basic understanding on internet browsing using a browser like Google Chromeor Firefox etc.
  22. 22. HTMLCreating HTML Document: - Open Notepad or another text editor and type: <html> <head> <title>This is document title</title> </head> <body> <h1>This is a heading</h1> <p>Document description goes here.....</p> </body> </html> - Name the file template.html. - Click Save.
  23. 23. HTMLNow you have created one HTML page and you can use a Web Browser toopen this HTML file to see the result.Hope you understood that Web Pages are nothing but they are simple HTMLfiles with some content which can be rendered using Web Browsers.Here <html>, <head>,...<p>, <h1> etc. are called HTML tags.HTML tags are building blocks of an HTML document.NOTE: One HTML file can have extension as .htm or .html. So you can useeither of them based on your comfort.
  24. 24. HTMLHTML Document Structure:An HTML document starts and ends with <html> and >/html> tags. These tagstell the browser that the entire document is composed in HTML. Inside thesetwo tags, the document is split into two sections:The <head>...</head> elements, which contain information about thedocument such as title of the document, author of the document etc.The <body>...</body> elements, which contain the real content of thedocument that you see on your screen.HTML Tags and Elements:HTML language is a markup language and we use many tags to markup text. Youhave seen <html> etc. are called HTML tags or HTML elements.Every tag consists of a tag name, sometimes followed by an optional list of tagattributes , all placed between opening and closing brackets (< and >).According to the HTML standard, tag and attribute names are not case-sensitive.Theres no difference in effect between <HEAD> and <HeaD>;
  25. 25. HTMLHTML Attributes:An attribute is used to define the characteristics of an element and is placed inside theelements opening tag.All attributes are made up of two parts: a name and a value:The name is the property you want to set.The value is what you want the value of the property to be.The value of the attribute should be put in double quotation marks, and is separated fromthe name by the equals sign. <font face="arial" color="#CC0000">The four core attributes that can be used on the majority of HTML elements(although not all) are: id title class style<p style="font-family:arial; color:#FF0000;">Some text...</p>
  26. 26. HTMLCreate Headings - The <hn> Elements:Any documents starts with a heading. You use different sizes for yourheadings. HTML also have six levels of headings, which use the elements<h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. While displaying any heading,browser adds one line before and after that heading.Example:<h1>This is heading 1</h1><h2>This is heading 2</h2><h3>This is heading 3</h3><h4>This is heading 4</h4><h5>This is heading 5</h5><h6>This is heading 6</h6>
  27. 27. HTMLLine BreaksHello<br />You come most carefully upon your hour.<br />Thanks<br /> MahnazCenter Content<p>This is not in the center.</p><center> <p>This is in the center.</p> </center>Bold Text<p>The following word uses a <b>bold</b> typeface.</p>Italic Text<p>The following word uses a <i>italicized</i> typeface.</p>
  28. 28. HTMLStyle TagThe HTML <style> tag is used for declaring style sheets within the head of your HTMLdocument.<head><style type="text/css"> h1 { color:#F1F1F1 }</style></head><html> <body style="background-color:yellow;"> <h2 style="background-color:red;">This is a heading</h2> <p style="background-color:green;">This is a paragraph.</p> </body></html>