SlideShare a Scribd company logo
1 of 141
Download to read offline
FacultyFaculty of Computer Science and Engineering
Introduction to Database Lab CS-232L
Ghulam Ishaq Khan Institute of Engineering
Sciences and Technology, Pakistan
SQL/MYSQL
Contents
Lab#1 Introduction to HTML.....................................................................................................................5
HTML Basics:..........................................................................................................................................5
HTML Images .........................................................................................................................................9
HTML Tables...........................................................................................................................................9
HTML Layouts.......................................................................................................................................11
HTML Forms .........................................................................................................................................13
Lab#2: Introduction to PHP.....................................................................................................................16
PHP Introduction ..................................................................................................................................16
Conditional Statementsin PHP...........................................................................................................19
PHP Loops ............................................................................................................................................22
PHP Functions......................................................................................................................................26
PHP Forms and User Input.................................................................................................................28
Form Validation.....................................................................................................................................29
PHP Include Files.................................................................................................................................31
Lab#3: DBMS, MS Access and Oracle 10g.........................................................................................34
Introduction to DBMS: .........................................................................................................................34
Schemas................................................................................................................................................35
Oracle 10g Logging in as the Database Administrator...................................................................35
Unlocking the Sample User Account:................................................................................................35
Oracle 10g tables .................................................................................................................................38
Lab#4: Introduction to Structure Query Language..............................................................................39
Executing SQL Statements.................................................................................................................39
SQL select statement ..........................................................................................................................39
Displaying table structure....................................................................................................................43
Lab#5: SQL Functions.............................................................................................................................44
Character Manipulation Function.......................................................................................................44
Case Conversion Function .................................................................................................................44
DUAL......................................................................................................................................................45
SYSDATE..............................................................................................................................................46
Type Conversion Functions................................................................................................................47
The NVL Function ................................................................................................................................48
Decode Function ..................................................................................................................................49
Lab#6: Creating and Managing Tables:................................................................................................52
Naming Rules .......................................................................................................................................52
Data Definition Language: ..................................................................................................................52
Data Manipulation Language (DML) .................................................................................................56
SQL Constraints:..................................................................................................................................60
Lab#7: MYSQL .........................................................................................................................................68
MySQL Introduction:............................................................................................................................68
Lab#8: Database connectivity with PHP...............................................................................................74
PHP Database ODBC .........................................................................................................................74
Connecting to an ODBC......................................................................................................................74
Retrieving Records...............................................................................................................................74
PHP MySQL Connect to a Database................................................................................................77
PHP MySQL Create Database and Tables......................................................................................78
PHP MySQL Insert Into.......................................................................................................................81
PHP MySQL Select..............................................................................................................................83
PHP MySQL The Where Clause .......................................................................................................85
PHP MySQL Order By Keyword ........................................................................................................86
PHP MySQL Update............................................................................................................................87
Lab#9: Group functions and sub queries..............................................................................................90
Group Functions...................................................................................................................................91
Group By Clause..................................................................................................................................94
Having clause .......................................................................................................................................96
Order of evaluation of the clauses:....................................................................................................98
SUBQUERIES ......................................................................................................................................98
Using group functions in a subquery...............................................................................................101
Lab#10: SQL Statements......................................................................................................................104
Database Transactions .....................................................................................................................104
Set Operators......................................................................................................................................107
SQL View.............................................................................................................................................111
Lab#11: Introduction to PL/SQL...........................................................................................................115
General syntax to create PL/SQL:...................................................................................................115
Use of PL/SQL variables...................................................................................................................115
PL/SQL IF Statement.........................................................................................................................117
IF/THEN ELSE Statement ................................................................................................................117
Nested IF/THEN ELSE Statement...................................................................................................118
PL/SQL Loops.....................................................................................................................................119
Lab#12: More on PL/SQL .....................................................................................................................123
Cursors ................................................................................................................................................123
Stored Procedures .............................................................................................................................130
PL/SQL Functions..............................................................................................................................131
Trigger..................................................................................................................................................136
Lab#1 Introduction to HTML
HTML Basics:
Writing HTML Using Notepad or TextEdit
Save Your HTML. Run the HTML in Your Browser
HTML headings are defined with the <h1> to <h6> tags.
HTML paragraphs are defined with the <p> tag.
HTML documents are defined by HTML elements.
An HTML element is everything from the start tag to the end tag:
The start tag is often called the opening tag. The end tag is often called the closing tag.
Some HTML elements have empty content. Empty elements are closed in the start tag
Most HTML elements can have attributes
HTML Document Example
<!DOCTYPE html>
<html>
<body>
<p>This is my first paragraph.</p>
</body>
</html>
This example contains 3 HTML elements.
Above Example Explanation
The <p> element:
<p>This is my first paragraph.</p>. The <p> element defines a paragraph in the HTML
document. The element has a start tag <p> and an end tag </p>. The element content
is: This is my first paragraph.
The <body> element:
<body>
<p>This is my first paragraph.</p>
</body>
The <body> element defines the body of the HTML document. The element has a start
tag <body> and an end tag </body>. The element content is another HTML element (a
p element).
The <html> element:
<html>
<body>
<p>This is my first paragraph.</p>
</body>
</html>
The <html> element defines the whole HTML document. The element has a start tag
<html> and an end tag </html>. The element content is another HTML element (the
body element).
HTML Attributes
HTML elements can have attributes. Attributes provide additional information about
an element. Attributes are always specified in the start tag. Attributes come in
name/value pairs like: name="value"
Attribute Example
HTML links are defined with the <a> tag. The link address is specified in the href
attribute: e.g.
<a href="http://www.w3schools.com">This is a link</a>
Always Quote Attribute Values
Attribute values should always be enclosed in quotes.
Double style quotes are the most common, but single style quotes are also allowed.
In some rare situations, when the attribute value itself contains quotes, it is necessary to
use single quotes: name='John "ShotGun" Nelson'
HTML Headings
Headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important heading.
Example
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
HTML Lines
The <hr>tag creates a horizontal line in an HTML page.
The hr element can be used to separate content:
Example
<p>This is a paragraph</p>
<hr><p>This is a paragraph</p>
<hr><p>This is a paragraph</p>
HTML Comments
Comments can be inserted into the HTML code to make it more readable and
understandable. Comments are ignored by the browser and are not displayed.
Comments are written like this:
Example
<!-- This is a comment -->
Note: There is an exclamation point after the opening bracket, but not before the
closing bracket.
<html> defines an HTML document
<body> defines the documents body
<h1> to <h6> defines HTML headings
<hr> define a horizontal line
<!--> defines a comment
<p> defines a paragraph
<br> inserts a single line break
HTML Text Formatting Tags
Tag Description
<b> Defines bold text
<big> Defines big text
<em> Defines emphasized text
<i> Defines a part of text in an alternate voice or mood
<small> Defines small text
<strong> Defines strong text
<sub> Defines subscripted text
<sup> Defines superscripted text
HTML Link Syntax
The HTML code for a link is simple. It looks like this:
<a href="url">Link text</a>
The href attribute specifies the destination of a link.
Example
<a href="http://www.w3schools.com/">Visit W3Schools</a>
HTML Links - The name Attribute
The name attribute specifies the name of an anchor.
The name attribute is used to create a bookmark inside an HTML document.
Note: The upcoming HTML5 standard suggests using the id attribute instead of the
name attribute for specifying the name of an anchor. Using the id attribute actually
works also for HTML4 in all modern browsers.
Bookmarks are not displayed in any special way. They are invisible to the reader.
Example
A named anchor inside an HTML document:
<a name="tips">Useful Tips Section</a>
Create a link to the "Useful Tips Section" inside the same document:
<a href="#tips">Visit the Useful Tips Section</a>
Or, create a link to the "Useful Tips Section" from another page:
<a href="http://www.w3schools.com/html_links.htm#tips">
Visit the Useful Tips Section</a>
The HTML <title> Element
The <title> tag defines the title of the document.
The title element is required in all HTML/XHTML documents.
The title element:
defines a title in the browser toolbar
provides a title for the page when it is added to favorites
displays a title for the page in search-engine results
A simplified HTML document:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
HTML head Elements
Tag Description
<head> Defines information about the document
<title> Defines the title of a document
<base> Defines a default address or a default target for all links on a page
<link> Defines the relationship between a document and an external
resource
<meta> Defines metadata about an HTML document
<script> Defines a client-side script
<style> Defines style information for a document
HTML Images
HTML Images - The <img> Tag and the Src Attribute
In HTML, images are defined with the <img> tag.
The <img> tag is empty, which means that it contains attributes only, and has no closing
tag. To display an image on a page, you need to use the src attribute. Src stands for
"source". The value of the src attribute is the URL of the image you want to display.
Syntax for defining an image:
<img src="url" alt="some_text">
The URL points to the location where the image is stored. An image named "boat.gif",
located in the "images" directory on "www.w3schools.com" has the URL:
http://www.w3schools.com/images/boat.gif. The browser displays the image where the
<img> tag occurs in the document. If you put an image tag between two paragraphs, the
browser shows the first paragraph, then the image, and then the second paragraph.
HTML Images - The Alt Attribute
The required alt attribute specifies an alternate text for an image, if the image cannot be
displayed. The value of the alt attribute is an author-defined text:
<img src="boat.gif" alt="Big Boat">
The alt attribute provides alternative information for an image if a user for some reason
cannot view it (because of slow connection, an error in the src attribute, or if the user
uses a screen reader).
HTML Images - Set Height and Width of an Image
The height and width attributes are used to specify the height and width of an image.
The attribute values are specified in pixels by default:
<img src="pulpit.jpg" alt="Pulpit rock" width="304" height="228">
HTML Tables
Tables are defined with the <table> tag.
A table is divided into rows (with the <tr> tag), and each row is divided into data cells
(with the <td> tag). td stands for "table data," and holds the content of a data cell. A
<td> tag can contain text, links, images, lists, forms, other tables, etc.
Table Example
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
How the HTML code above looks in a browser:
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
HTML Tables and the Border Attribute
If you do not specify a border attribute, the table will be displayed without borders.
Sometimes this can be useful, but most of the time, we want the borders to show.
To display a table with borders, specify the border attribute:
HTML Table Headers
Header information in a table are defined with the <th> tag.
All major browsers display the text in the <th> element as bold and centered.
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
How the HTML code above looks in your browser:
Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
HTML Table Tags
Tag Description
<table> Defines a table
<th> Defines a table header
<tr> Defines a table row
<td> Defines a table cell
<caption> Defines a table caption
<colgroup> Defines a group of columns in a table, for formatting
<col> Defines attribute values for one or more columns in a table
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table
HTML Layouts
Web page layout is very important to make your website look good.
Design your webpage layout very carefully.
Website Layouts
Most websites have put their content in multiple columns (formatted like a magazine or
newspaper).
Multiple columns are created by using <div> or <table> elements. CSS are used to
position elements, or to create backgrounds or colorful look for the pages.
Even though it is possible to create nice layouts with HTML tables, tables were
designed for presenting tabular data - NOT as a layout tool!.
HTML Layouts - Using Tables
A simple way of creating layouts is by using the HTML <table> tag.
Multiple columns are created by using <div> or <table> elements. CSS are used to
position elements, or to create backgrounds or colorful look for the pages.
Using tables is not the correct use of the <table> element. The purpose of the
<table> element is to display tabular data.
The following example uses a table with 3 rows and 2 columns - the first and last row
spans both columns using the colspan attribute:
Example
<!DOCTYPE html>
<html>
<body>
<table width="500" border="0">
<tr>
<td colspan="2" style="background-color:#FFA500;">
<h1>Main Title of Web Page</h1>
</td>
</tr>
<tr>
<td style="background-color:#FFD700;width:100px;text-align:top;">
<b>Menu</b><br>
HTML<br>
CSS<br>
JavaScript
</td>
<td style="background-color:#EEEEEE;height:200px;width:400px;text-align:top;">
Content goes here</td>
</tr>
<tr>
<td colspan="2" style="background-color:#FFA500;text-align:center;">
Copyright © W3Schools.com</td>
</tr>
</table>
</body>
</html>
The HTML code above will produce the following result:
Main Title of Web Page
Menu
HTML
CSS
JavaScript
Content goes here
Copyright © W3Schools.com
HTML Forms
HTML forms are used to pass data to a server. A form can contain input elements like
text fields, checkboxes, radio-buttons, submit buttons and more. A form can also
contain select lists, textarea, fieldset, legend, and label elements.
The <form> tag is used to create an HTML form:
<form>
input elements
</form>
HTML Forms - The Input Element
The most important form element is the input element.
The input element is used to select user information.
An input element can vary in many ways, depending on the type attribute. An input
element can be of type text field, checkbox, password, radio button, submit button, and
more.
The most used input types are described below.
Text Fields
<input type="text">defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
How the HTML code above looks in a browser:
First name:
Last name:
Note: The form itself is not visible. Also note that the default width of a text field is 20
characters.
Password Field
<input type="password">defines a password field:
<form>
Password: <input type="password" name="pwd"></form>
How the HTML code above looks in a browser:
Password:
Note: The characters in a password field are masked (shown as asterisks or circles).
Radio Buttons
<input type="radio">defines a radio button. Radio buttons let a user select ONLY ONE
of a limited number of choices:
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
How the HTML code above looks in a browser:
Male
Female
Checkboxes
<input type="checkbox">defines a checkbox. Checkboxes let a user select ZERO or
MORE options of a limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
How the HTML code above looks in a browser:
I have a bike
I have a car
Submit Button
<input type="submit">defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page
specified in the form's action attribute. The file defined in the action attribute usually
does something with the received input:
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user"><input type="submit"
value="Submit"></form>
How the HTML code above looks in a browser:
Username:
Submit
If you type some characters in the text field above, and click the "Submit" button, the
browser will send your input to a page called "html_form_action.asp". The page will
show you the received input.
HTML Form Tags
Tag Description
<form> Defines an HTML form for user input
<input> Defines an input control
<textarea> Defines a multi-line text input control
<label> Defines a label for an input element
<fieldset> Defines a border around elements in a form
<legend> Defines a caption for a fieldset element
<select> Defines a select list (drop-down list)
<optgroup> Defines a group of related options in a select list
<option> Defines an option in a select list
<button> Defines a push button
Lab#2: Introduction to PHP
PHP Introduction
PHP stands for PHP: Hypertext Preprocessor. It is a server-side scripting language, like
ASP. PHP scripts are executed on the server. It supports many databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.). It is an open source
software. PHP is a powerful tool for making dynamic and interactive Web pages. It is
the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
In this section you will learn about PHP, and how to execute scripts on your server.
PHP File
PHP files can contain text, HTML tags and scripts, PHP files are returned to the browser
as plain HTML, PHP files have a file extension of ".php", ".php3", or ".phtml"
Basic PHP Syntax
A PHP script always starts with <?php and ends with ?>. A PHP script can be placed
anywhere in the document. On servers with shorthand-support, you can start a PHP
script with <? and end with ?>. For maximum compatibility, we recommend that you use
the standard form (<?php) rather than the shorthand form. <?php ?>
A PHP file must have a .php extension. A PHP file normally contains HTML tags, and
some PHP scripting code. Below, we have an example of a simple PHP script that
sends the text "Hello World" back to the browser:
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is
used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print.
In the example above we have used the echo statement to output the text "Hello World".
Comments in PHP
In PHP, we use // to make a one-line comment or /* and */ to make a comment block:
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
PHP Variables
Variables are "containers" for storing information. PHP variables are used to hold values
or expressions. A variable can have a short name, like x, or a more descriptive name,
like carName. Rules for PHP variable names: Variables in PHP starts with a $ sign,
followed by the name of the variable The variable name must begin with a letter or the
underscore character A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ) A variable name should not contain spaces Variable
names are case sensitive (y and Y are two different variables)
Creating (Declaring) PHP Variables
PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
$myCar="Volvo";
After the execution of the statement above, the variable myCar will hold the value
Volvo.
Tip: If you want to create a variable without assigning it a value, then you assign it the
value of null.
Let's create a variable containing a string, and a variable containing a number:
<?php
$txt="Hello World!";
$x=16;
?>
Note: When you assign a text value to a variable, put quotes around the value.
PHP is a Loosely Typed Language
In PHP, a variable does not need to be declared before adding a value to it. In the
example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its
value. In a strongly typed programming language, you have to declare (define) the type
and name of the variable before using it.
Strings in PHP
String variables are used for values that contain characters.
In this chapter we are going to look at the most common functions and operators used
to manipulate strings in PHP.
After we create a string we can manipulate it. A string can be used directly in a function
or it can be stored in a variable.
Below, the PHP script assigns the text "Hello World" to a string variable called $txt:
<?php
$txt="Hello World";
echo $txt;
?>
The output of the code above will be:
Hello World
Now, lets try to use some different functions and operators to manipulate the string.
The Concatenation Operator
There is only one string operator in PHP. The concatenation operator (.) is used to put
two string values together.To concatenate two string variables together, use the
concatenation operator:
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>
The output of the code above will be:
Hello World! What a nice day!
If we look at the code above you see that we used the concatenation operator two
times. This is because we had to insert a third string (a space character), to separate
the two strings.
The strlen() function
The strlen() function is used to return the length of a string.
Let's find the length of a string:
<?php
echo strlen("Hello world!");
?>
The output of the code above will be:
12
The length of a string is often used in loops or other functions, when it is important to
know when the string ends. (i.e. in a loop, we would want to stop the loop after the last
character in the string).
The strpos() function
The strpos() function is used to search for a character/text within a string.
If a match is found, this function will return the character position of the first match. If no
match is found, it will return FALSE.
Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>
The output of the code above will be:
6
The position of the string "world" in the example above is 6. The reason that it is 6 (and
not 7), is that the first character position in the string is 0, and not 1.
PHP Operators
The assignment operator = is used to assign values to variables in PHP.
The arithmetic operator + is used to add values together.
Arithmetic Operators
Comparison Operators
Logical Operators
Conditional Statementsin PHP
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions.
You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
if statement - use this statement to execute some code only if a specified condition is
true
if...else statement - use this statement to execute some code if a condition is true and
another code if the condition is false
if...elseif....else statement - use this statement to select one of several blocks of code
to be executed
switch statement - use this statement to select one of many blocks of code to be
executed
The if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition) code to be executed if condition is true;
The following example will output "Have a nice weekend!" if the current day is Friday:
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
</body>
</html>
Notice that there is no ..else.. in this syntax. The code is executed only if the specified
condition is true.
The if...else Statement
Use the if....else statement to execute some code if a condition is true and another code
if a condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
Example
The following example will output "Have a nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
else
{
echo "Have a nice day!";
}
?>
</body>
</html>
The if...elseif....else Statement
Use the if....elseif...else statement to select one of several blocks of code to be
executed.
Syntax
if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
Example
The following example will output "Have a nice weekend!" if the current day is Friday,
and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a
nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
elseif ($d=="Sun")
{
echo "Have a nice Sunday!";
}
else
{
echo "Have a nice day!";
}
?>
</body>
</html>
PHP Loops
Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal lines in a script we can use loops to
perform a task like this.
In PHP, we have the following looping statements:
while - loops through a block of code while a specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as a
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
The while Loop
The while loop executes a block of code while a condition is true.
Syntax
while (condition)
{
code to be executed;
}
Example
The example below defines a loop that starts with i=1. The loop will continue to run as
long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The do...while Statement
The do...while statement will always execute the block of code once, it will then check
the condition, and repeat the loop while the condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
The example below defines a loop that starts with i=1. It will then increment i with 1, and
write some output. Then the condition is checked, and the loop will continue to run as
long as i is less than, or equal to 5:
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment)
{
code to be executed;
}
Parameters:
init: Mostly used to set a counter (but can be any code to be executed once at the
beginning of the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
increment: Mostly used to increment a counter (but can be any code to be executed at
the end of the iteration)
Note: The init and increment parameters above can be empty or have multiple
expressions (separated by commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as
long as the variable i is less than, or equal to 5. The variable i will increase by 1 each
time the loop runs:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The foreach Loop
The foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value
(and the array pointer is moved by one) - so on the next loop iteration, you'll be looking
at the next array value.
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br />";
}
?>
</body>
</html>
Output:
one
two
three
PHP Functions
The real power of PHP comes from its functions. In PHP, there are more than 700 built-
in functions. In this section we will show you how to create your own functions. To keep
the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function. You may call a function from
anywhere within a page.
Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
PHP function guidelines:
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)
Example
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes
PHP Functions - Adding parameters
To add more functionality to a function, we can add parameters. A parameter is just like
a variable.
Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.
Example 2
The following function has two parameters:
<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?
PHP Functions - Return values
To let a function return a value, use the return statement.
Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Output:
1 + 16 = 17
PHP Forms and User Input
The PHP $_GET and $_POST variables are used to retrieve information from forms,
like user input.
PHP Form Handling
The most important thing to notice when dealing with HTML forms and PHP is that any
form element in an HTML page will automatically be available to your PHP scripts.
Example
The example below contains an HTML form with two input fields and a submit button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
When a user fills out the form above and clicks on the submit button, the form data is
sent to a PHP file, called "welcome.php":
"welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
Output could be something like this:
Welcome John!
You are 28 years old.
Form Validation
User input should be validated on the browser whenever possible (by client scripts).
Browser validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A
good way to validate a form on the server is to post the form to itself, instead of jumping
to a different page. The user will then get the error messages on the same page as the
form. This makes it easier to discover the error.
PHP $_GET Variable
In PHP, the predefined $_GET variable is used to collect values in a form with
method="get".
The $_GET Variable
The predefined $_GET variable is used to collect values in a form with method="get"
Information sent from a form with the GET method is visible to everyone (it will be
displayed in the browser's address bar) and has limits on the amount of information to
send.
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent to the server could look
something like this:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET variable to collect form data (the names
of the form fields will automatically be the keys in the $_GET array):
Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
When to use method="get"?
When using method="get" in HTML forms, all variable names and values are displayed
in the URL.
Note: This method should not be used when sending passwords or other sensitive
information!
However, because the variables are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.
Note: The get method is not suitable for very large variable values. It should not be
used with values exceeding 2000 characters.
PHP $_POST Function
In PHP, the predefined $_POST variable is used to collect values in a form with
method="post".
The $_POST Variable
The predefined $_POST variable is used to collect values from a form sent with
method="post".
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be
changed by setting the post_max_size in the php.ini file).
Example
<form action="welcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL will look like this:
http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST variable to collect form data (the
names of the form fields will automatically be the keys in the $_POST array):
Welcome <?php echo $_POST["fname"]; ?>!<br />
You are <?php echo $_POST["age"]; ?> years old.
When to use method="post"?
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
However, because the variables are not displayed in the URL, it is not possible to
bookmark the page.
The PHP $_REQUEST Variable
The predefined $_REQUEST variable contains the contents of both $_GET, $_POST,
and $_COOKIE.
The $_REQUEST variable can be used to collect form data sent with both the GET and
POST methods.
Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br />
You are <?php echo $_REQUEST["age"]; ?> years old.
PHP Include Files
PHP include and require Statements
In PHP, you can insert the content of one PHP file into another PHP file before the
server executes it.
The include and require statements are used to insert useful codes written in other files,
in the flow of execution.
Syntax
include 'filename';
or
require 'filename';
PHP include and require Statement
Basic Example
Assume that you have a standard header file, called "header.php". To include the
header file in a page, use include/require:
<html>
<body>
<?php include 'header.php'; ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
</body>
</html>
Example 2
Assume we have a standard menu file that should be used on all pages.
"menu.php":
echo '<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>';
All pages in the Web site should include this menu file. Here is how it can be done:
<html>
<body>
<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>
Example 3
Assume we have an include file with some variables defined ("vars.php"):
<?php
$color='red';
$car='BMW';
?>
Then the variables can be used in the calling file:
<html>
<body>
<h1>Welcome to my home page.</h1>
<?php include 'vars.php';
echo "I have a $color $car"; // I have a red BMW
?>
</body>
</html>
Lab#3: DBMS, MS Access and Oracle 10g
Introduction to DBMS:
A Database Management System (DBMS) is a set of computer programs that controls
the creation, maintenance, and the use of the database of an organization and its end
users. It allows organizations to place control of organization-wide database
development in the hands of database administrators (DBAs) and other specialists
Introduction to Oracle. Oracle Database is the official name of the flagship relational
database management
system (RDBMS) software product released by Oracle Corporation. The product has
been renamed several times, and is also referred to as Oracle RDBMS or simply Oracle
Lawrence J. Ellison (Larry Ellison) has served as Oracle's CEO throughout the
company's history. Ellison served as the Chairman of the Board until his replacement by
Jeffrey O. Version numbering. Oracle products have historically followed their own
release-numbering and naming conventions. With the Oracle RDBMS 10g release,
Oracle Corporation started standardizing all current versions of its major products using
the "10g" label, although some sources continued to refer to Oracle Applications
Release 11i as Oracle 11i. Major database-related products and some of their versions
include:
• Oracle Application Server 10g (also known as "Oracle AS 10g"): a middleware
product;
• Oracle Applications Release 11i (aka Oracle e-Business Suite, Oracle Financials
or Oracle 11i): a suite of business applications;
• Oracle Developer Suite 10g (9.0.4);
• Oracle JDeveloper 10g: a Java integrated development environment;
Since version 7, Oracle's RDBMS release numbering has used the following codes:
• Oracle7: 7.0.16 — 7.3.4
• Oracle8 Database: 8.0.3 — 8.0.6
• Oracle8i Database Release 1: 8.1.5.0 — 8.1.5.1
• Oracle8i Database Release 2: 8.1.6.0 — 8.1.6.3
• Oracle8i Database Release 3: 8.1.7.0 — 8.1.7.4
• Oracle9i Database Release 1: 9.0.1.0 — 9.0.1.5 (patchset as of December 2003)
• Oracle9i Database Release 2: 9.2.0.1 — 9.2.0.8 (patchset as of April 2007)
• Oracle Database 10g Release 1: 10.1.0.2 — 10.1.0.5 (patchset as of February
2006)
• Oracle Database 10g Release 2: 10.2.0.1 — 10.2.0.4 (patchset as of April 2008)
• Oracle Database 11g Release 1: 11.1.0.6 — 11.1.0.7 (patchset as of September
2008)
• Oracle Database 11g Release 2: 11.2.0.1 (released 2009-09-01)
Schemas
Oracle database conventions refer to defined groups of ownership (generally associated
with a "username") as schemas. Most Oracle database (Oracle 8i, 9i) installations
traditionally come with a default schema called SCOTT. After the installation process
has set up the sample tables, the user can log into the database with the username
scott and the password tiger. (The name of the SCOTT schema originated with Bruce
Scott, one of the first employees at Oracle (then Software Development Laboratories),
who had a cat named Tiger.) Oracle 10g also have the default schema called system
and HR.
Oracle 10g Logging in as the Database Administrator
The first thing you need to do is to log in as the Oracle Database XE Administrator.
Follow these steps:
Open the Database Home Page login window:
On Windows, from the Start menu, select Programs (or All Programs), then Oracle
Database 10g Express Edition, and then Go To Database Home Page
At the Database Home Page login window, enter the following information:
Username: Enter system for the user name.
Password: Enter the password that was specified when Oracle Database XE was
installed.
Click Login.
The Oracle Database XE home page appears.
Unlocking the Sample User Account:
To create your application, you need to log in as a database user. Oracle Database XE
comes with a sample database user called HR. This user owns a number of database
tables in a sample schema that can be used to create applications for a fictional Human
Resources department. However, for security reasons, this user's account is locked.
You need to unlock this account before you can build a sample application.
To unlock the sample user account:
Make sure you are still logged on as the database administrator, as described in the
previous section.
Click the Administration icon, and then click Database Users.
Click the HR schema icon to display the user information for HR.
f
Under Manage Database User, enter the following settings:
Password and Confirm Password: Enter hr for the password.
Account Status: Select Unlocked.
Roles: Ensure that both CONNECT and RESOURCE are enabled.
Click Alter User.
Logging in as the Sample User Account
To log in as the sample user account:
Log out from the database administrator account by clicking Logout in the upper right
corner of the Database Home Page.
In the window, click Login.
In the Login window, enter hr for both the user name and password.
Click Login.
Now click on object browser (arrow pin) then click on Browse.
When you click on Tables the following screen will appear. Which shows the tables
include in HR Schema.
Oracle 10g tables
PRACTICE ON THE ABOVE TABLES
Oracle 8i uses the following tables
EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
DEPT (DEPTNO, DNAME, LOC)
SALGRADE (GRADE, LOSAL, HISAL)
Lab#4: Introduction to Structure Query Language
SQL stands for Structure Query Language, SQL statements are not case sensitive
SQL statements can be on one or more lines. Keywords cannot be abbreviated or split
across lines Clauses are usually placed on separate lines, Tabs and indents are used to
enhance readability
Executing SQL Statements
Place a semicolon (;) at the end of the last clause
Place a slash on the last line in the buffer
Place a slash at the SQL prompt
SQL select statement
Selecting all Columns
You can display all columns of data in a table by following the SELECT keyword
with an asterisk (*).
e.g
SELECT * from employees;
Selecting specific Columns
You can use the SELECT statement to display specific columns of the table by
specifying the column names, separated by commas
e.g
SELECT department_id, department_name from deptartments;
Arithmetic expressions
• You may need to modify the way in which data is displayed, perform
calculation, or look at what-if scenarios. This is possible using arithmetic
expressions. An arithmetic expression may contain column names,
constant numeric values, and the arithmetic operators.
• List of arithmetic operators available in SQL are + Add, - Subtract, *
Multiply, / Divide
• You can use arithmetic operators in any clause of a SQL statement except
the FROM clause.
• If an arithmetic expression contains more than one operator then
multiplication and division are evaluated first.
• If operators within an expression are of same priority, then evaluation is
done from left to right.
• You can use parentheses to force the expression within parentheses to be
evaluated first.
e.g
SELECT first_name, last_name salary, 12*salary+100 from employees;
will give different result from
e.g
SELECT first_name, last_name salary, 12*(salary+100) from employees;
Null value
If a row lacks the data value for a particular column, that value is said to be null,
or to contain null. A null value is a value that is unavailable, unassigned,
unknown, or inapplicable. A null value is not the same as zero or a space. Zero is
a number and space is a character.
If any column value in an arithmetic expression is null, the result is null. For e.g,
if you attempt to perform division with zero, you get an error. However if you
divide a number by null, the result is a null or unknown.
Defining a column alias
Specify the alias after the column in the SELECT list using space as a separator.
By default alias heading appear in uppercase. If the alias contains spaces, special
character (such as # or $), or is case sensitive, enclose the alias in double
quotation marks (― ―).
e.g
SELECT first_name AS name, salary AS Monthly-Salary from employees;
SELECT first_name “Name”, salary*12 “Annual Salary” from employees;
Eliminating duplicate rows
To eliminate duplicate rows in the result, include the DISTINCT keyword in the
SELECT clause immediately after the SELECT keyword.
e.g
SELECT DISTINCT department_id from employees;
Limiting rows selected
You can restrict the rows returned from the query by using the WHERE clause. A
WHERE clause contains a condition that must be met and it directly follows the
FORM clause.
The WHERE clause can compare values in columns, literal values, arithmetic
expressions or functions. The WHERE clause consists of three elements:
Column name, Comparison operator, Column name, constant or list of values
e.g.
SELECT first_name, last_name, job_id, department_id from employees where
department_id=30;
Character strings and dates in the WHERE clause must be enclosed in single
quotation marks (‗ ‗) Number constants however should not. All character
searches are case sensitive.
The default date display is DD-MON-YY.
Comparison operators
Comparison operators are used in conditions that compare one expression to
another.
The operators are
• = Equal to
• > Greater than
• >= Greater than or equal to
• < Less than
• <= Less than or equal to
• <> Not equal to
They are used in the WHERE clause in following format
Syntax
WHERE expr operator value
e.g
SELECT first_name, last_name, salary from employees where salary<=4000.;
Other comparison operators
• BETWEEN …AND…. Between two values (inclusive)
• IN (list) Match any of a list of values
• LIKE Match a character pattern
• IS NULL Is a null value
You can display rows based on a range of values using the BETWEEN operator.
The range that you specify contains a lower range and an upper range
e.g
SELECT first_name, last_name, salary from employees where salary between
1500 and 3000;
To test for values in a specified list use the IN operator
e.g
SELECT department_id, first_name, salary, manager_id from employees where
manager_id in (101, 105, 122, 124, 854,276);
You can select rows that match a character pattern by using the LIKE operator.
The character pattern-matching operation is referred to as wild card search.
Two symbols can be used to construct the search string.
• % Represents any sequence of zero or more character
• _ Represents any single character
e.g
SELECT first_name, last_name from employees where first_name like „S%‟;
SELECT first_name, last_name from emp where first_name like „_A%‟;
Null operator
The IS NULL operator tests for values that are null. A null value means the value
is unavailable, unassigned, unknown or inapplicable. Therefore you cannot test
with (=) because a null value cannot be equal or unequal to any value.
e.g
SELECT first_name, manager_id from employees where manager_id is null;
Logical operators
A logical operator combines the result of two component conditions to produce a
single result based on them or to invert the result of a single condition. Three
logical operators are available in SQL.
• AND Returns TRUE if both component conditions are TRUE
• OR Returns TRUE if either component condition is TRUE
• NOT Returns TRUE if the following condition is FALSE
You can use several conditions in one WHERE clause using the AND and OR
operators.
e.g
SELECT empno,ename,job,sal from emp where sal>=1100 and job=‟CLERK‟;
SELECT empno,ename,job,sal from emp where sal>=1100 or job=‟CLERK‟;
SELECT ename,job from emp where job not in („CLERK‟, „MANAGER‟,
„ANALYST‟);
Rules of Precedence
Order Evaluated Operator
1 All comparison operators
2 NOT
3 AND
4 OR
Override rules of precedence by using parentheses
SELECT first_name,job_id,salarat from employees where job_id=‟ST_CLERK‟ or
Job_ID=‟ST_MAN‟ and sal>5000;
SELECT first_name, job_id, salary from employees where (job_id=‟ST_CLERK‟ or
job_id=‟ ST_MAN‟) and salary>8000;
Order by clause
The order by clause can be used to sort the rows. If it is used then it must be
placed in last. The default sort order is ascending. To reverse the order you
specify the keyword DESC after column name in ORDE BY clause.
e.g
SELECT first_name, last_name, department_id, job_id from employees ordere by
last_name;
SELECT first_name, last_name, department_id, job_id from employees ordere by
last_name desc;
You can use a column alias in the order by clause.
e.g
SELECT employee_id, first_name, salary*12 annsal from employee order by
annsal;
Sorting by multiple columns
You can sort query results by more than one column. The sort limit is the number
of columns in the given table.
e.g
SELECT first_name, department_id, salary from employees order by
department_id, salaray desc;
Displaying table structure
In SQL* Plus you can display the structure of a table using the DESCRIBE
command.
e.g
DESCRIBE employees;
OR
DESC employees;
Note: for Exercises See attached page or will be provided by the Lab Instructor.
Lab#5: SQL Functions
Functions are a very powerful feature of SQL and can be used to do the following:
Perform calculation on data, Modify individual data items, Manipulate output for groups
of rows, Format dates and numbers for display, Convert column data types
Character Manipulation Function
CONCAT, SUBSTR, LENGTH, INSTR, and LPAD are the five character
manipulation functions
• CONCAT: Joins values together
• SUBSTR: Extracts a string of determined length
• LENGTH: Shows the length of a string as a numeric value
• INSTR: Finds numeric position of a named character
• LPAD: Pads the character value right-justified
• RPAD: Pads the character value left-justified
E.g
To display employee first name and last name joined together, length of the
employee first name, and the numeric position of the letter A in the employee first
name, for all employees who are clerk.
SELECT first_name, CONCAT (first_name, last_name), LENGTH (first_name),
INSTR (first_name,‟A‟) FROM employees WHERE SUBSTR (job,3,7) = „CLERK‟;
Assignment
Display employee name and job joined together, length of the employee name, and the
numeric
position of the letter M in the employee name, for all employees who are manager.
Case Conversion Function
LOWER, UPPER and INITCAP are the three case conversion functions
• LOWER: Converts mixed case or uppercase character string to lowercase
• UPPER: Converts mixed case or lowercase character string to uppercase
• INITCAP: Converts first letter of each word to uppercase and remaining letter
to lowercase
E.g
Display the employee number, name, and department number for employee Neena.
SELECT employee_id, first_name, department_id FROM employees
WHERE LOWER (first_name)=‟neena‟;
Assignment
Display the names of employees in employees table such that in first column they are
displayed in uppercase, in second column they are displayed in lower case and in the
third column only the first letter is capital and all other letters in lower case.
Number Function
DUAL
The DUAL table is owned by the user SYS and can be accessed by all users. It
contains one column, DUMMY and one row with value X. The DUAL table is useful
when you want to return a value once only for instance the value of a constant,
pseudocolumn, or expression that is not derived from a table with user data.
E.g
SELECT ROUND (45.923,2), ROUND (45.923,0), ROUND (45.923,-1) from dual;
Calculate the remainder of the ratio of salary to commission for all employees
whose job_id is SA_MAN(sale manager).
SELECT first_name, salary, commission_pct, MOD (salaray, commission_pct)
FROM employees WHERE job_id=‟SA_MAN‟;
Assignment
Display the employee number, name, salary and salary increase by 15% expressed
as a whole number. Label the column New Salary.
SYSDATE
SYSDATE is a date function that returns the current date and time. You can use
sysdate just as you would use any other column name. For example you can display
the current date by selecting sysdate from a table. It is customary to select sysdate
from a dummy table called dual.
Oracle Date Format
Oracle stored dates in an internal numeric format, representing the century, year,
month, day, hours, minutes, and seconds.
Date Functions
Date functions operate on Oracle dates. All date functions returns a value of DATE
datatypes except MONTHS_BETWEEN, which return a numeric value.
Type Conversion Functions
In addition to Oracle datatypes, columns of tables in an Oracle database can be
defined using ANSI, DB2, and SQL/DS datatypes. However, the oracle Server internally
converts such datatypes to Oracle datatypes. In some cases, Oracle server allows data
of one datatypes where it expects data of a different datatype. This is allowed when
Oracle server can automatically convert the data to the expected datatypes. This
datatypes conversion can be done implicitly by Oracle server or explicitly by the user.
Explicit datatypes conversion are done by using the conversion functions. Conversion
functions convert a value from one datatype to another. Generally the form of the
function names follows the convention datatype TO datatyps. The first datatype is the
input datatype and the last datatype is the output.
Implicit Datatypes Conversion
Explicit Datatypes Conversion
SQL provides three functions to convert a value from one datatype to another.
The format model must be enclosed in single quotation marks and is case sensitive.
E.g
To display the name and hire dates as this format 17 November 1981 for all the
employees
SELECT first_name, TO_CHAR (sysdate,‟fmDD Month YYYY‟) hiredate FROM
employees;
The NVL Function
To convert a null value to an actual value we use the NVL function.
Syntax
NVL (Source_expr1, To_expr2)
Where:
Expr1 is the source value or expression that may contain null
Expr2 is the target value for converting
You can use the NVL function to convert any datatype but return value is always the
same as the datatype of expr1.
E.G
To calculate the annual compensation of all employees, you need to multiply the
monthly
salary by 12 and then add the commission to it. But here the salary will be calculated
only
for those employees who earn a commission. If any column value is an expression is
null,
the result is null.
So to calculate values for all employees, you must convert the null value to a number
before applying the arithmetic operator.
SELECT first_name, salary, commission_pct, (salary*12)+NVL(commission_pct,0)
FROM employees;
Assignment
Create a query that will display the employee name and commission amount. If the
employee does not earn commission put 99 label the column COMM.
Decode Function
The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE
logic used in various languages. The DECODE function decodes expression
after comparing it to each search value. If the expression is the same as search, result
is returned. If the default value is omitted a null value is returned where a search
value does not match any of the result values.
E.g
SELECT job,sal,
DECODE (job_id, 'IT_PROG', SAL*1.1, 'SA_CLERK', SAL*1.15, 'ST_MAN',
SAL*1.20, SAL) REVISED_SALARY FROM employees;
JOIN
When data from more than one table in the database is required, a join condition is
used. Rows in one table can be joined to rows in another table according to common
values existing in corresponding columns, that is, usually primary and foreign key
columns. For displaying data from two or more related tables. Write a simple join
condition in the WHERE clause.
Syntax:
SELECT table1.column, table2.column FROM table1, table2
WHERE table1.column1=table2.column2;
Cartesian Product
When a join condition is invalid or omitted completely, the result is a Cartesian
product in which all combinations of rows will be displayed. All rows in the first
table are joined to all rows in the second table.
A Cartesian product tends to generate a large number of rows, and its result is rarely
useful. You should always include a valid join condition in a WHERE clause, unless
you have a specific need to combine all rows from all tables.
E.g
To displays employee name and department name from EMPLOYEES and
DEPTARTMETNS table we will use cartesian product. Since no WHERE clause has
been specified so all rows from EMP table are joined with all rows in the DEPT table,
there by generating 2889 rows in the
output.
SELECT first_name, department_name FROM employees, deptartments;
Types of Joins
• Equijoin
• Non-equijoin
• Outer join
• Self join
What is Equijoin?
To determine the name of an employee‘s department, you compare the value in the
Department_id column in the EMPLOYEES table with the DEPARTMENT_ID values in
the DEPARTMENTS table. The relationship between the EMP and DEPT tables is an
equijoin that is, values in the DEPARTMENT_ID column on both tables must be equal.
Frequently this type of join involves primary and foreign key complements.
E.g
SELECT employees.employee_id, employees.first_name,
employees.department_id, departments.department_id, departments.location_id
FROM employees, departments
WHERE employee.department_id=departments.department_id;
The SELECT clause specifies the column names to retrieve employee name, employee
number, and department number, which are column in the EMP table department
number, department name, and location, which are column in the dept table
The FORM clause specifies the two tables that the database must access EMP table
and DEPT table
The WHERE clause specifies how the tables are to be joined
EMPLOYEES.DEPARTMENT_ID=DEPARTMENTS.DEPARTMENT_ID
Because the DEPARTMENT_ID column is common to both tables. In addition to the
join, you may have criteria for you WHERE clause.
Assignment
Create a unique listing of all employees (only name) that are in department 30. Include
the location of department 30 in the output.
Write a query to display the employee name, department name, and location of
all employees who earn a commission.
Non-Equijoins
The relationship between the EMPLOYEES table and the JOBS table is a non-equijoin
meaning that no column in the EMPLOYEES table corresponds directly to a column
in the JOBS table. The relationship between the two tables is that the SALARY Column
in the EMPLOYEES table is between the MIN_SALARY and MAX_SALARY column of
the JOBS table. The relationship is obtained using an operator other than equal (=).
E.g
SELECT employees.first_name, employees.salary, jobs.job_title
FROM employees, jobs WHERE employees.salary BETWEEN jobs.min_salary
AND jobs.max_salary;
Outer Joins
If a row does not satisfy a join condition the row will not appear in the query result.
For example in the equijoin condition of EMP and DEPT tables, department
OPERATIONS does not appear because no one works in that department.
The missing rows(s) can be returned if an outer join operator is used in the join
condition. The operator is a plus sign enclosed in parentheses (+), and it is placed on
the ―side‖ of the join that is deficient in information. This operator has the effect of
creating one or more null rows, to which one or more rows from the nondeficient
table can be joined.
Note:
The outer join operator can appear on only one side of the expression, the side that
has information missing. It returns those rows from one table that has no direct match
in the other table.
A condition involving an outer join cannot use the IN operator to be linked to another
condition by the OR operator.
E.g
In the equijoin condition of EMPLOYEES and DEPARTMENTS tables, department
OPERATIONS does not appear because no one works in that department. So we will
have to do outer join
SELECT employees.first_name, departments.department_id,
departments.department_name
FROM employees, department WHERE employees.department_id (+) =
departments.department_id;
Self Join
Sometimes you need to join a table to itself. To find the name of each employee's
manager, you need to join the EMPLOYEES table to itself, or perform a self join.
E.g
SELECT worker.first_name ||' works for '|| manager.first_name
FROM employees worker, employees manager WHERE worker.manager_id =
manager.employee_id;
The above example joins the EMP table to itself. To simulate two tables in the FROM
clause, there are two aliases, namely WORKER and MANAGER for the same table,
EMPLOYEES. Here the WHERE clause contains the join that means " where a worker'
manager
number matches the employee number for the manager".
Note: for Exercises See attached page or will be provided by the Lab Instructor.
Lab#6: Creating and Managing Tables:
Naming Rules
Name database tables and columns according to the standard rules for naming any
Oracle database object: Table names and column names must begin with a letter and
can be 1-30 character long. Names must contain only the characters A-Z, a-z, 0-9, _
(underscore), $ and # (legal characters, but their use is discouraged). Names must not
duplicate the name of another object owned by the same Oracle Server user. Names
must not be an Oracle Server reserved word. Naming Guidelines Use descriptive
names for tables and other database objects. Name the same entity consistently in
different tables. For example, the department number in column is called DEPTNO in
both the EMP table and the DEPT table. Note: Names are case insensitive. For
example, EMP is treated as the same name as eMP or eMp.
Data Definition Language:
The CREATE TABLE Statement , The ALTER TABLE Statement
The CREATE TABLE Statement
Create tables to store data by executing the SQL CREATE TABLE statement. This
statement is one of the data definition language (DDL) statements. DDL statements are
a subset of SQL statements used to create, modify, or remove Oracle database
structures.
These statements have an immediate effect on the database, and they also record
information in the data dictionary.
To create a table, a user must have the CREATE TABLE privilege and a storage area in
which to crate objects.
The ALTER TABLE Statement
After you create your tables, you may need to change the table structure because you
omitted a column or your column definition needs to be changed. You can do this by
using the ALTER TABLE statement.
You can add columns to a table by using the ALTER TABLE statement with the ADD
clause.
Adding a Column
Guidelines for adding a column
You can add or modify columns, but you cannot drop them from a table.
You cannot specify where the column is to appear. The new column becomes the last
column
The example above adds a column named job to the dept1 table. The JOB column
becomes the last column in the table.
Note: If a table already contains rows when a column is added, then the new column is
initially null for all the rows.
Modifying a Column
You can modify a column definition by using the ALTER TABLE statement with the
MODIFY clause. Column modification can include changes to a column‘s datatype, size,
and the default value
Guidelines
Increases the width or precision of a numeric column. Decreases the width of a column
if the columns only null values or if the table has no rows Change the datatype if the
column contains null values. Convert a CHAR column to the VARCHAR1 datatype or
convert a VARCHAR2 column to the CHAR datatypes if the column contains null values
or if you do not change the size. A change to the default value of a column affects only
subsequent insertions to the table. E.g
Renaming a Table
Assignments
3. Modify the EMPLOYEE table to allow for longer employee last names (50).
4. Rename the EMPLOYEE table to EMPLOYEE1
Data Manipulation Language (DML)
Data manipulation language is a core part of SQL. When you want to add, update, or
delete data in the database, you execute a DML statement. A collection of DML
statements that form a logical unit work is called a transaction.
Consider a banking database. When a bank customer transfers money from a saving
account to a checking account, the transaction might consists of three separate
operations: decrease savings account, increase the checking account, and record the
transaction in the transaction journal. The Oracle Server must guarantee that all three
SQL statements are performed to maintain the account in proper balance. When
something prevents one of the statements in the transaction from executing, the other
statements of the transaction must be done.
Adding a New Row to a Table
Because you can insert a new row that contains values for each column, the column list
is not required in the INSERT clause. However if you do not use the column list, the
values must be listed according to the default order of the columns in the table.
Methods for Inserting Null Values
Be sure that the targeted column allows null values by verifying Null? status from the
SQL DESCRIBE command.
Inserting Special Values
Check you table by using select command
The above example records the information for employee Green in the EMP table. It
supplies the current date and time in the HIREDATE column. It uses the SYSDATE
function for current date and time.
Inserting Specific Date Values
The format DD-MM-YY is usually used to insert a date value. With this format, recall
that the century defaults to the current century. Because the date also contains time
information, the default time is midnight (00:00:00).
If a date is required to be entered in a format other than the default (for example,
another century) and/or a specific time is required, use the TO_DATE function.
The Update Statement
The UPDATE statement is used to modify the data in a table.
Syntax
Update one Column in a Row
We want to add a first name to the person with a last name of "Rasmussen":
Update several Columns in a Row
We want to change the address and add the name of the city:
The DELETE Statement
The DELETE statement is used to delete rows in a table.
Syntax
Delete a Row
"Nina Rasmussen" is going to be deleted:
Delete All Rows
It is possible to delete all rows in a table without deleting the table. This means that
the table structure, attributes, and indexes will be intact:
Dropping a Table
The DROP TABLE statement removes the definition of an Oracle table. When you drop
a table, the database loses all the data in the table and all the indexes associated with
it.
Syntax:
Truncating a Table
It is used to remove all rows from a table and to release the storage space used by that
table.
Syntax:
SQL Constraints:
Note: for Exercises See attached page or will be provided by the Lab Instructor.
Lab#7: MYSQL
MySQL Introduction:
MySQL is a database server, MySQL is ideal for both small and large applications
MySQL supports standard SQL, MySQL compiles on a number of platforms, MySQL is
free to download and use.
Starting MySQL Command-Line Interface
MySQL is preinstalled on our virtual machine and automatically starts when you boot
the VM. Once you log in to the VM, you can start the MySQL command-line interface by
typing mysql:
cs144@cs144:~$ mysql
Then you should receive the following prompt
mysql>
and be inside the MySQL command-line interface. All commands in this tutorial should
be issued inside the MySQL command-line unless noted otherwise.
Choosing a Databases in MySQL
MySQL allows users to create multiple databases, so that a single MySQL server can
host databases for many independent applications. Before you start issuing SQL
commands to mysql, you first have to select the database that you will be using. In
order to see what databases currently exist, run
SHOW DATABASES;
You will see an output like
+--------------------+
| Database |
+--------------------+
| information_schema |
| CS144 |
| TEST |
+--------------------+
information_schema is a database that MySQL creates automatically and uses to
maintain some internal statistics on datbases and tables. The other two databases,
CS144 and TEST, are what we created for the project (note database names are case-
sensitive in MySQL). This two database setup mimics common development
environments in the real world. The CS144 database is your "production" database,
meant for use in the final versions of your code. The TEST database is for any
experimentation and for use during development and debugging. Select the TEST
database for the rest of this tutorial by issuing the command
USE TEST;
It is also possible to specify a database as a command line parameter to the mysql
command:
cs144@cs144:~$ mysql TEST
Creating a Table
Once you select a database, you can execute any SQL command. For example, you
can create a table using the CREATE TABLE command:
CREATE TABLE <tableName> (
<list of attributes and their types> );
Note that all reserved keywords (like CREATE and TABLE) are case-insensitive and
identifiers (like table names and attribute names) are case-sensitive in MySQL by
default. That is, a table named STUDENT is different from the student table.
You may enter a command on one line or on several lines. If your command runs over
several lines, you will be prompted with " -> " until you type the semicolon that ends any
command. An example table-creation command is:
CREATE TABLE tbl(a int, b char(20));
This command creates a table named tbl with two attributes. The first, named a, is an
integer, and the second, named b, is a character string of length (up to) 20.
When you create a table, you can declare a (set of) attribute(s) to be the primary key
like:
CREATE TABLE <tableName> (..., a <type> PRIMARY KEY, b, ...);
or
CREATE TABLE <tableName> (<attrs and their types>, PRIMARY KEY(a,b,c));
Inserting and Retrieving Tuples
Having created a table, we can insert tuples into it. The simplest way to insert is with the
INSERT command:
INSERT INTO <tableName> VALUES( <list of values for attributes, in order> );
For instance, we can insert the tuple (10, 'foobar') into relation tbl by
INSERT INTO tbl VALUES(10, 'foobar');
Once tuples are inserted, we can see the tuples in a relation with the command:
SELECT * FROM <tableName>;
For instance, after the above create and insert statements, the command
SELECT * FROM tbl;
produces the result
+------+--------+
| a | b |
+------+--------+
| 10 | foobar |
+------+--------+
Bulk Loading Data
Instead of inserting tuples one at a time, it is possible to create a file that contains all
tuples that you want to load in batch. The command for bulking loading tuples from a file
is the following:
LOAD DATA LOCAL INFILE <dataFile> INTO TABLE <tableName>;
where <dataFile> is the name of the file that contains the tuples. Each line in the data
file corresponds to one tuple and columns are separated by a tab character (t). You can
specify a NULL value in the data file using N.
For example, the following data file
1 first
2 second
3 N
will insert three tuples, (1, 'first'), (2, 'second'), and (3, NULL) to a table. If you want to
use, say, commas to separate columns, not tabs, add FIELDS TERMINATED BY ',' to
the LOAD command as follows:
LOAD DATA LOCAL INFILE <dataFile> INTO TABLE <tableName>
FIELDS TERMINATED BY ',';
If some columns in the data file is enclosed with, say, double quotes, you need to add
OPTIONALLY ENCLOED BY '"' as well:
LOAD DATA LOCAL INFILE <dataFile> INTO TABLE <tableName>
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"';
Notes on CR/LF issue: If your host OS is Windows, you need to pay particular
attention to how each line of a text file ends. By convention, Windows uses a pair of CR
(carriage return) and LF (line feed) characters to terminate lines. On the other hand,
Unix (including Linux and Mac OS X) use only a LF character. Therefore, problems
arise when you are feeding a text file generated from a Windows program to a program
running in Unix (such as mysql in Ubuntu). Since the end of the line of the input file is
different from what the tools expect, you may encounter unexpected behavior from
these tools. If you encounter this problem, you may want to run dos2unix command
from Ubuntu on your Windows-generated text file. This command converts CR and LF
at the end of each line in the input file to just LF. Type dos2unix --help to learn how to
use this command.
Getting Rid of Your Tables
To remove a table from your database, execute
DROP TABLE <tableName>;
We suggest you execute
DROP TABLE tbl;
after trying out the sequence of commands in this tutorial to avoid leaving a lot of
garbage tables around.
Getting Information About Your TABLES
You can get the set of all tables within the current database by the following command:
SHOW TABLES;
Once you know the list of tables, it is also possible to learn more about the table by
issuing the command:
DESCRIBE <tableName>;
Executing SQL From a File
Instead of typing and running SQL commands at a terminal, it is often more convenient
to type the SQL command(s) into a file and cause the file to be executed.
To run the commands in foo.sql (in the current working directory), type:
SOURCE foo.sql;
in mysql. Files like foo.sql that have SQL commands to be executed are often referred
to as a (batch) script file. You can also execute the script file directly from the Unix shell
by redirecting the input to mysql like the following:
cs144@cs144:~$ mysql TEST < foo.sql
Again, pay attention to the CR/LF issue if your host OS is windows and if you create
your SQL batch script file from Windows. Run dos2unix on the file if necessary.
Recording Your MySQL Session In a File
mysql provides the command TEE to save the queries that you executed and their
results to a file. At the mysql> prompt, you say:
TEE foo.txt;
and a file called foo.txt will appear in your current directory and will record all user input
and system output, until you exit mysql or type:
NOTEE;
Note that if the file foo.txt existed previously, new output will be appended to the file.
Quitting mysql
To leave mysql, type
QUIT;
MySQL Users and Privileges
By default, when you run mysql, you connect to MySQL as a user with the same name
of your Unix account: cs144. It is also possible to connect to MySQL as a different user
by specifying the -u option:
cs144@cs144:~$ mysql <database> -u <username> -p
Here, <username> should be replaced with the username that you want to use, and the
option -p asks mysql to prompt for the password of the user. So far in this tutorial, we
haven't had to use the -p option because the default user cs144 has empty password.
In our VM, we created another user root with password password. For example, if you
run
cs144@cs144:~$ mysql TEST -u root -p
mysql will ask for a password, for which you have to type "password" (without quotes).
After successful login, you are now connected to the TEST database as the user root.
The user root is the "superuser" or the "database administrator" of our MySQL
installation and has full access to all databases and tables, including the ability to create
new users, change user privileges, and so on. Because the root user has unrestricted
access, for security purposes, it is best to connect to MySQL as root only when you
need to perform one of these administrative tasks. For your project work, the default
user account cs144 (no password) will be sufficeint, which has full access to the CS144
and TEST databases but nothing else.
If you are logged in to MySQL as the root user, you can create a new MySQL user with
the CREATE USER command:
CREATE USER <user> IDENTIFIED BY '<password>';
where <user> is the name of the new user and <password> is its password. To create a
user with an empty password, you can simply type CREATE USER <user>; skipping the
IDENTIFIED BY part. All user data is stored in the user table in the mysql database,
issuing the following query as root will give you the list of current users:
SELECT * FROM mysql.user;
Note that prefixing the table name user with the database name mysql with a dot allows
you to access a table in a database not in currently in use. (mysql is the database
where MySQL maintains administrative records.) Once a new user is created, you will
have to grant appropriate privileges to the user with the GRANT command. For
example, the command
GRANT ALL ON TEST.* to cs144@localhost;
will give all privileges for the TEST database to the user cs144 (on localhost). To see
the privileges that you have, run:
SHOW GRANTS;
which will produce an output like:
+----------------------------------------------------------+
| Grants for cs144@localhost |
+----------------------------------------------------------+
| GRANT USAGE ON *.* TO 'cs144'@'localhost' |
| GRANT ALL PRIVILEGES ON `CS144`.* TO 'cs144'@'localhost' |
| GRANT ALL PRIVILEGES ON `TEST`.* TO 'cs144'@'localhost' |
+----------------------------------------------------------+
As the root user, you can also create and drop databases using CREATE DATABASE
and DROP DATABASE command like the following:
CREATE DATABASE TESTDB;
DROP DATABASE TESTDB;
As a final note, keep in mind that MySQL maintains its own username and password
pairs independently of the underlying OS. Thus, it is possible to create a MySQL user
that does not exist in the underlying OS and vice versa. This means that your default
MySQL user cs144 is not related to your Ubuntu account cs144 except the shared
name. In fact, as you may have noticed, cs144 in MySQL has a different password
(empty) from cs144 of the Ubuntu account ("password").
Help Facilities
mysql provides internal help facilities for MySQL commands. To see a list of commands
for which help is available, type help or help contents in mysql. To look up help for a
particular topic (listed in the contents), type help followed by the topic.
Lab#8: Database connectivity with PHP
PHP Database ODBC
ODBC is an Application Programming Interface (API) that allows you to connect to a
data source (e.g. an MS Access database).
Create an ODBC Connection
With an ODBC connection, you can connect to any database, on any computer in your
network, as long as an ODBC connection is available.
Here is how to create an ODBC connection to a MS Access Database:
Open the Administrative Tools icon in your Control Panel.
Double-click on the Data Sources (ODBC) icon inside.
Choose the System DSN tab.
Click on Add in the System DSN tab.
Select the Microsoft Access Driver. Click Finish.
In the next screen, click Select to locate the database.
Give the database a Data Source Name (DSN).
Click OK.
Note that this configuration has to be done on the computer where your web site is
located. If you are running Internet Information Server (IIS) on your own computer, the
instructions above will work, but if your web site is located on a remote server, you have
to have physical access to that server, or ask your web host to to set up a DSN for you
to use.
Connecting to an ODBC
The odbc_connect() function is used to connect to an ODBC data source. The function
takes four parameters: the data source name, username, password, and an optional
cursor type.
The odbc_exec() function is used to execute an SQL statement.
Example
The following example creates a connection to a DSN called northwind, with no
username and no password. It then creates an SQL and executes it:
$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
Retrieving Records
The odbc_fetch_row() function is used to return records from the result-set. This
function returns true if it is able to return rows, otherwise false.
The function takes two parameters: the ODBC result identifier and an optional row
number:
odbc_fetch_row($rs)
Retrieving Fields from a Record
The odbc_result() function is used to read fields from a record. This function takes two
parameters: the ODBC result identifier and a field number or name.
The code line below returns the value of the first field from the record:
$compname=odbc_result($rs,1);
The code line below returns the value of a field called "CompanyName":
$compname=odbc_result($rs,"CompanyName");
Closing an ODBC Connection
The odbc_close() function is used to close an ODBC connection.
odbc_close($conn);
An ODBC Example
The following example shows how to first create a database connection, then a result-
set, and then display the data in an HTML table.
<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body>
</html>
PHP MySQL Introduction
MySQL is the most popular open-source database system.
What is MySQL?
MySQL is a database.
The data in MySQL is stored in database objects called tables.
A table is a collection of related data entries and it consists of columns and rows.
Databases are useful when storing information categorically. A company may have a
database with the following tables: "Employees", "Products", "Customers" and "Orders".
Database Tables
A database most often contains one or more tables. Each table is identified by a name
(e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
Below is an example of a table called "Persons":
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger
The table above contains three records (one for each person) and four columns
(LastName, FirstName, Address, and City).
Queries
A query is a question or a request.
With MySQL, we can query a database for specific information and have a recordset
returned.
Look at the following query:
SELECT LastName FROM Persons
The query above selects all the data in the "LastName" column from the "Persons"
table, and will return a recordset like this:
LastName
Hansen
Svendson
Pettersen
Facts About MySQL Database
One great thing about MySQL is that it can be scaled down to support embedded
database applications. Perhaps it is because of this reputation that many people believe
that MySQL can only handle small to medium-sized systems.
The truth is that MySQL is the de-facto standard database for web sites that support
huge volumes of both data and end users (like Friendster, Yahoo, Google).
Look at http://www.mysql.com/customers/ for an overview of companies using MySQL.
PHP MySQL Connect to a Database
Create a Connection to a MySQL Database. Before you can access data in a database,
you must create a connection to the database. In PHP, this is done with the
mysql_connect() function. Syntax
mysql_connect(servername,username,password);
Parameter Description
servername Optional. Specifies the server to connect to. Default value is
"localhost:3306"
username Optional. Specifies the username to log in with. Default value is the
name of the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
Example
In the following example we store the connection in a variable ($con) for later use in the
script. The "die" part will be executed if the connection fails:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
?>
Closing a Connection
The connection will be closed automatically when the script ends. To close the
connection before, use the mysql_close() function:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
PHP MySQL Create Database and Tables
A database holds one or multiple tables.
Create a Database
The CREATE DATABASE statement is used to create a database in MySQL.
Syntax
CREATE DATABASE database_name
To learn more about SQL, please visit our SQL tutorial.
To get PHP to execute the statement above we must use the mysql_query() function.
This function is used to send a query or command to a MySQL connection.
Example
The following example creates a database called "my_db":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
Syntax
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
To learn more about SQL, please visit our SQL tutorial.
We must add the CREATE TABLE statement to the mysql_query() function to execute
the command.
Example
The following example creates a table named "Persons", with three columns. The
column names will be "FirstName", "LastName" and "Age":
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("my_db", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Important: A database must be selected before a table can be created. The database
is selected with the mysql_select_db() function.
Note: When you create a database field of type varchar, you must specify the maximum
length of the field, e.g. varchar(15).
Primary Keys and Auto Increment Fields
Each table should have a primary key field. A primary key is used to uniquely identify
the rows in a table. Each primary key value must be unique within the table.
Furthermore, the primary key field cannot be null because the database engine requires
a value to locate the record. The following example sets the personID field as the
primary key field. The primary key field is often an ID number, and is often used with the
AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the value of
the field by 1 each time a new record is added. To ensure that the primary key field
cannot be null, we must add the NOT NULL setting to the field.
Example
$sql = "CREATE TABLE Persons
(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual
Database lab manual

More Related Content

What's hot

What's hot (20)

Python cgi programming
Python cgi programmingPython cgi programming
Python cgi programming
 
Church Turing Thesis
Church Turing ThesisChurch Turing Thesis
Church Turing Thesis
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
Relational algebra ppt
Relational algebra pptRelational algebra ppt
Relational algebra ppt
 
Concurrency control
Concurrency controlConcurrency control
Concurrency control
 
Concurrency Control Techniques
Concurrency Control TechniquesConcurrency Control Techniques
Concurrency Control Techniques
 
Extended relational algebra
Extended relational algebraExtended relational algebra
Extended relational algebra
 
Automata theory -RE to NFA-ε
Automata theory -RE to  NFA-εAutomata theory -RE to  NFA-ε
Automata theory -RE to NFA-ε
 
Prolog Programming Language
Prolog Programming  LanguageProlog Programming  Language
Prolog Programming Language
 
Parse Tree
Parse TreeParse Tree
Parse Tree
 
2 database system concepts and architecture
2 database system concepts and architecture2 database system concepts and architecture
2 database system concepts and architecture
 
CLR AND LALR PARSER
CLR AND LALR PARSERCLR AND LALR PARSER
CLR AND LALR PARSER
 
Functional dependency
Functional dependencyFunctional dependency
Functional dependency
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
 
Presentation on dbms(relational calculus)
Presentation on dbms(relational calculus)Presentation on dbms(relational calculus)
Presentation on dbms(relational calculus)
 
UNIT I LINEAR DATA STRUCTURES – LIST
UNIT I 	LINEAR DATA STRUCTURES – LIST 	UNIT I 	LINEAR DATA STRUCTURES – LIST
UNIT I LINEAR DATA STRUCTURES – LIST
 
Code optimization in compiler design
Code optimization in compiler designCode optimization in compiler design
Code optimization in compiler design
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Data base management systems ppt
Data base management systems pptData base management systems ppt
Data base management systems ppt
 

Viewers also liked

Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideSrinimf-Slides
 
Oracle Sql developer tutorial
Oracle Sql developer tutorialOracle Sql developer tutorial
Oracle Sql developer tutorialAsad Masood Qazi
 
Colorectal Cancer-A Rising Concern
Colorectal Cancer-A Rising ConcernColorectal Cancer-A Rising Concern
Colorectal Cancer-A Rising ConcernIsDocIn .
 
Oracle Baisc Tutorial
Oracle Baisc TutorialOracle Baisc Tutorial
Oracle Baisc Tutorialbunny0143
 
Joins in databases
Joins in databases Joins in databases
Joins in databases CourseHunt
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsAbdul Rahman Sherzad
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manualSANTOSH RATH
 
Object relational and extended relational databases
Object relational and extended relational databasesObject relational and extended relational databases
Object relational and extended relational databasesSuhad Jihad
 
Oracl DBA lab manual
Oracl DBA lab manualOracl DBA lab manual
Oracl DBA lab manualAbdulla Shaik
 
Lecture 14 requirements modeling - flow and behavior
Lecture 14   requirements modeling - flow and  behaviorLecture 14   requirements modeling - flow and  behavior
Lecture 14 requirements modeling - flow and behaviorIIUI
 

Viewers also liked (20)

Adbms lab manual
Adbms lab manualAdbms lab manual
Adbms lab manual
 
Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step Guide
 
Oracle Sql developer tutorial
Oracle Sql developer tutorialOracle Sql developer tutorial
Oracle Sql developer tutorial
 
Colorectal Cancer-A Rising Concern
Colorectal Cancer-A Rising ConcernColorectal Cancer-A Rising Concern
Colorectal Cancer-A Rising Concern
 
Payilagam oracle sql & plsql training syllabus
Payilagam oracle sql & plsql training syllabusPayilagam oracle sql & plsql training syllabus
Payilagam oracle sql & plsql training syllabus
 
Oracle Baisc Tutorial
Oracle Baisc TutorialOracle Baisc Tutorial
Oracle Baisc Tutorial
 
En ch23
En ch23En ch23
En ch23
 
4 bit counter
4 bit counter4 bit counter
4 bit counter
 
Eer case study
Eer case studyEer case study
Eer case study
 
Joins in databases
Joins in databases Joins in databases
Joins in databases
 
Adbms
AdbmsAdbms
Adbms
 
PLSQL Cursors
PLSQL CursorsPLSQL Cursors
PLSQL Cursors
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Chapter02
Chapter02Chapter02
Chapter02
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manual
 
Object relational and extended relational databases
Object relational and extended relational databasesObject relational and extended relational databases
Object relational and extended relational databases
 
Oracl DBA lab manual
Oracl DBA lab manualOracl DBA lab manual
Oracl DBA lab manual
 
Lecture 14 requirements modeling - flow and behavior
Lecture 14   requirements modeling - flow and  behaviorLecture 14   requirements modeling - flow and  behavior
Lecture 14 requirements modeling - flow and behavior
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 

Similar to Database lab manual

How to-write-injection-proof-plsql-1-129572
How to-write-injection-proof-plsql-1-129572How to-write-injection-proof-plsql-1-129572
How to-write-injection-proof-plsql-1-129572Dylan Chan
 
Ftth development manual part1 (1)
Ftth development manual part1 (1)Ftth development manual part1 (1)
Ftth development manual part1 (1)Igors Cardoso
 
2013HT12504-Dissertation Report
2013HT12504-Dissertation Report2013HT12504-Dissertation Report
2013HT12504-Dissertation ReportSri Kumaran
 
2014-07-30 defense in depth scap workbook
2014-07-30 defense in depth scap workbook2014-07-30 defense in depth scap workbook
2014-07-30 defense in depth scap workbookShawn Wells
 
Ceph Object Storage Reference Architecture Performance and Sizing Guide
Ceph Object Storage Reference Architecture Performance and Sizing GuideCeph Object Storage Reference Architecture Performance and Sizing Guide
Ceph Object Storage Reference Architecture Performance and Sizing GuideKaran Singh
 
Beginners_Guide_to_PLC_Programming_How_t.pdf
Beginners_Guide_to_PLC_Programming_How_t.pdfBeginners_Guide_to_PLC_Programming_How_t.pdf
Beginners_Guide_to_PLC_Programming_How_t.pdfMAamirAsghar
 
System design and 8051
System design and 8051System design and 8051
System design and 8051handson28
 
Tellurium reference Document 0.7.0
Tellurium reference Document 0.7.0Tellurium reference Document 0.7.0
Tellurium reference Document 0.7.0John.Jian.Fang
 
How To Create PowerShell Function
How To Create PowerShell FunctionHow To Create PowerShell Function
How To Create PowerShell FunctionVCP Muthukrishna
 
Sql account-user-manual
Sql account-user-manualSql account-user-manual
Sql account-user-manualgeniusppang
 
Dataguard11g rac-maa-1-134639
Dataguard11g rac-maa-1-134639Dataguard11g rac-maa-1-134639
Dataguard11g rac-maa-1-134639Mohammed Khan
 
Process documentation: SQL
Process documentation: SQLProcess documentation: SQL
Process documentation: SQLPeter Rovick
 
Using sql server in c sharp
Using sql server in c sharpUsing sql server in c sharp
Using sql server in c sharpFaruk Alkan
 

Similar to Database lab manual (20)

How to-write-injection-proof-plsql-1-129572
How to-write-injection-proof-plsql-1-129572How to-write-injection-proof-plsql-1-129572
How to-write-injection-proof-plsql-1-129572
 
Ftth development manual part1 (1)
Ftth development manual part1 (1)Ftth development manual part1 (1)
Ftth development manual part1 (1)
 
2013HT12504-Dissertation Report
2013HT12504-Dissertation Report2013HT12504-Dissertation Report
2013HT12504-Dissertation Report
 
2014-07-30 defense in depth scap workbook
2014-07-30 defense in depth scap workbook2014-07-30 defense in depth scap workbook
2014-07-30 defense in depth scap workbook
 
MSc dissertation np
MSc dissertation npMSc dissertation np
MSc dissertation np
 
PHP-Nuke-HOWTO
PHP-Nuke-HOWTOPHP-Nuke-HOWTO
PHP-Nuke-HOWTO
 
PHP-Nuke-HOWTO
PHP-Nuke-HOWTOPHP-Nuke-HOWTO
PHP-Nuke-HOWTO
 
Ceph Object Storage Reference Architecture Performance and Sizing Guide
Ceph Object Storage Reference Architecture Performance and Sizing GuideCeph Object Storage Reference Architecture Performance and Sizing Guide
Ceph Object Storage Reference Architecture Performance and Sizing Guide
 
Beginners_Guide_to_PLC_Programming_How_t.pdf
Beginners_Guide_to_PLC_Programming_How_t.pdfBeginners_Guide_to_PLC_Programming_How_t.pdf
Beginners_Guide_to_PLC_Programming_How_t.pdf
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
System design and 8051
System design and 8051System design and 8051
System design and 8051
 
Httpcore tutorial
Httpcore tutorialHttpcore tutorial
Httpcore tutorial
 
Tellurium reference Document 0.7.0
Tellurium reference Document 0.7.0Tellurium reference Document 0.7.0
Tellurium reference Document 0.7.0
 
How To Create PowerShell Function
How To Create PowerShell FunctionHow To Create PowerShell Function
How To Create PowerShell Function
 
Sql account-user-manual
Sql account-user-manualSql account-user-manual
Sql account-user-manual
 
Dataguard11g rac-maa-1-134639
Dataguard11g rac-maa-1-134639Dataguard11g rac-maa-1-134639
Dataguard11g rac-maa-1-134639
 
Install
InstallInstall
Install
 
Process documentation: SQL
Process documentation: SQLProcess documentation: SQL
Process documentation: SQL
 
Using sql server in c sharp
Using sql server in c sharpUsing sql server in c sharp
Using sql server in c sharp
 
PHP Essentials
PHP EssentialsPHP Essentials
PHP Essentials
 

Recently uploaded

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

Database lab manual

  • 1. FacultyFaculty of Computer Science and Engineering Introduction to Database Lab CS-232L Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Pakistan SQL/MYSQL
  • 2. Contents Lab#1 Introduction to HTML.....................................................................................................................5 HTML Basics:..........................................................................................................................................5 HTML Images .........................................................................................................................................9 HTML Tables...........................................................................................................................................9 HTML Layouts.......................................................................................................................................11 HTML Forms .........................................................................................................................................13 Lab#2: Introduction to PHP.....................................................................................................................16 PHP Introduction ..................................................................................................................................16 Conditional Statementsin PHP...........................................................................................................19 PHP Loops ............................................................................................................................................22 PHP Functions......................................................................................................................................26 PHP Forms and User Input.................................................................................................................28 Form Validation.....................................................................................................................................29 PHP Include Files.................................................................................................................................31 Lab#3: DBMS, MS Access and Oracle 10g.........................................................................................34 Introduction to DBMS: .........................................................................................................................34 Schemas................................................................................................................................................35 Oracle 10g Logging in as the Database Administrator...................................................................35 Unlocking the Sample User Account:................................................................................................35 Oracle 10g tables .................................................................................................................................38 Lab#4: Introduction to Structure Query Language..............................................................................39 Executing SQL Statements.................................................................................................................39 SQL select statement ..........................................................................................................................39 Displaying table structure....................................................................................................................43 Lab#5: SQL Functions.............................................................................................................................44 Character Manipulation Function.......................................................................................................44 Case Conversion Function .................................................................................................................44 DUAL......................................................................................................................................................45 SYSDATE..............................................................................................................................................46 Type Conversion Functions................................................................................................................47 The NVL Function ................................................................................................................................48
  • 3. Decode Function ..................................................................................................................................49 Lab#6: Creating and Managing Tables:................................................................................................52 Naming Rules .......................................................................................................................................52 Data Definition Language: ..................................................................................................................52 Data Manipulation Language (DML) .................................................................................................56 SQL Constraints:..................................................................................................................................60 Lab#7: MYSQL .........................................................................................................................................68 MySQL Introduction:............................................................................................................................68 Lab#8: Database connectivity with PHP...............................................................................................74 PHP Database ODBC .........................................................................................................................74 Connecting to an ODBC......................................................................................................................74 Retrieving Records...............................................................................................................................74 PHP MySQL Connect to a Database................................................................................................77 PHP MySQL Create Database and Tables......................................................................................78 PHP MySQL Insert Into.......................................................................................................................81 PHP MySQL Select..............................................................................................................................83 PHP MySQL The Where Clause .......................................................................................................85 PHP MySQL Order By Keyword ........................................................................................................86 PHP MySQL Update............................................................................................................................87 Lab#9: Group functions and sub queries..............................................................................................90 Group Functions...................................................................................................................................91 Group By Clause..................................................................................................................................94 Having clause .......................................................................................................................................96 Order of evaluation of the clauses:....................................................................................................98 SUBQUERIES ......................................................................................................................................98 Using group functions in a subquery...............................................................................................101 Lab#10: SQL Statements......................................................................................................................104 Database Transactions .....................................................................................................................104 Set Operators......................................................................................................................................107 SQL View.............................................................................................................................................111 Lab#11: Introduction to PL/SQL...........................................................................................................115 General syntax to create PL/SQL:...................................................................................................115
  • 4. Use of PL/SQL variables...................................................................................................................115 PL/SQL IF Statement.........................................................................................................................117 IF/THEN ELSE Statement ................................................................................................................117 Nested IF/THEN ELSE Statement...................................................................................................118 PL/SQL Loops.....................................................................................................................................119 Lab#12: More on PL/SQL .....................................................................................................................123 Cursors ................................................................................................................................................123 Stored Procedures .............................................................................................................................130 PL/SQL Functions..............................................................................................................................131 Trigger..................................................................................................................................................136
  • 5. Lab#1 Introduction to HTML HTML Basics: Writing HTML Using Notepad or TextEdit Save Your HTML. Run the HTML in Your Browser HTML headings are defined with the <h1> to <h6> tags. HTML paragraphs are defined with the <p> tag. HTML documents are defined by HTML elements. An HTML element is everything from the start tag to the end tag: The start tag is often called the opening tag. The end tag is often called the closing tag. Some HTML elements have empty content. Empty elements are closed in the start tag Most HTML elements can have attributes HTML Document Example <!DOCTYPE html> <html> <body> <p>This is my first paragraph.</p> </body> </html> This example contains 3 HTML elements. Above Example Explanation The <p> element: <p>This is my first paragraph.</p>. The <p> element defines a paragraph in the HTML document. The element has a start tag <p> and an end tag </p>. The element content is: This is my first paragraph. The <body> element:
  • 6. <body> <p>This is my first paragraph.</p> </body> The <body> element defines the body of the HTML document. The element has a start tag <body> and an end tag </body>. The element content is another HTML element (a p element). The <html> element: <html> <body> <p>This is my first paragraph.</p> </body> </html> The <html> element defines the whole HTML document. The element has a start tag <html> and an end tag </html>. The element content is another HTML element (the body element). HTML Attributes HTML elements can have attributes. Attributes provide additional information about an element. Attributes are always specified in the start tag. Attributes come in name/value pairs like: name="value" Attribute Example HTML links are defined with the <a> tag. The link address is specified in the href attribute: e.g. <a href="http://www.w3schools.com">This is a link</a> Always Quote Attribute Values Attribute values should always be enclosed in quotes. Double style quotes are the most common, but single style quotes are also allowed. In some rare situations, when the attribute value itself contains quotes, it is necessary to use single quotes: name='John "ShotGun" Nelson' HTML Headings Headings are defined with the <h1> to <h6> tags. <h1> defines the most important heading. <h6> defines the least important heading. Example <h1>This is a heading</h1> <h2>This is a heading</h2> <h3>This is a heading</h3> HTML Lines The <hr>tag creates a horizontal line in an HTML page. The hr element can be used to separate content: Example
  • 7. <p>This is a paragraph</p> <hr><p>This is a paragraph</p> <hr><p>This is a paragraph</p> HTML Comments Comments can be inserted into the HTML code to make it more readable and understandable. Comments are ignored by the browser and are not displayed. Comments are written like this: Example <!-- This is a comment --> Note: There is an exclamation point after the opening bracket, but not before the closing bracket. <html> defines an HTML document <body> defines the documents body <h1> to <h6> defines HTML headings <hr> define a horizontal line <!--> defines a comment <p> defines a paragraph <br> inserts a single line break HTML Text Formatting Tags Tag Description <b> Defines bold text <big> Defines big text <em> Defines emphasized text <i> Defines a part of text in an alternate voice or mood <small> Defines small text <strong> Defines strong text <sub> Defines subscripted text <sup> Defines superscripted text HTML Link Syntax The HTML code for a link is simple. It looks like this: <a href="url">Link text</a> The href attribute specifies the destination of a link. Example <a href="http://www.w3schools.com/">Visit W3Schools</a>
  • 8. HTML Links - The name Attribute The name attribute specifies the name of an anchor. The name attribute is used to create a bookmark inside an HTML document. Note: The upcoming HTML5 standard suggests using the id attribute instead of the name attribute for specifying the name of an anchor. Using the id attribute actually works also for HTML4 in all modern browsers. Bookmarks are not displayed in any special way. They are invisible to the reader. Example A named anchor inside an HTML document: <a name="tips">Useful Tips Section</a> Create a link to the "Useful Tips Section" inside the same document: <a href="#tips">Visit the Useful Tips Section</a> Or, create a link to the "Useful Tips Section" from another page: <a href="http://www.w3schools.com/html_links.htm#tips"> Visit the Useful Tips Section</a> The HTML <title> Element The <title> tag defines the title of the document. The title element is required in all HTML/XHTML documents. The title element: defines a title in the browser toolbar provides a title for the page when it is added to favorites displays a title for the page in search-engine results A simplified HTML document: <!DOCTYPE html> <html> <head> <title>Title of the document</title> </head> <body> The content of the document...... </body> </html> HTML head Elements Tag Description <head> Defines information about the document <title> Defines the title of a document <base> Defines a default address or a default target for all links on a page <link> Defines the relationship between a document and an external
  • 9. resource <meta> Defines metadata about an HTML document <script> Defines a client-side script <style> Defines style information for a document HTML Images HTML Images - The <img> Tag and the Src Attribute In HTML, images are defined with the <img> tag. The <img> tag is empty, which means that it contains attributes only, and has no closing tag. To display an image on a page, you need to use the src attribute. Src stands for "source". The value of the src attribute is the URL of the image you want to display. Syntax for defining an image: <img src="url" alt="some_text"> The URL points to the location where the image is stored. An image named "boat.gif", located in the "images" directory on "www.w3schools.com" has the URL: http://www.w3schools.com/images/boat.gif. The browser displays the image where the <img> tag occurs in the document. If you put an image tag between two paragraphs, the browser shows the first paragraph, then the image, and then the second paragraph. HTML Images - The Alt Attribute The required alt attribute specifies an alternate text for an image, if the image cannot be displayed. The value of the alt attribute is an author-defined text: <img src="boat.gif" alt="Big Boat"> The alt attribute provides alternative information for an image if a user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader). HTML Images - Set Height and Width of an Image The height and width attributes are used to specify the height and width of an image. The attribute values are specified in pixels by default: <img src="pulpit.jpg" alt="Pulpit rock" width="304" height="228"> HTML Tables Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td> tag). td stands for "table data," and holds the content of a data cell. A <td> tag can contain text, links, images, lists, forms, other tables, etc.
  • 10. Table Example <table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> How the HTML code above looks in a browser: row 1, cell 1 row 1, cell 2 row 2, cell 1 row 2, cell 2 HTML Tables and the Border Attribute If you do not specify a border attribute, the table will be displayed without borders. Sometimes this can be useful, but most of the time, we want the borders to show. To display a table with borders, specify the border attribute: HTML Table Headers Header information in a table are defined with the <th> tag. All major browsers display the text in the <th> element as bold and centered. <table border="1"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> How the HTML code above looks in your browser: Header 1 Header 2 row 1, cell 1 row 1, cell 2 row 2, cell 1 row 2, cell 2
  • 11. HTML Table Tags Tag Description <table> Defines a table <th> Defines a table header <tr> Defines a table row <td> Defines a table cell <caption> Defines a table caption <colgroup> Defines a group of columns in a table, for formatting <col> Defines attribute values for one or more columns in a table <thead> Groups the header content in a table <tbody> Groups the body content in a table <tfoot> Groups the footer content in a table HTML Layouts Web page layout is very important to make your website look good. Design your webpage layout very carefully. Website Layouts Most websites have put their content in multiple columns (formatted like a magazine or newspaper). Multiple columns are created by using <div> or <table> elements. CSS are used to position elements, or to create backgrounds or colorful look for the pages. Even though it is possible to create nice layouts with HTML tables, tables were designed for presenting tabular data - NOT as a layout tool!. HTML Layouts - Using Tables A simple way of creating layouts is by using the HTML <table> tag. Multiple columns are created by using <div> or <table> elements. CSS are used to position elements, or to create backgrounds or colorful look for the pages. Using tables is not the correct use of the <table> element. The purpose of the <table> element is to display tabular data. The following example uses a table with 3 rows and 2 columns - the first and last row spans both columns using the colspan attribute: Example <!DOCTYPE html> <html> <body>
  • 12. <table width="500" border="0"> <tr> <td colspan="2" style="background-color:#FFA500;"> <h1>Main Title of Web Page</h1> </td> </tr> <tr> <td style="background-color:#FFD700;width:100px;text-align:top;"> <b>Menu</b><br> HTML<br> CSS<br> JavaScript </td> <td style="background-color:#EEEEEE;height:200px;width:400px;text-align:top;"> Content goes here</td> </tr> <tr> <td colspan="2" style="background-color:#FFA500;text-align:center;"> Copyright © W3Schools.com</td> </tr> </table> </body> </html> The HTML code above will produce the following result: Main Title of Web Page Menu HTML CSS JavaScript Content goes here Copyright © W3Schools.com
  • 13. HTML Forms HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements. The <form> tag is used to create an HTML form: <form> input elements </form> HTML Forms - The Input Element The most important form element is the input element. The input element is used to select user information. An input element can vary in many ways, depending on the type attribute. An input element can be of type text field, checkbox, password, radio button, submit button, and more. The most used input types are described below. Text Fields <input type="text">defines a one-line input field that a user can enter text into: <form> First name: <input type="text" name="firstname"><br> Last name: <input type="text" name="lastname"> </form> How the HTML code above looks in a browser: First name: Last name: Note: The form itself is not visible. Also note that the default width of a text field is 20 characters. Password Field <input type="password">defines a password field: <form> Password: <input type="password" name="pwd"></form> How the HTML code above looks in a browser: Password: Note: The characters in a password field are masked (shown as asterisks or circles).
  • 14. Radio Buttons <input type="radio">defines a radio button. Radio buttons let a user select ONLY ONE of a limited number of choices: <form> <input type="radio" name="sex" value="male">Male<br> <input type="radio" name="sex" value="female">Female </form> How the HTML code above looks in a browser: Male Female Checkboxes <input type="checkbox">defines a checkbox. Checkboxes let a user select ZERO or MORE options of a limited number of choices. <form> <input type="checkbox" name="vehicle" value="Bike">I have a bike<br> <input type="checkbox" name="vehicle" value="Car">I have a car </form> How the HTML code above looks in a browser: I have a bike I have a car Submit Button <input type="submit">defines a submit button. A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input: <form name="input" action="html_form_action.asp" method="get"> Username: <input type="text" name="user"><input type="submit" value="Submit"></form> How the HTML code above looks in a browser: Username: Submit If you type some characters in the text field above, and click the "Submit" button, the browser will send your input to a page called "html_form_action.asp". The page will show you the received input.
  • 15. HTML Form Tags Tag Description <form> Defines an HTML form for user input <input> Defines an input control <textarea> Defines a multi-line text input control <label> Defines a label for an input element <fieldset> Defines a border around elements in a form <legend> Defines a caption for a fieldset element <select> Defines a select list (drop-down list) <optgroup> Defines a group of related options in a select list <option> Defines an option in a select list <button> Defines a push button
  • 16. Lab#2: Introduction to PHP PHP Introduction PHP stands for PHP: Hypertext Preprocessor. It is a server-side scripting language, like ASP. PHP scripts are executed on the server. It supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.). It is an open source software. PHP is a powerful tool for making dynamic and interactive Web pages. It is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. In this section you will learn about PHP, and how to execute scripts on your server. PHP File PHP files can contain text, HTML tags and scripts, PHP files are returned to the browser as plain HTML, PHP files have a file extension of ".php", ".php3", or ".phtml" Basic PHP Syntax A PHP script always starts with <?php and ends with ?>. A PHP script can be placed anywhere in the document. On servers with shorthand-support, you can start a PHP script with <? and end with ?>. For maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form. <?php ?> A PHP file must have a .php extension. A PHP file normally contains HTML tags, and some PHP scripting code. Below, we have an example of a simple PHP script that sends the text "Hello World" back to the browser: <html> <body> <?php echo "Hello World"; ?> </body> </html> Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World". Comments in PHP In PHP, we use // to make a one-line comment or /* and */ to make a comment block: <html> <body>
  • 17. <?php //This is a comment /* This is a comment block */ ?> </body> </html> PHP Variables Variables are "containers" for storing information. PHP variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like carName. Rules for PHP variable names: Variables in PHP starts with a $ sign, followed by the name of the variable The variable name must begin with a letter or the underscore character A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) A variable name should not contain spaces Variable names are case sensitive (y and Y are two different variables) Creating (Declaring) PHP Variables PHP has no command for declaring a variable. A variable is created the moment you first assign a value to it: $myCar="Volvo"; After the execution of the statement above, the variable myCar will hold the value Volvo. Tip: If you want to create a variable without assigning it a value, then you assign it the value of null. Let's create a variable containing a string, and a variable containing a number: <?php $txt="Hello World!"; $x=16; ?> Note: When you assign a text value to a variable, put quotes around the value. PHP is a Loosely Typed Language In PHP, a variable does not need to be declared before adding a value to it. In the example above, notice that we did not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on its
  • 18. value. In a strongly typed programming language, you have to declare (define) the type and name of the variable before using it. Strings in PHP String variables are used for values that contain characters. In this chapter we are going to look at the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the text "Hello World" to a string variable called $txt: <?php $txt="Hello World"; echo $txt; ?> The output of the code above will be: Hello World Now, lets try to use some different functions and operators to manipulate the string. The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together.To concatenate two string variables together, use the concatenation operator: <?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?> The output of the code above will be: Hello World! What a nice day! If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string (a space character), to separate the two strings. The strlen() function The strlen() function is used to return the length of a string. Let's find the length of a string: <?php echo strlen("Hello world!"); ?> The output of the code above will be: 12
  • 19. The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string). The strpos() function The strpos() function is used to search for a character/text within a string. If a match is found, this function will return the character position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string: <?php echo strpos("Hello world!","world"); ?> The output of the code above will be: 6 The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that the first character position in the string is 0, and not 1. PHP Operators The assignment operator = is used to assign values to variables in PHP. The arithmetic operator + is used to add values together. Arithmetic Operators Comparison Operators Logical Operators Conditional Statementsin PHP Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements: if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false if...elseif....else statement - use this statement to select one of several blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed The if Statement Use the if statement to execute some code only if a specified condition is true.
  • 20. Syntax if (condition) code to be executed if condition is true; The following example will output "Have a nice weekend!" if the current day is Friday: <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html> Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition is true. The if...else Statement Use the if....else statement to execute some code if a condition is true and another code if a condition is false. Syntax if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } Example The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!"; }
  • 21. else { echo "Have a nice day!"; } ?> </body> </html> The if...elseif....else Statement Use the if....elseif...else statement to select one of several blocks of code to be executed. Syntax if (condition) { code to be executed if condition is true; } elseif (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; } Example The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Have a nice weekend!"; } elseif ($d=="Sun")
  • 22. { echo "Have a nice Sunday!"; } else { echo "Have a nice day!"; } ?> </body> </html> PHP Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In PHP, we have the following looping statements: while - loops through a block of code while a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array The while Loop The while loop executes a block of code while a condition is true. Syntax while (condition) { code to be executed; } Example The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php $i=1; while($i<=5) {
  • 23. echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> Output: The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The do...while Statement The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the condition is true. Syntax do { code to be executed; } while (condition); Example The example below defines a loop that starts with i=1. It will then increment i with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal to 5: <html> <body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?>
  • 24. </body> </html> Output: The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The for Loop The for loop is used when you know in advance how many times the script should run. Syntax for (init; condition; increment) { code to be executed; } Parameters: init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment: Mostly used to increment a counter (but can be any code to be executed at the end of the iteration) Note: The init and increment parameters above can be empty or have multiple expressions (separated by commas). Example The example below defines a loop that starts with i=1. The loop will continue to run as long as the variable i is less than, or equal to 5. The variable i will increase by 1 each time the loop runs: <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?>
  • 25. </body> </html> Output: The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The foreach Loop The foreach loop is used to loop through arrays. Syntax foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value. Example The following example demonstrates a loop that will print the values of the given array: <html> <body> <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br />"; } ?> </body> </html> Output: one two three
  • 26. PHP Functions The real power of PHP comes from its functions. In PHP, there are more than 700 built- in functions. In this section we will show you how to create your own functions. To keep the script from being executed when the page loads, you can put it into a function. A function will be executed by a call to the function. You may call a function from anywhere within a page. Create a PHP Function A function will be executed by a call to the function. Syntax function functionName() { code to be executed; } PHP function guidelines: Give the function a name that reflects what the function does The function name can start with a letter or underscore (not a number) Example A simple function that writes my name when it is called: <html> <body> <?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?> </body> </html> Output: My name is Kai Jim Refsnes PHP Functions - Adding parameters
  • 27. To add more functionality to a function, we can add parameters. A parameter is just like a variable. Parameters are specified after the function name, inside the parentheses. Example 1 The following example will write different first names, but equal last name: <html> <body> <?php function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?> </body> </html> Output: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes. My brother's name is Stale Refsnes. Example 2 The following function has two parameters: <html> <body> <?php function writeName($fname,$punctuation) { echo $fname . " Refsnes" . $punctuation . "<br />"; } echo "My name is ";
  • 28. writeName("Kai Jim","."); echo "My sister's name is "; writeName("Hege","!"); echo "My brother's name is "; writeName("Ståle","?"); ?> </body> </html> Output: My name is Kai Jim Refsnes. My sister's name is Hege Refsnes! My brother's name is Ståle Refsnes? PHP Functions - Return values To let a function return a value, use the return statement. Example <html> <body> <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html> Output: 1 + 16 = 17 PHP Forms and User Input The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. PHP Form Handling The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.
  • 29. Example The example below contains an HTML form with two input fields and a submit button: <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> When a user fills out the form above and clicks on the submit button, the form data is sent to a PHP file, called "welcome.php": "welcome.php" looks like this: <html> <body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> Output could be something like this: Welcome John! You are 28 years old. Form Validation User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load. You should consider server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error. PHP $_GET Variable In PHP, the predefined $_GET variable is used to collect values in a form with method="get".
  • 30. The $_GET Variable The predefined $_GET variable is used to collect values in a form with method="get" Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. Example <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL sent to the server could look something like this: http://www.w3schools.com/welcome.php?fname=Peter&age=37 The "welcome.php" file can now use the $_GET variable to collect form data (the names of the form fields will automatically be the keys in the $_GET array): Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! When to use method="get"? When using method="get" in HTML forms, all variable names and values are displayed in the URL. Note: This method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters. PHP $_POST Function In PHP, the predefined $_POST variable is used to collect values in a form with method="post". The $_POST Variable The predefined $_POST variable is used to collect values from a form sent with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
  • 31. Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file). Example <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When the user clicks the "Submit" button, the URL will look like this: http://www.w3schools.com/welcome.php The "welcome.php" file can now use the $_POST variable to collect form data (the names of the form fields will automatically be the keys in the $_POST array): Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. When to use method="post"? Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page. The PHP $_REQUEST Variable The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods. Example Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old. PHP Include Files PHP include and require Statements In PHP, you can insert the content of one PHP file into another PHP file before the server executes it. The include and require statements are used to insert useful codes written in other files, in the flow of execution. Syntax
  • 32. include 'filename'; or require 'filename'; PHP include and require Statement Basic Example Assume that you have a standard header file, called "header.php". To include the header file in a page, use include/require: <html> <body> <?php include 'header.php'; ?> <h1>Welcome to my home page!</h1> <p>Some text.</p> </body> </html> Example 2 Assume we have a standard menu file that should be used on all pages. "menu.php": echo '<a href="/default.php">Home</a> <a href="/tutorials.php">Tutorials</a> <a href="/references.php">References</a> <a href="/examples.php">Examples</a> <a href="/about.php">About Us</a> <a href="/contact.php">Contact Us</a>'; All pages in the Web site should include this menu file. Here is how it can be done: <html> <body> <div class="leftmenu"> <?php include 'menu.php'; ?> </div> <h1>Welcome to my home page.</h1> <p>Some text.</p> </body> </html> Example 3 Assume we have an include file with some variables defined ("vars.php"): <?php $color='red';
  • 33. $car='BMW'; ?> Then the variables can be used in the calling file: <html> <body> <h1>Welcome to my home page.</h1> <?php include 'vars.php'; echo "I have a $color $car"; // I have a red BMW ?> </body> </html>
  • 34. Lab#3: DBMS, MS Access and Oracle 10g Introduction to DBMS: A Database Management System (DBMS) is a set of computer programs that controls the creation, maintenance, and the use of the database of an organization and its end users. It allows organizations to place control of organization-wide database development in the hands of database administrators (DBAs) and other specialists Introduction to Oracle. Oracle Database is the official name of the flagship relational database management system (RDBMS) software product released by Oracle Corporation. The product has been renamed several times, and is also referred to as Oracle RDBMS or simply Oracle Lawrence J. Ellison (Larry Ellison) has served as Oracle's CEO throughout the company's history. Ellison served as the Chairman of the Board until his replacement by Jeffrey O. Version numbering. Oracle products have historically followed their own release-numbering and naming conventions. With the Oracle RDBMS 10g release, Oracle Corporation started standardizing all current versions of its major products using the "10g" label, although some sources continued to refer to Oracle Applications Release 11i as Oracle 11i. Major database-related products and some of their versions include: • Oracle Application Server 10g (also known as "Oracle AS 10g"): a middleware product; • Oracle Applications Release 11i (aka Oracle e-Business Suite, Oracle Financials or Oracle 11i): a suite of business applications; • Oracle Developer Suite 10g (9.0.4); • Oracle JDeveloper 10g: a Java integrated development environment; Since version 7, Oracle's RDBMS release numbering has used the following codes: • Oracle7: 7.0.16 — 7.3.4 • Oracle8 Database: 8.0.3 — 8.0.6 • Oracle8i Database Release 1: 8.1.5.0 — 8.1.5.1 • Oracle8i Database Release 2: 8.1.6.0 — 8.1.6.3 • Oracle8i Database Release 3: 8.1.7.0 — 8.1.7.4 • Oracle9i Database Release 1: 9.0.1.0 — 9.0.1.5 (patchset as of December 2003) • Oracle9i Database Release 2: 9.2.0.1 — 9.2.0.8 (patchset as of April 2007) • Oracle Database 10g Release 1: 10.1.0.2 — 10.1.0.5 (patchset as of February 2006) • Oracle Database 10g Release 2: 10.2.0.1 — 10.2.0.4 (patchset as of April 2008) • Oracle Database 11g Release 1: 11.1.0.6 — 11.1.0.7 (patchset as of September 2008) • Oracle Database 11g Release 2: 11.2.0.1 (released 2009-09-01)
  • 35. Schemas Oracle database conventions refer to defined groups of ownership (generally associated with a "username") as schemas. Most Oracle database (Oracle 8i, 9i) installations traditionally come with a default schema called SCOTT. After the installation process has set up the sample tables, the user can log into the database with the username scott and the password tiger. (The name of the SCOTT schema originated with Bruce Scott, one of the first employees at Oracle (then Software Development Laboratories), who had a cat named Tiger.) Oracle 10g also have the default schema called system and HR. Oracle 10g Logging in as the Database Administrator The first thing you need to do is to log in as the Oracle Database XE Administrator. Follow these steps: Open the Database Home Page login window: On Windows, from the Start menu, select Programs (or All Programs), then Oracle Database 10g Express Edition, and then Go To Database Home Page At the Database Home Page login window, enter the following information: Username: Enter system for the user name. Password: Enter the password that was specified when Oracle Database XE was installed. Click Login. The Oracle Database XE home page appears. Unlocking the Sample User Account: To create your application, you need to log in as a database user. Oracle Database XE comes with a sample database user called HR. This user owns a number of database
  • 36. tables in a sample schema that can be used to create applications for a fictional Human Resources department. However, for security reasons, this user's account is locked. You need to unlock this account before you can build a sample application. To unlock the sample user account: Make sure you are still logged on as the database administrator, as described in the previous section. Click the Administration icon, and then click Database Users. Click the HR schema icon to display the user information for HR. f Under Manage Database User, enter the following settings: Password and Confirm Password: Enter hr for the password. Account Status: Select Unlocked. Roles: Ensure that both CONNECT and RESOURCE are enabled. Click Alter User. Logging in as the Sample User Account To log in as the sample user account: Log out from the database administrator account by clicking Logout in the upper right corner of the Database Home Page. In the window, click Login. In the Login window, enter hr for both the user name and password. Click Login.
  • 37. Now click on object browser (arrow pin) then click on Browse. When you click on Tables the following screen will appear. Which shows the tables include in HR Schema.
  • 38. Oracle 10g tables PRACTICE ON THE ABOVE TABLES Oracle 8i uses the following tables EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO) DEPT (DEPTNO, DNAME, LOC) SALGRADE (GRADE, LOSAL, HISAL)
  • 39. Lab#4: Introduction to Structure Query Language SQL stands for Structure Query Language, SQL statements are not case sensitive SQL statements can be on one or more lines. Keywords cannot be abbreviated or split across lines Clauses are usually placed on separate lines, Tabs and indents are used to enhance readability Executing SQL Statements Place a semicolon (;) at the end of the last clause Place a slash on the last line in the buffer Place a slash at the SQL prompt SQL select statement Selecting all Columns You can display all columns of data in a table by following the SELECT keyword with an asterisk (*). e.g SELECT * from employees; Selecting specific Columns You can use the SELECT statement to display specific columns of the table by specifying the column names, separated by commas e.g SELECT department_id, department_name from deptartments; Arithmetic expressions • You may need to modify the way in which data is displayed, perform calculation, or look at what-if scenarios. This is possible using arithmetic expressions. An arithmetic expression may contain column names, constant numeric values, and the arithmetic operators. • List of arithmetic operators available in SQL are + Add, - Subtract, * Multiply, / Divide • You can use arithmetic operators in any clause of a SQL statement except the FROM clause. • If an arithmetic expression contains more than one operator then multiplication and division are evaluated first. • If operators within an expression are of same priority, then evaluation is done from left to right. • You can use parentheses to force the expression within parentheses to be evaluated first. e.g SELECT first_name, last_name salary, 12*salary+100 from employees;
  • 40. will give different result from e.g SELECT first_name, last_name salary, 12*(salary+100) from employees; Null value If a row lacks the data value for a particular column, that value is said to be null, or to contain null. A null value is a value that is unavailable, unassigned, unknown, or inapplicable. A null value is not the same as zero or a space. Zero is a number and space is a character. If any column value in an arithmetic expression is null, the result is null. For e.g, if you attempt to perform division with zero, you get an error. However if you divide a number by null, the result is a null or unknown. Defining a column alias Specify the alias after the column in the SELECT list using space as a separator. By default alias heading appear in uppercase. If the alias contains spaces, special character (such as # or $), or is case sensitive, enclose the alias in double quotation marks (― ―). e.g SELECT first_name AS name, salary AS Monthly-Salary from employees; SELECT first_name “Name”, salary*12 “Annual Salary” from employees; Eliminating duplicate rows To eliminate duplicate rows in the result, include the DISTINCT keyword in the SELECT clause immediately after the SELECT keyword. e.g SELECT DISTINCT department_id from employees; Limiting rows selected You can restrict the rows returned from the query by using the WHERE clause. A WHERE clause contains a condition that must be met and it directly follows the FORM clause. The WHERE clause can compare values in columns, literal values, arithmetic expressions or functions. The WHERE clause consists of three elements: Column name, Comparison operator, Column name, constant or list of values e.g. SELECT first_name, last_name, job_id, department_id from employees where department_id=30; Character strings and dates in the WHERE clause must be enclosed in single quotation marks (‗ ‗) Number constants however should not. All character searches are case sensitive. The default date display is DD-MON-YY.
  • 41. Comparison operators Comparison operators are used in conditions that compare one expression to another. The operators are • = Equal to • > Greater than • >= Greater than or equal to • < Less than • <= Less than or equal to • <> Not equal to They are used in the WHERE clause in following format Syntax WHERE expr operator value e.g SELECT first_name, last_name, salary from employees where salary<=4000.; Other comparison operators • BETWEEN …AND…. Between two values (inclusive) • IN (list) Match any of a list of values • LIKE Match a character pattern • IS NULL Is a null value You can display rows based on a range of values using the BETWEEN operator. The range that you specify contains a lower range and an upper range e.g SELECT first_name, last_name, salary from employees where salary between 1500 and 3000; To test for values in a specified list use the IN operator e.g SELECT department_id, first_name, salary, manager_id from employees where manager_id in (101, 105, 122, 124, 854,276); You can select rows that match a character pattern by using the LIKE operator. The character pattern-matching operation is referred to as wild card search. Two symbols can be used to construct the search string. • % Represents any sequence of zero or more character • _ Represents any single character e.g
  • 42. SELECT first_name, last_name from employees where first_name like „S%‟; SELECT first_name, last_name from emp where first_name like „_A%‟; Null operator The IS NULL operator tests for values that are null. A null value means the value is unavailable, unassigned, unknown or inapplicable. Therefore you cannot test with (=) because a null value cannot be equal or unequal to any value. e.g SELECT first_name, manager_id from employees where manager_id is null; Logical operators A logical operator combines the result of two component conditions to produce a single result based on them or to invert the result of a single condition. Three logical operators are available in SQL. • AND Returns TRUE if both component conditions are TRUE • OR Returns TRUE if either component condition is TRUE • NOT Returns TRUE if the following condition is FALSE You can use several conditions in one WHERE clause using the AND and OR operators. e.g SELECT empno,ename,job,sal from emp where sal>=1100 and job=‟CLERK‟; SELECT empno,ename,job,sal from emp where sal>=1100 or job=‟CLERK‟; SELECT ename,job from emp where job not in („CLERK‟, „MANAGER‟, „ANALYST‟); Rules of Precedence Order Evaluated Operator 1 All comparison operators 2 NOT 3 AND 4 OR Override rules of precedence by using parentheses SELECT first_name,job_id,salarat from employees where job_id=‟ST_CLERK‟ or Job_ID=‟ST_MAN‟ and sal>5000; SELECT first_name, job_id, salary from employees where (job_id=‟ST_CLERK‟ or job_id=‟ ST_MAN‟) and salary>8000; Order by clause The order by clause can be used to sort the rows. If it is used then it must be placed in last. The default sort order is ascending. To reverse the order you specify the keyword DESC after column name in ORDE BY clause. e.g
  • 43. SELECT first_name, last_name, department_id, job_id from employees ordere by last_name; SELECT first_name, last_name, department_id, job_id from employees ordere by last_name desc; You can use a column alias in the order by clause. e.g SELECT employee_id, first_name, salary*12 annsal from employee order by annsal; Sorting by multiple columns You can sort query results by more than one column. The sort limit is the number of columns in the given table. e.g SELECT first_name, department_id, salary from employees order by department_id, salaray desc; Displaying table structure In SQL* Plus you can display the structure of a table using the DESCRIBE command. e.g DESCRIBE employees; OR DESC employees; Note: for Exercises See attached page or will be provided by the Lab Instructor.
  • 44. Lab#5: SQL Functions Functions are a very powerful feature of SQL and can be used to do the following: Perform calculation on data, Modify individual data items, Manipulate output for groups of rows, Format dates and numbers for display, Convert column data types Character Manipulation Function CONCAT, SUBSTR, LENGTH, INSTR, and LPAD are the five character manipulation functions • CONCAT: Joins values together • SUBSTR: Extracts a string of determined length • LENGTH: Shows the length of a string as a numeric value • INSTR: Finds numeric position of a named character • LPAD: Pads the character value right-justified • RPAD: Pads the character value left-justified E.g To display employee first name and last name joined together, length of the employee first name, and the numeric position of the letter A in the employee first name, for all employees who are clerk. SELECT first_name, CONCAT (first_name, last_name), LENGTH (first_name), INSTR (first_name,‟A‟) FROM employees WHERE SUBSTR (job,3,7) = „CLERK‟; Assignment Display employee name and job joined together, length of the employee name, and the numeric position of the letter M in the employee name, for all employees who are manager. Case Conversion Function LOWER, UPPER and INITCAP are the three case conversion functions • LOWER: Converts mixed case or uppercase character string to lowercase • UPPER: Converts mixed case or lowercase character string to uppercase • INITCAP: Converts first letter of each word to uppercase and remaining letter
  • 45. to lowercase E.g Display the employee number, name, and department number for employee Neena. SELECT employee_id, first_name, department_id FROM employees WHERE LOWER (first_name)=‟neena‟; Assignment Display the names of employees in employees table such that in first column they are displayed in uppercase, in second column they are displayed in lower case and in the third column only the first letter is capital and all other letters in lower case. Number Function DUAL The DUAL table is owned by the user SYS and can be accessed by all users. It contains one column, DUMMY and one row with value X. The DUAL table is useful when you want to return a value once only for instance the value of a constant, pseudocolumn, or expression that is not derived from a table with user data. E.g SELECT ROUND (45.923,2), ROUND (45.923,0), ROUND (45.923,-1) from dual; Calculate the remainder of the ratio of salary to commission for all employees whose job_id is SA_MAN(sale manager).
  • 46. SELECT first_name, salary, commission_pct, MOD (salaray, commission_pct) FROM employees WHERE job_id=‟SA_MAN‟; Assignment Display the employee number, name, salary and salary increase by 15% expressed as a whole number. Label the column New Salary. SYSDATE SYSDATE is a date function that returns the current date and time. You can use sysdate just as you would use any other column name. For example you can display the current date by selecting sysdate from a table. It is customary to select sysdate from a dummy table called dual. Oracle Date Format Oracle stored dates in an internal numeric format, representing the century, year, month, day, hours, minutes, and seconds. Date Functions Date functions operate on Oracle dates. All date functions returns a value of DATE datatypes except MONTHS_BETWEEN, which return a numeric value.
  • 47. Type Conversion Functions In addition to Oracle datatypes, columns of tables in an Oracle database can be defined using ANSI, DB2, and SQL/DS datatypes. However, the oracle Server internally converts such datatypes to Oracle datatypes. In some cases, Oracle server allows data of one datatypes where it expects data of a different datatype. This is allowed when Oracle server can automatically convert the data to the expected datatypes. This datatypes conversion can be done implicitly by Oracle server or explicitly by the user. Explicit datatypes conversion are done by using the conversion functions. Conversion functions convert a value from one datatype to another. Generally the form of the function names follows the convention datatype TO datatyps. The first datatype is the input datatype and the last datatype is the output. Implicit Datatypes Conversion Explicit Datatypes Conversion SQL provides three functions to convert a value from one datatype to another. The format model must be enclosed in single quotation marks and is case sensitive.
  • 48. E.g To display the name and hire dates as this format 17 November 1981 for all the employees SELECT first_name, TO_CHAR (sysdate,‟fmDD Month YYYY‟) hiredate FROM employees; The NVL Function To convert a null value to an actual value we use the NVL function. Syntax NVL (Source_expr1, To_expr2) Where: Expr1 is the source value or expression that may contain null Expr2 is the target value for converting You can use the NVL function to convert any datatype but return value is always the same as the datatype of expr1. E.G To calculate the annual compensation of all employees, you need to multiply the monthly salary by 12 and then add the commission to it. But here the salary will be calculated only for those employees who earn a commission. If any column value is an expression is null, the result is null. So to calculate values for all employees, you must convert the null value to a number before applying the arithmetic operator. SELECT first_name, salary, commission_pct, (salary*12)+NVL(commission_pct,0) FROM employees; Assignment Create a query that will display the employee name and commission amount. If the employee does not earn commission put 99 label the column COMM.
  • 49. Decode Function The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned. If the default value is omitted a null value is returned where a search value does not match any of the result values. E.g SELECT job,sal, DECODE (job_id, 'IT_PROG', SAL*1.1, 'SA_CLERK', SAL*1.15, 'ST_MAN', SAL*1.20, SAL) REVISED_SALARY FROM employees; JOIN When data from more than one table in the database is required, a join condition is used. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns, that is, usually primary and foreign key columns. For displaying data from two or more related tables. Write a simple join condition in the WHERE clause. Syntax: SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1=table2.column2; Cartesian Product When a join condition is invalid or omitted completely, the result is a Cartesian product in which all combinations of rows will be displayed. All rows in the first table are joined to all rows in the second table. A Cartesian product tends to generate a large number of rows, and its result is rarely useful. You should always include a valid join condition in a WHERE clause, unless you have a specific need to combine all rows from all tables. E.g To displays employee name and department name from EMPLOYEES and DEPTARTMETNS table we will use cartesian product. Since no WHERE clause has been specified so all rows from EMP table are joined with all rows in the DEPT table, there by generating 2889 rows in the output. SELECT first_name, department_name FROM employees, deptartments; Types of Joins • Equijoin • Non-equijoin • Outer join
  • 50. • Self join What is Equijoin? To determine the name of an employee‘s department, you compare the value in the Department_id column in the EMPLOYEES table with the DEPARTMENT_ID values in the DEPARTMENTS table. The relationship between the EMP and DEPT tables is an equijoin that is, values in the DEPARTMENT_ID column on both tables must be equal. Frequently this type of join involves primary and foreign key complements. E.g SELECT employees.employee_id, employees.first_name, employees.department_id, departments.department_id, departments.location_id FROM employees, departments WHERE employee.department_id=departments.department_id; The SELECT clause specifies the column names to retrieve employee name, employee number, and department number, which are column in the EMP table department number, department name, and location, which are column in the dept table The FORM clause specifies the two tables that the database must access EMP table and DEPT table The WHERE clause specifies how the tables are to be joined EMPLOYEES.DEPARTMENT_ID=DEPARTMENTS.DEPARTMENT_ID Because the DEPARTMENT_ID column is common to both tables. In addition to the join, you may have criteria for you WHERE clause. Assignment Create a unique listing of all employees (only name) that are in department 30. Include the location of department 30 in the output. Write a query to display the employee name, department name, and location of all employees who earn a commission. Non-Equijoins The relationship between the EMPLOYEES table and the JOBS table is a non-equijoin meaning that no column in the EMPLOYEES table corresponds directly to a column in the JOBS table. The relationship between the two tables is that the SALARY Column in the EMPLOYEES table is between the MIN_SALARY and MAX_SALARY column of the JOBS table. The relationship is obtained using an operator other than equal (=). E.g SELECT employees.first_name, employees.salary, jobs.job_title FROM employees, jobs WHERE employees.salary BETWEEN jobs.min_salary AND jobs.max_salary;
  • 51. Outer Joins If a row does not satisfy a join condition the row will not appear in the query result. For example in the equijoin condition of EMP and DEPT tables, department OPERATIONS does not appear because no one works in that department. The missing rows(s) can be returned if an outer join operator is used in the join condition. The operator is a plus sign enclosed in parentheses (+), and it is placed on the ―side‖ of the join that is deficient in information. This operator has the effect of creating one or more null rows, to which one or more rows from the nondeficient table can be joined. Note: The outer join operator can appear on only one side of the expression, the side that has information missing. It returns those rows from one table that has no direct match in the other table. A condition involving an outer join cannot use the IN operator to be linked to another condition by the OR operator. E.g In the equijoin condition of EMPLOYEES and DEPARTMENTS tables, department OPERATIONS does not appear because no one works in that department. So we will have to do outer join SELECT employees.first_name, departments.department_id, departments.department_name FROM employees, department WHERE employees.department_id (+) = departments.department_id; Self Join Sometimes you need to join a table to itself. To find the name of each employee's manager, you need to join the EMPLOYEES table to itself, or perform a self join. E.g SELECT worker.first_name ||' works for '|| manager.first_name FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id; The above example joins the EMP table to itself. To simulate two tables in the FROM clause, there are two aliases, namely WORKER and MANAGER for the same table, EMPLOYEES. Here the WHERE clause contains the join that means " where a worker' manager number matches the employee number for the manager". Note: for Exercises See attached page or will be provided by the Lab Instructor.
  • 52. Lab#6: Creating and Managing Tables: Naming Rules Name database tables and columns according to the standard rules for naming any Oracle database object: Table names and column names must begin with a letter and can be 1-30 character long. Names must contain only the characters A-Z, a-z, 0-9, _ (underscore), $ and # (legal characters, but their use is discouraged). Names must not duplicate the name of another object owned by the same Oracle Server user. Names must not be an Oracle Server reserved word. Naming Guidelines Use descriptive names for tables and other database objects. Name the same entity consistently in different tables. For example, the department number in column is called DEPTNO in both the EMP table and the DEPT table. Note: Names are case insensitive. For example, EMP is treated as the same name as eMP or eMp. Data Definition Language: The CREATE TABLE Statement , The ALTER TABLE Statement The CREATE TABLE Statement Create tables to store data by executing the SQL CREATE TABLE statement. This statement is one of the data definition language (DDL) statements. DDL statements are a subset of SQL statements used to create, modify, or remove Oracle database structures. These statements have an immediate effect on the database, and they also record information in the data dictionary. To create a table, a user must have the CREATE TABLE privilege and a storage area in which to crate objects.
  • 53.
  • 54. The ALTER TABLE Statement After you create your tables, you may need to change the table structure because you omitted a column or your column definition needs to be changed. You can do this by using the ALTER TABLE statement. You can add columns to a table by using the ALTER TABLE statement with the ADD clause. Adding a Column Guidelines for adding a column You can add or modify columns, but you cannot drop them from a table. You cannot specify where the column is to appear. The new column becomes the last column The example above adds a column named job to the dept1 table. The JOB column becomes the last column in the table. Note: If a table already contains rows when a column is added, then the new column is initially null for all the rows.
  • 55. Modifying a Column You can modify a column definition by using the ALTER TABLE statement with the MODIFY clause. Column modification can include changes to a column‘s datatype, size, and the default value Guidelines Increases the width or precision of a numeric column. Decreases the width of a column if the columns only null values or if the table has no rows Change the datatype if the column contains null values. Convert a CHAR column to the VARCHAR1 datatype or convert a VARCHAR2 column to the CHAR datatypes if the column contains null values or if you do not change the size. A change to the default value of a column affects only subsequent insertions to the table. E.g Renaming a Table Assignments
  • 56. 3. Modify the EMPLOYEE table to allow for longer employee last names (50). 4. Rename the EMPLOYEE table to EMPLOYEE1 Data Manipulation Language (DML) Data manipulation language is a core part of SQL. When you want to add, update, or delete data in the database, you execute a DML statement. A collection of DML statements that form a logical unit work is called a transaction. Consider a banking database. When a bank customer transfers money from a saving account to a checking account, the transaction might consists of three separate operations: decrease savings account, increase the checking account, and record the transaction in the transaction journal. The Oracle Server must guarantee that all three SQL statements are performed to maintain the account in proper balance. When something prevents one of the statements in the transaction from executing, the other statements of the transaction must be done. Adding a New Row to a Table
  • 57. Because you can insert a new row that contains values for each column, the column list is not required in the INSERT clause. However if you do not use the column list, the values must be listed according to the default order of the columns in the table. Methods for Inserting Null Values Be sure that the targeted column allows null values by verifying Null? status from the SQL DESCRIBE command. Inserting Special Values Check you table by using select command The above example records the information for employee Green in the EMP table. It supplies the current date and time in the HIREDATE column. It uses the SYSDATE function for current date and time.
  • 58. Inserting Specific Date Values The format DD-MM-YY is usually used to insert a date value. With this format, recall that the century defaults to the current century. Because the date also contains time information, the default time is midnight (00:00:00). If a date is required to be entered in a format other than the default (for example, another century) and/or a specific time is required, use the TO_DATE function. The Update Statement The UPDATE statement is used to modify the data in a table. Syntax Update one Column in a Row We want to add a first name to the person with a last name of "Rasmussen": Update several Columns in a Row We want to change the address and add the name of the city: The DELETE Statement The DELETE statement is used to delete rows in a table.
  • 59. Syntax Delete a Row "Nina Rasmussen" is going to be deleted: Delete All Rows It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: Dropping a Table The DROP TABLE statement removes the definition of an Oracle table. When you drop a table, the database loses all the data in the table and all the indexes associated with it. Syntax: Truncating a Table It is used to remove all rows from a table and to release the storage space used by that table. Syntax:
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67. Note: for Exercises See attached page or will be provided by the Lab Instructor.
  • 68. Lab#7: MYSQL MySQL Introduction: MySQL is a database server, MySQL is ideal for both small and large applications MySQL supports standard SQL, MySQL compiles on a number of platforms, MySQL is free to download and use. Starting MySQL Command-Line Interface MySQL is preinstalled on our virtual machine and automatically starts when you boot the VM. Once you log in to the VM, you can start the MySQL command-line interface by typing mysql: cs144@cs144:~$ mysql Then you should receive the following prompt mysql> and be inside the MySQL command-line interface. All commands in this tutorial should be issued inside the MySQL command-line unless noted otherwise. Choosing a Databases in MySQL MySQL allows users to create multiple databases, so that a single MySQL server can host databases for many independent applications. Before you start issuing SQL commands to mysql, you first have to select the database that you will be using. In order to see what databases currently exist, run SHOW DATABASES; You will see an output like +--------------------+ | Database | +--------------------+ | information_schema | | CS144 | | TEST | +--------------------+ information_schema is a database that MySQL creates automatically and uses to maintain some internal statistics on datbases and tables. The other two databases, CS144 and TEST, are what we created for the project (note database names are case- sensitive in MySQL). This two database setup mimics common development environments in the real world. The CS144 database is your "production" database, meant for use in the final versions of your code. The TEST database is for any experimentation and for use during development and debugging. Select the TEST database for the rest of this tutorial by issuing the command USE TEST;
  • 69. It is also possible to specify a database as a command line parameter to the mysql command: cs144@cs144:~$ mysql TEST Creating a Table Once you select a database, you can execute any SQL command. For example, you can create a table using the CREATE TABLE command: CREATE TABLE <tableName> ( <list of attributes and their types> ); Note that all reserved keywords (like CREATE and TABLE) are case-insensitive and identifiers (like table names and attribute names) are case-sensitive in MySQL by default. That is, a table named STUDENT is different from the student table. You may enter a command on one line or on several lines. If your command runs over several lines, you will be prompted with " -> " until you type the semicolon that ends any command. An example table-creation command is: CREATE TABLE tbl(a int, b char(20)); This command creates a table named tbl with two attributes. The first, named a, is an integer, and the second, named b, is a character string of length (up to) 20. When you create a table, you can declare a (set of) attribute(s) to be the primary key like: CREATE TABLE <tableName> (..., a <type> PRIMARY KEY, b, ...); or CREATE TABLE <tableName> (<attrs and their types>, PRIMARY KEY(a,b,c)); Inserting and Retrieving Tuples Having created a table, we can insert tuples into it. The simplest way to insert is with the INSERT command: INSERT INTO <tableName> VALUES( <list of values for attributes, in order> ); For instance, we can insert the tuple (10, 'foobar') into relation tbl by INSERT INTO tbl VALUES(10, 'foobar'); Once tuples are inserted, we can see the tuples in a relation with the command: SELECT * FROM <tableName>; For instance, after the above create and insert statements, the command SELECT * FROM tbl; produces the result +------+--------+ | a | b | +------+--------+ | 10 | foobar | +------+--------+
  • 70. Bulk Loading Data Instead of inserting tuples one at a time, it is possible to create a file that contains all tuples that you want to load in batch. The command for bulking loading tuples from a file is the following: LOAD DATA LOCAL INFILE <dataFile> INTO TABLE <tableName>; where <dataFile> is the name of the file that contains the tuples. Each line in the data file corresponds to one tuple and columns are separated by a tab character (t). You can specify a NULL value in the data file using N. For example, the following data file 1 first 2 second 3 N will insert three tuples, (1, 'first'), (2, 'second'), and (3, NULL) to a table. If you want to use, say, commas to separate columns, not tabs, add FIELDS TERMINATED BY ',' to the LOAD command as follows: LOAD DATA LOCAL INFILE <dataFile> INTO TABLE <tableName> FIELDS TERMINATED BY ','; If some columns in the data file is enclosed with, say, double quotes, you need to add OPTIONALLY ENCLOED BY '"' as well: LOAD DATA LOCAL INFILE <dataFile> INTO TABLE <tableName> FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'; Notes on CR/LF issue: If your host OS is Windows, you need to pay particular attention to how each line of a text file ends. By convention, Windows uses a pair of CR (carriage return) and LF (line feed) characters to terminate lines. On the other hand, Unix (including Linux and Mac OS X) use only a LF character. Therefore, problems arise when you are feeding a text file generated from a Windows program to a program running in Unix (such as mysql in Ubuntu). Since the end of the line of the input file is different from what the tools expect, you may encounter unexpected behavior from these tools. If you encounter this problem, you may want to run dos2unix command from Ubuntu on your Windows-generated text file. This command converts CR and LF at the end of each line in the input file to just LF. Type dos2unix --help to learn how to use this command. Getting Rid of Your Tables To remove a table from your database, execute DROP TABLE <tableName>; We suggest you execute DROP TABLE tbl; after trying out the sequence of commands in this tutorial to avoid leaving a lot of garbage tables around.
  • 71. Getting Information About Your TABLES You can get the set of all tables within the current database by the following command: SHOW TABLES; Once you know the list of tables, it is also possible to learn more about the table by issuing the command: DESCRIBE <tableName>; Executing SQL From a File Instead of typing and running SQL commands at a terminal, it is often more convenient to type the SQL command(s) into a file and cause the file to be executed. To run the commands in foo.sql (in the current working directory), type: SOURCE foo.sql; in mysql. Files like foo.sql that have SQL commands to be executed are often referred to as a (batch) script file. You can also execute the script file directly from the Unix shell by redirecting the input to mysql like the following: cs144@cs144:~$ mysql TEST < foo.sql Again, pay attention to the CR/LF issue if your host OS is windows and if you create your SQL batch script file from Windows. Run dos2unix on the file if necessary. Recording Your MySQL Session In a File mysql provides the command TEE to save the queries that you executed and their results to a file. At the mysql> prompt, you say: TEE foo.txt; and a file called foo.txt will appear in your current directory and will record all user input and system output, until you exit mysql or type: NOTEE; Note that if the file foo.txt existed previously, new output will be appended to the file. Quitting mysql To leave mysql, type QUIT; MySQL Users and Privileges By default, when you run mysql, you connect to MySQL as a user with the same name of your Unix account: cs144. It is also possible to connect to MySQL as a different user by specifying the -u option: cs144@cs144:~$ mysql <database> -u <username> -p Here, <username> should be replaced with the username that you want to use, and the option -p asks mysql to prompt for the password of the user. So far in this tutorial, we haven't had to use the -p option because the default user cs144 has empty password.
  • 72. In our VM, we created another user root with password password. For example, if you run cs144@cs144:~$ mysql TEST -u root -p mysql will ask for a password, for which you have to type "password" (without quotes). After successful login, you are now connected to the TEST database as the user root. The user root is the "superuser" or the "database administrator" of our MySQL installation and has full access to all databases and tables, including the ability to create new users, change user privileges, and so on. Because the root user has unrestricted access, for security purposes, it is best to connect to MySQL as root only when you need to perform one of these administrative tasks. For your project work, the default user account cs144 (no password) will be sufficeint, which has full access to the CS144 and TEST databases but nothing else. If you are logged in to MySQL as the root user, you can create a new MySQL user with the CREATE USER command: CREATE USER <user> IDENTIFIED BY '<password>'; where <user> is the name of the new user and <password> is its password. To create a user with an empty password, you can simply type CREATE USER <user>; skipping the IDENTIFIED BY part. All user data is stored in the user table in the mysql database, issuing the following query as root will give you the list of current users: SELECT * FROM mysql.user; Note that prefixing the table name user with the database name mysql with a dot allows you to access a table in a database not in currently in use. (mysql is the database where MySQL maintains administrative records.) Once a new user is created, you will have to grant appropriate privileges to the user with the GRANT command. For example, the command GRANT ALL ON TEST.* to cs144@localhost; will give all privileges for the TEST database to the user cs144 (on localhost). To see the privileges that you have, run: SHOW GRANTS; which will produce an output like: +----------------------------------------------------------+ | Grants for cs144@localhost | +----------------------------------------------------------+ | GRANT USAGE ON *.* TO 'cs144'@'localhost' | | GRANT ALL PRIVILEGES ON `CS144`.* TO 'cs144'@'localhost' | | GRANT ALL PRIVILEGES ON `TEST`.* TO 'cs144'@'localhost' | +----------------------------------------------------------+ As the root user, you can also create and drop databases using CREATE DATABASE and DROP DATABASE command like the following: CREATE DATABASE TESTDB;
  • 73. DROP DATABASE TESTDB; As a final note, keep in mind that MySQL maintains its own username and password pairs independently of the underlying OS. Thus, it is possible to create a MySQL user that does not exist in the underlying OS and vice versa. This means that your default MySQL user cs144 is not related to your Ubuntu account cs144 except the shared name. In fact, as you may have noticed, cs144 in MySQL has a different password (empty) from cs144 of the Ubuntu account ("password"). Help Facilities mysql provides internal help facilities for MySQL commands. To see a list of commands for which help is available, type help or help contents in mysql. To look up help for a particular topic (listed in the contents), type help followed by the topic.
  • 74. Lab#8: Database connectivity with PHP PHP Database ODBC ODBC is an Application Programming Interface (API) that allows you to connect to a data source (e.g. an MS Access database). Create an ODBC Connection With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available. Here is how to create an ODBC connection to a MS Access Database: Open the Administrative Tools icon in your Control Panel. Double-click on the Data Sources (ODBC) icon inside. Choose the System DSN tab. Click on Add in the System DSN tab. Select the Microsoft Access Driver. Click Finish. In the next screen, click Select to locate the database. Give the database a Data Source Name (DSN). Click OK. Note that this configuration has to be done on the computer where your web site is located. If you are running Internet Information Server (IIS) on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to to set up a DSN for you to use. Connecting to an ODBC The odbc_connect() function is used to connect to an ODBC data source. The function takes four parameters: the data source name, username, password, and an optional cursor type. The odbc_exec() function is used to execute an SQL statement. Example The following example creates a connection to a DSN called northwind, with no username and no password. It then creates an SQL and executes it: $conn=odbc_connect('northwind','',''); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); Retrieving Records The odbc_fetch_row() function is used to return records from the result-set. This function returns true if it is able to return rows, otherwise false.
  • 75. The function takes two parameters: the ODBC result identifier and an optional row number: odbc_fetch_row($rs) Retrieving Fields from a Record The odbc_result() function is used to read fields from a record. This function takes two parameters: the ODBC result identifier and a field number or name. The code line below returns the value of the first field from the record: $compname=odbc_result($rs,1); The code line below returns the value of a field called "CompanyName": $compname=odbc_result($rs,"CompanyName"); Closing an ODBC Connection The odbc_close() function is used to close an ODBC connection. odbc_close($conn); An ODBC Example The following example shows how to first create a database connection, then a result- set, and then display the data in an HTML table. <html> <body> <?php $conn=odbc_connect('northwind','',''); if (!$conn) {exit("Connection Failed: " . $conn);} $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); if (!$rs) {exit("Error in SQL");} echo "<table><tr>"; echo "<th>Companyname</th>"; echo "<th>Contactname</th></tr>"; while (odbc_fetch_row($rs)) { $compname=odbc_result($rs,"CompanyName"); $conname=odbc_result($rs,"ContactName"); echo "<tr><td>$compname</td>";
  • 76. echo "<td>$conname</td></tr>"; } odbc_close($conn); echo "</table>"; ?> </body> </html> PHP MySQL Introduction MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows. Databases are useful when storing information categorically. A company may have a database with the following tables: "Employees", "Products", "Customers" and "Orders". Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons": LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger The table above contains three records (one for each person) and four columns (LastName, FirstName, Address, and City). Queries A query is a question or a request. With MySQL, we can query a database for specific information and have a recordset returned. Look at the following query: SELECT LastName FROM Persons The query above selects all the data in the "LastName" column from the "Persons" table, and will return a recordset like this: LastName Hansen
  • 77. Svendson Pettersen Facts About MySQL Database One great thing about MySQL is that it can be scaled down to support embedded database applications. Perhaps it is because of this reputation that many people believe that MySQL can only handle small to medium-sized systems. The truth is that MySQL is the de-facto standard database for web sites that support huge volumes of both data and end users (like Friendster, Yahoo, Google). Look at http://www.mysql.com/customers/ for an overview of companies using MySQL. PHP MySQL Connect to a Database Create a Connection to a MySQL Database. Before you can access data in a database, you must create a connection to the database. In PHP, this is done with the mysql_connect() function. Syntax mysql_connect(servername,username,password); Parameter Description servername Optional. Specifies the server to connect to. Default value is "localhost:3306" username Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process password Optional. Specifies the password to log in with. Default is "" Example In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code ?>
  • 78. Closing a Connection The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function: <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?> PHP MySQL Create Database and Tables A database holds one or multiple tables. Create a Database The CREATE DATABASE statement is used to create a database in MySQL. Syntax CREATE DATABASE database_name To learn more about SQL, please visit our SQL tutorial. To get PHP to execute the statement above we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection. Example The following example creates a database called "my_db": <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else
  • 79. { echo "Error creating database: " . mysql_error(); } mysql_close($con); ?> Create a Table The CREATE TABLE statement is used to create a table in MySQL. Syntax CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, .... ) To learn more about SQL, please visit our SQL tutorial. We must add the CREATE TABLE statement to the mysql_query() function to execute the command. Example The following example creates a table named "Persons", with three columns. The column names will be "FirstName", "LastName" and "Age": <?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); }
  • 80. // Create table mysql_select_db("my_db", $con); $sql = "CREATE TABLE Persons ( FirstName varchar(15), LastName varchar(15), Age int )"; // Execute query mysql_query($sql,$con); mysql_close($con); ?> Important: A database must be selected before a table can be created. The database is selected with the mysql_select_db() function. Note: When you create a database field of type varchar, you must specify the maximum length of the field, e.g. varchar(15). Primary Keys and Auto Increment Fields Each table should have a primary key field. A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique within the table. Furthermore, the primary key field cannot be null because the database engine requires a value to locate the record. The following example sets the personID field as the primary key field. The primary key field is often an ID number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically increases the value of the field by 1 each time a new record is added. To ensure that the primary key field cannot be null, we must add the NOT NULL setting to the field. Example $sql = "CREATE TABLE Persons ( personID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(personID), FirstName varchar(15), LastName varchar(15), Age int )"; mysql_query($sql,$con);