Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Oss Unit III

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 44

UNIT-III

Java Script & Mysql


Java script :Advantages of JavaScript –JavaScript Syntax–Data type– Variable– Array –
Operators and Expressions– Loops – functions – Dialog box– MySQL – The show Databases
and Table – The USE command –Create Database and Tables – Describe Table – Select, Insert,
Update, and Delete statement.

3.1 What is JavaScript?


JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script to
interact with the user and make dynamic pages. It is an interpreted programming language with
object-oriented capabilities..
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java.
JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript.
The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and
other web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript language.
 JavaScript is a lightweight, interpreted programming language.
 Designed for creating network-centric applications.
 Complementary to and integrated with Java.
 Complementary to and integrated with HTML.
 Open and cross-platform
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with
the user, control the browser, and dynamically create HTML content.
3.2 Advantages of JavaScript:
The merits of using JavaScript are −
 Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
 Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
 Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
 Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.
 JavaScript cannot be used for networking applications because there is no such support
available.
 JavaScript doesn't have any multi-threading or multiprocessor capabilities.
3.3 JavaScript Syntax:
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page,
but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as
a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
 Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
 Type − This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>

Your First JavaScript Code


Take a sample example to print out "Hello World". add that to prevent a browser from reading
the end of the HTML comment as a piece of JavaScript code. Next, we call a
function document.write which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.
Live Demo
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
Output:
Hello World!
3.4 JavaScript Data types:
One of the most fundamental characteristics of a programming language is the set of data
types it supports. These are the type of values that can be represented and manipulated in a
programming language.
JavaScript allows you to work with three primitive data types −
 Numbers, eg. 123, 120.50 etc.
 Strings of text e.g. "This text string" etc.
 Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data type
known as object. We will cover objects in detail in a separate chapter.
Note − JavaScript does not make a distinction between integer values and floating-point values.
All numbers in JavaScript are represented as floating-point values. JavaScript represents
numbers using the 64-bit floating-point format defined by the IEEE 754 standard.
3.5 JavaScript Variables:
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then refer to the
data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money, name;
//-->
</script>
Storing a value in a variable is called variable initialization. You can do variable initialization
at the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later.
For another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
 Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
 Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If you declare a local variable or function parameter with the same name as a global
variable, you effectively hide the global variable. Take a look into the following example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
Output:
Local
JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in mind.
 You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable
names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must begin with a
letter or an underscore character. For example, 123test is an invalid variable name
but _123test is a valid one.
 JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.
JavaScript Reserved Words
A list of all the reserved words in JavaScript is given in the following table. They cannot
be used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract else instanceof switch

boolean enum int synchronized

break export interface this


byte extends long throw

case false native throws

catch final new transient

char finally null true

class float package try

const for private typeof

continue function protected var

debugger goto public void

default if return volatile

delete implements short while

do import static with

double in super

3.6 JavaScript Array


JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
 By array literal
 By creating instance of Array directly (using new keyword)
 By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
The .length property returns the length of an array.
Output
Sonoo
Vimal
Ratan
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output
Arun
Varun
John
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output
Jai
Vijay
Smith

3.7 What is an Operator?


Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’
is called the operator. JavaScript supports the following types of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No Operator & Description


.

1 + (Addition)
Adds two operands
Ex: A + B will give 30

2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200

4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2

5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0

6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11

7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Example
<html>
<body>

<script type = "text/javascript">


<!--
var a = 33;
var b = 10;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->
</script>
Set the variables to different values and then try...
</body>
</html>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43
++a = 35
--b = 8
Set the variables to different values and then try...
Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No Operator & Description


.

1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then
the condition becomes true.
Ex: (A == B) is not true.

2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values
are not equal, then the condition becomes true.
Ex: (A != B) is true.

3 > (Greater than)


Checks if the value of the left operand is greater than the value of
the right operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
4 < (Less than)
Checks if the value of the left operand is less than the value of the
right operand, if yes, then the condition becomes true.
Ex: (A < B) is true.

5 >= (Greater than or Equal to)


Checks if the value of the left operand is greater than or equal to
the value of the right operand, if yes, then the condition becomes
true.
Ex: (A >= B) is not true.

6 <= (Less than or Equal to)


Checks if the value of the left operand is less than or equal to the
value of the right operand, if yes, then the condition becomes true.
Ex: (A <= B) is true.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);
document.write("(a != b) => ");
result = (a != b);
document.write(result);
document.write(linebreak);
document.write("(a >= b) => ");
result = (a >= b);
document.write(result);
document.write(linebreak);
document.write("(a <= b) => ");
result = (a <= b);
document.write(result);
document.write(linebreak);
//--> </script>
Set the variables to different values and different operators and then try...
</body> </html>
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...
Logical Operators
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −

Sr.No Operator & Description


.

1 && (Logical AND)


If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

2 || (Logical OR)
If any of the two operands are non-zero, then the condition
becomes true.
Ex: (A || B) is true.

3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then
the Logical NOT operator will make it false.
Ex: ! (A && B) is false.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
document.write("(a && b) => ");
result = (a && b);
document.write(result);
document.write(linebreak);
document.write("(a || b) => ");
result = (a || b);
document.write(result);
document.write(linebreak);
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body> </html>
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
Bitwise Operators
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −

Sr.No Operator & Description


.

1 & (Bitwise AND)


It performs a Boolean AND operation on each bit of its integer
arguments.
Ex: (A & B) is 2.

2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer
arguments.
Ex: (A | B) is 3.

3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its
integer arguments. Exclusive OR means that either operand one is
true or operand two is true, but not both.
Ex: (A ^ B) is 1.

4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the
operand.
Ex: (~B) is -4.

5 << (Left Shift)


It moves all the bits in its first operand to the left by the number of
places specified in the second operand. New bits are filled with
zeros. Shifting a value left by one position is equivalent to
multiplying it by 2, shifting two positions is equivalent to
multiplying by 4, and so on.
Ex: (A << 1) is 4.

6 >> (Right Shift)


Binary Right Shift Operator. The left operand’s value is moved
right by the number of bits specified by the right operand.
Ex: (A >> 1) is 1.

7 >>> (Right shift with Zero)


This operator is just like the >> operator, except that the bits
shifted in on the left are always zero.
Ex: (A >>> 1) is 1.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
document.write("(a & b) => ");
result = (a & b);
document.write(result);
document.write(linebreak);
document.write("(a | b) => ");
result = (a | b);
document.write(result);
document.write(linebreak);
document.write("(a ^ b) => ");
result = (a ^ b);
document.write(result);
document.write(linebreak);
document.write("(~b) => ");
result = (~b);
document.write(result);
document.write(linebreak);
document.write("(a << b) => ");
result = (a << b);
document.write(result);
document.write(linebreak);
document.write("(a >> b) => ");
result = (a >> b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...

Assignment Operators
JavaScript supports the following assignment operators −

Sr.No Operator & Description


.

1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C

2 += (Add and Assignment)


It adds the right operand to the left operand and assigns the result
to the left operand.
Ex: C += A is equivalent to C = C + A

3 −= (Subtract and Assignment)


It subtracts the right operand from the left operand and assigns the
result to the left operand.
Ex: C -= A is equivalent to C = C - A

4 *= (Multiply and Assignment)


It multiplies the right operand with the left operand and assigns the
result to the left operand.
Ex: C *= A is equivalent to C = C * A

5 /= (Divide and Assignment)


It divides the left operand with the right operand and assigns the
result to the left operand.
Ex: C /= A is equivalent to C = C / A

6 %= (Modules and Assignment)


It takes modulus using two operands and assigns the result to the
left operand.
Ex: C %= A is equivalent to C = C % A

Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |=
and ^=.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
document.write("Value of a => (a = b) => ");
result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a -= b) => ");
result = (a -= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a *= b) => ");
result = (a *= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a /= b) => ");
result = (a /= b);
document.write(result);
document.write(linebreak);
document.write("Value of a => (a %= b) => ");
result = (a %= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then executes
one of the two given statements depending upon the result of the evaluation.

Sr.No Operator and Description


.

1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y

Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ? 100 : 200) => ");
result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
document.write ("((a < b) ? 100 : 200) => ");
result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of
any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.

Type String Returned by typeof

Number "number"
String "string"

Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then t

3.8 EXPRESSIONS:
JavaScript supports conditional statements which are used to perform different actions
based on different conditions. Here we will explain the if..else statement.

Flow Chart of if-else

The following flow chart shows how the if-else statement works.
JavaScript supports the following forms of if..else statement −
 if statement
 if...else statement
 if...else if... statement.

if statement
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.
Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are
executed. If the expression is false, then no statement would be not executed. Most of the times,
you will use comparison operators while making decisions.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Qualifies for driving
Set the variable to different value and then try...
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to
execute statements in a more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
}
else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;

if( age > 18 ) {


document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Does not qualify for driving
Set the variable to different value and then try...

if...else if... statement


The if...else if... statement is an advanced form of if…else that allows JavaScript to make
a correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a part
of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
<html>
Output
Maths Book
Set the variable to different value and then try...

switch statement
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation,
and it does so more efficiently than repeated if...else if statements.
Flow Chart
The following flow chart explains a switch-case statement works.
Syntax
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches,
a default condition will be used.

switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the interpreter
would continue executing each statement in each of the following cases.
We will explain break statement in Loop Control chapter.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Break statements play a major role in switch-case statements. Try the following code that uses
switch-case statement without any break statement.

<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
case 'F': document.write("Failed<br />");
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block
Set the variable to different value and then try...
3.9 LOOPS:
The while Loop
The most basic loop in JavaScript is the while loop which would be discussed in this
chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long
as an expression is true. Once the expression becomes false, the loop terminates.
Flow Chart
The flow chart of while loop looks as follows −

Syntax
The syntax of while loop in JavaScript is as follows −
while (expression)
{
Statement(s) to be executed if expression is true
}

Example
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

The do...while Loop


The do...while loop is similar to the while loop except that the condition check happens
at the end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.

Flow Chart
The flow chart of a do-while loop would be as follows −

Syntax
The syntax for do-while loop in JavaScript is as follows −
do
{
Statement(s) to be executed;
} while (expression);
Note − Don’t miss the semicolon used at the end of the do...while loop.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

document.write("Starting Loop" + "<br />");


do {
document.write("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...

for Loop:
The 'for' loop is the most compact form of looping. It includes the following three important
parts −
 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will come
out of the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Flow Chart
The flow chart of a for loop in JavaScript would be as follows −
Syntax
The syntax of for loop is JavaScript is as follows −
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
Example
<html>
<body>
<script type = "text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++) {
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...
BREAK & CONTINUE STATEMENTS
JavaScript provides break and continue statements. These statements are used to
immediately come out of any loop or to start the next iteration of any loop respectively.
The break Statement
The break statement, which was briefly introduced with the switch statement, is used to exit a
loop early, breaking out of the enclosing curly braces.
Flow Chart
The flow chart of a break statement would look as follows −

Example
The following example illustrates the use of a break statement with a while loop. Notice how the
loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below
to the closing curly brace −

<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 20) {


if (x == 5) {
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>
Output
Entering the loop
2
3
4
5
Exiting the loop!
Set the variable to different value and then try...
We already have seen the usage of break statement inside a switch statement.
The continue Statement
The continue statement tells the interpreter to immediately start the next iteration of the
loop and skip the remaining code block. When a continue statement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise the control comes out of the loop.
Example
This example illustrates the use of a continue statement with a while loop. Notice how
the continue statement is used to skip printing when the index held in variable x reaches 5 −
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");

while (x < 10) {


x = x + 1;

if (x == 5) {
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!
Set the variable to different value and then try...
3.10 Function:
A function is a group of reusable code which can be called anywhere in your program.
This eliminates the need of writing the same code again and again. It helps programmers in
writing modular codes. Functions allow a programmer to divide a big program into a number of
small and manageable functions.
Like any other advanced programming language, JavaScript also supports all the features
necessary to write modular code using functions. You must have seen functions
like alert() and write() in the earlier chapters. We were using these functions again and again,
but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how to write your
own functions in JavaScript.
Function Definition
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
Syntax
The basic syntax is shown here.
<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters −
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>

Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of
that function as shown in the following code.
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>

</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>

Output

Click the following button to call the function

Say Hello

Use different text in write method and then try...

Function Parameters
Till now, we have seen functions without parameters. But there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the function
and any manipulation can be done over those parameters. A function can take multiple
parameters separated by comma.
Example
Try the following example. We have modified our sayHello function here. Now it takes two
parameters.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Output

Click the following button to call the function

Say Hello

Use different parameters inside the function and then try...

The return Statement

A JavaScript function can have an optional return statement. This is required if you want
to return a value from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the function to
return their multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters and concatenates them
before returning the resultant in the calling program.
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>

<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Output

Click the following button to call the function

Call Function
Use different parameters inside the function and then try...

3.11 DIALOG BOXES:


JavaScript supports three important types of dialog boxes. These dialog boxes can be
used to raise and alert, or to get confirmation on any input or to have a kind of input from the
users. Here we will discuss each dialog box one by one.
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example,
if one input field requires to enter some text but the user does not provide any input, then as a
part of validation, you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form>
</body>
</html>

Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays
a dialog box with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box
as follows.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
document.write ("User wants to continue!");
return true;
} else {
document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>

Prompt Dialog Box


The prompt dialog box is very useful when you want to pop-up a text box to get user
input. Thus, it enables you to interact with the user. The user needs to fill in the field and then
click OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a
label which you want to display in the text box and (ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt() returns null.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>

<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>

MYSQL
3.12 Introduction to MYSQL:
MySQL is a fast, easy to use relational database. It is currently the most popular open-
source database. It is very commonly used in conjunction with PHP scripts to create powerful
and dynamic server-side applications.

MySQL is used for many small and big businesses. It is developed, marketed and
supported by MySQL AB, a Swedish company. It is written in C and C++.

What is a Database?

A database is a separate application that stores a collection of data. Each database has one
or more distinct APIs for creating, accessing, managing, searching and replicating the data it
holds.

Nowadays, we use relational database management systems (RDBMS) to store and


manage huge volume of data. This is called relational database because all the data is stored into
different tables and relations are established using primary keys or other keys known as Foreign
Keys.

A Relational DataBase Management System (RDBMS) is a software that −


 Enables you to implement a database with tables, columns and indexes.
 Guarantees the Referential Integrity between rows of various tables.
 Updates the indexes automatically.
 Interprets an SQL query and combines information from various tables.
RDBMS Terminology
Before we proceed to explain the MySQL database system, let us revise a few definitions
related to the database.
 Database − A database is a collection of tables, with related data.
 Table − A table is a matrix with data. A table in a database looks like a simple
spreadsheet.
 Column − One column (data element) contains data of one and the same kind, for
example the column postcode.
 Row − A row (= tuple, entry or record) is a group of related data, for example the
data of one subscription.
 Redundancy − Storing data twice, redundantly to make the system faster.
 Primary Key − A primary key is unique. A key value can not occur twice in one
table. With a key, you can only find one row.
 Foreign Key − A foreign key is the linking pin between two tables.
 Compound Key − A compound key (composite key) is a key that consists of
multiple columns, because one column is not sufficiently unique.
 Index − An index in a database resembles an index at the back of a book.
 Referential Integrity − Referential Integrity makes sure that a foreign key value
always points to an existing row.
Reasons of popularity
MySQL is becoming so popular because of these following reasons:
 MySQL is an open-source database so you don't have to pay a single penny to use it.
 MySQL is a very powerful program so it can handle a large set of functionality of the
most expensive and powerful database packages.
 MySQL is customizable because it is an open source database and the open-source
GPL license facilitates programmers to modify the SQL software according to their
own specific environment.
 MySQL is quicker than other databases so it can work well even with the large data
set.
 MySQL supports many operating systems with many languages like PHP, PERL, C,
C++, JAVA, etc.
 MySQL uses a standard form of the well-known SQL data language.
 MySQL is very friendly with PHP, the most popular language for web development.
 MySQL supports large databases, up to 50 million rows or more in a table. The
default file size limit for a table is 4GB, but you can increase this (if your operating
system can handle it) to a theoretical limit of 8 million terabytes (TB).
MySQL Features
 Relational Database Management System (RDBMS): MySQL is a relational
database management system.
 Easy to use: MySQL is easy to use. You have to get only the basic knowledge of
SQL. You can build and interact with MySQL with only a few simple SQL
statements.
 It is secure: MySQL consist of a solid data security layer that protects sensitive data
from intruders. Passwords are encrypted in MySQL.
 Client/ Server Architecture: MySQL follows a client /server architecture. There is a
database server (MySQL) and arbitrarily many clients (application programs), which
communicate with the server; that is, they query data, save changes, etc.
 Free to download: MySQL is free to use and you can download it from MySQL
official website.
 It is scalable: MySQL can handle almost any amount of data, up to as much as 50
million rows or more. The default file size limit is about 4 GB. However, you can
increase this number to a theoretical limit of 8 TB of data.
 Compatibale on many operating systems: MySQL is compatible to run on many
operating systems, like Novell NetWare, Windows* Linux*, many varieties of
UNIX* (such as Sun* Solaris*, AIX, and DEC* UNIX), OS/2, FreeBSD*, and
others. MySQL also provides a facility that the clients can run on the same computer
as the server or on another computer (communication via a local network or the
Internet).
 Allows roll-back: MySQL allows transactions to be rolled back, commit and crash
recovery.
 High Performance: MySQL is faster, more reliable and cheaper because of its
unique storage engine architecture.
 High Flexibility: MySQL supports a large number of embedded applications which
makes MySQL very flexible.
 High Productivity: MySQL uses Triggers, Stored procedures and views which
allows the developer to give a higher productivity.
Disadvantages / Drawback of MySQL:
 MySQL version less than 5.0 doesn't support ROLE, COMMIT and stored procedure.
 MySQL does not support a very large database size as efficiently.
 MySQL doesn't handle transactions very efficiently and it is prone to data corruption.
 MySQL is accused that it doesn't have a good developing and debugging tool
compared to paid databases.
 MySQL doesn't support SQL check constraints.

MySQL SHOW TABLES command


 On opening the MySQL Command Line Client, enter your password.
 Select the specific database.
 Run the SHOW TABLES command to see all the tables in the database that has been
selected.
The USE command
The USE statement of MySQL helps you to select/use a database. You can also change to
another database with this statement. Once you set the current database it will be same until the
end of the session unless you change the it.
Syntax
USE db_name;
Example
Following example demonstrates the usage of the MySQL USE statement −
mysql> use test;
mysql> CREATE TABLE SAMPLE(NAME VARCHAR(10));
Query OK, 0 rows affected (1.65 sec)
mysql> INSERT INTO SAMPLE VALUES ('Raj');
Query OK, 1 row affected (0.19 sec)
mysql> use sample
Database changed
mysql> SELECT * FROM SAMPLE;
ERROR 1146 (42S02): Table 'sample.sample' doesn't exist
Example
Here we are creating a new database and changing the current database to it.
mysql> CREATE DATABASE myDatabase;
Query OK, 1 row affected (0.23 sec)

mysql> use myDatabase


Database changed
mysql>

4.2 MySQL Data Types

A Data Type specifies a particular type of data, like integer, floating points, Boolean etc.
It also identifies the possible values for that type, the operations that can be performed on that
type and the way the values of that type are stored.

MySQL supports a lot number of SQL standard data types in various categories. It uses
many different data types broken into mainly three categories: numeric, date and time, and string
types.

Numeric Data Type

Data Type Description


INT A normal-sized integer that can be signed or unsigned
SMALLINT A small integer that can be signed or unsigned.
BIGINT A large integer that can be signed or unsigned.
FLOAT(m,d) A floating-point number that cannot be unsigned.
DOUBLE(m,d) A double precision floating-point number that cannot be unsigned.
DECIMAL(m,d
An unpacked floating-point number that cannot be unsigned.
)

Date and Time Data Type:

Data Type Maximum Size Explanation


Values range from '1000-01-01' to Displayed as 'yyyy-mm-
DATE
'9999-12-31'. dd'.
Values range from '1000-01-01 Displayed as 'yyyy-mm-dd
DATETIME
00:00:00' to '9999-12-31 23:59:59'. hh:mm:ss'.
TIMESTAMP(m) Values range from '1970-01-01 Displayed as 'YYYY-MM-
00:00:01' UTC to '2038-01-19 03:14:07' DD HH:MM:SS'.
TC.
Values range from '-838:59:59' to
TIME Displayed as 'HH:MM:SS'.
'838:59:59'.
YEAR[(2|4)] Year value as 2 digits or 4 digits. Default is 4 digits.

String Data Types:

Data Type Maximum Size Explanation


Maximum size of Where size is the number of characters to store.
VARCHAR(size)
255 characters. Variable-length string.
Maximum size of
TEXT(size) Where size is the number of characters to store.
65,535 characters.
Where size is the number of binary characters
Maximum size of
BINARY(size) to store. Fixed-length strings. Space padded on
255 characters.
right to equal size characters.

Large Object Data Types (LOB) Data Types:

Data Type Maximum Size


TINYBLOB Maximum size of 255 bytes.
BLOB(size) Maximum size of 65,535 bytes.
MEDIUMBLOB Maximum size of 16,777,215 bytes.
LONGTEXT Maximum size of 4gb or 4,294,967,295 characters.

4.3 MYSQL Architecture

MySQL is based on tiered architecture consisting of both subsystems and support


components that interact with each other to read, parse, and execute queries and to cache and
return query results.

MySQL architecture consists of five primary subsystems that work together to


respond to a request made to MySQL database server.
Query Engine
 SQL Interface: The SQL interface provides the mechanisms to receive
commands and transmit results to the user.
 Parser: The parser constructs a query structure used to represent the query
statement in memory as a tree structure.
 Query Optimizer: The optimizer used is a SELECT-PROJECT-JOIN strategy
that attempts to restructure the query by first doing any restrictions.
 Query Execution: Execution of the query is handled by a set of library methods
designed to implement a particular query.
 Query Cache: This enables the system to check for frequently used queries and
shortcut the entire query optimization and execution stages altogether.
Buffer Manager/Cache and Buffers:
The caching and buffers subsystem is responsible for ensuring that the most
frequently used data are available in the most efficient manner possible.

The Storage Manager

 The storage manager interfaces with the operating system to write data to the disk
efficiently.
 The storage manager writes to disk all of the data in the user tables, indexes, and
logs as well as the internal system data.
The Transaction Manager
 The function of the Transaction manager is to facilitate concurrency in data
access.
 This subsystem provides a locking facility to ensure that multiple simultaneous
users access the data in consistent way.
Recovery Manager.
 The Recovery Manager’s job is to keep copies of data for retrieval later, in case of
loss of data.
 It also logs commands that modify the data and other significant events inside the
database

4.4 Administrative MSQL Commands


Here is the list of the important MySQL commands, which you will use time to time to
work with MySQL database −
 USE Databasename − This will be used to select a database in the MySQL
workarea.
 SHOW DATABASES − Lists out the databases that are accessible by the MySQL
DBMS.
 SHOW TABLES − Shows the tables in the database once a database has been
selected with the use command.
 SHOW COLUMNS FROM tablename: Shows the attributes, types of attributes,
key information, whether NULL is permitted, defaults, and other information for a
table.
 SHOW INDEX FROM tablename − Presents the details of all indexes on the table,
including the PRIMARY KEY.
 SHOW TABLE STATUS LIKE tablename\G − Reports details of the MySQL
DBMS performance and statistics.
4.5 MYSQL Database
We would need special privileges to create or to delete a MySQL database. So assuming
you have access to the root user, you can create any database using the
mysql mysqladmin binary.

4.5.1 Create Database:

 To create the new database, check the current databases to make sure a database of
that name doesn’t already exist;
 Then create the new one, and verify the existence of the new database:
Syntax:
mysql> CREATE DATABASE
Eg:
mysql> CREATE DATABASE Student;

4.5.2 SELECT Database


SELECT Database is used in MySQL to select a particular database to work with. This query
is used when multiple databases are available with MySQL Server.
We can use SQL command USE to select a particular database.
Syntax:
USE database_name;
Example:
USE customers;
4.5.3 Drop Database
We can drop/delete/remove a MySQL database easily with the MySQL command. You
should be careful while deleting any database because you will lose your all the data available in
your database.
Syntax:
DROP DATABASE database_name;
Example:
DROP DATABASE employees;
4.6 MYSQLTables:
 A table is a collection of rows, each row holding data for one record, each record
containing chunks of information called fields.
4.6.1 CREATE Table
CREATE TABLE command is used to create a new table into the database. A table
creation command requires three things:
o Name of the table
o Names of fields
o Definitions for each field
Syntax:
CREATE TABLE table_name (column_name column_type...);
Example:
CREATE TABLE cus_tbl(
cus_id INT NOT NULL AUTO_INCREMENT,
cus_firstname VARCHAR(100) NOT NULL,
cus_surname VARCHAR(100) NOT NULL,
PRIMARY KEY ( cus_id ) );
4.6.2 ALTER Table
MySQL ALTER statement is used when you want to change the name of your table or
any table field. It is also used to add or delete an existing column in a table.
The ALTER statement is always used with "ADD", "DROP" and "MODIFY" commands
according to the situation.
1) Add a column in the table
Syntax:
ALTER TABLE table_name ADD new_column_name column_def
[ FIRST | AFTER column_name ];
Example:
ALTER TABLE cus_tbl ADD cus_age varchar(40) NOT NULL;
2) MODIFY column in the table
The MODIFY command is used to change the column definition of the table.
Syntax:
ALTER TABLE table_name MODIFY column_name column_def
[ FIRST | AFTER column_name ];
Example:
ALTER TABLE cus_tbl MODIFY cus_name varchar(50) NULL;
3) DROP column in table
Syntax:
ALTER TABLE table_name DROP COLUMN column_name;
Example:
ALTER TABLE cus_tbl DROP COLUMN cus_address;
4) RENAME column in table
Syntax:
ALTER TABLE tbl_name CHANGE COLUMN ol_name ne_name
Example:
ALTER TABLE cus_tbl CHANGE COLUMN cus_name cus_title
varchar(20) NOT NULL;
5) RENAME table
Syntax:
ALTER TABLE table_name RENAME TO new_table_name;
Example:
ALTER TABLE cus_tbl RENAME TO cus_table;
4.6.3 TRUNCATE Table
MYSQL TRUNCATE statement removes the complete data without removing its
structure.
The TRUNCATE TABLE statement is used when you want to delete the complete data
from a table without removing the table structure.
Syntax: TRUNCATE TABLE table_name;
Example: TRUNCATE TABLE cus_tbl;
4.6.4 DESCRIBE Table
 It provides a description of the specified table or view.
 For a list of tables in the current schema, use the Show Tables command.
 For a list of views in the current schema, use the Show Views command.
 For a list of available schemas, use the Show Schemas command.
 If the table or view is in a particular schema, qualify it with the schema name.
 If the table or view name is case-sensitive, enclose it in single quotes.
 It displays the entire column from all the tables and views in a single schema by using
character '*'.
Syntax: DESCRIBE { table-Name | view-Name };
Eg: MYSQL> DESCRIBE age information;
4.7 MYSQL Statements
A list of commonly used MySQL statements to insert record, update record, delete
record, select record are given below.
4.7.1 Select Statement
The MYSQL SELECT statement is used to fetch data from the one or more tables. We
can retrieve records of all fields or specified fields.
Syntax: (Particular field)
SELECT expressions
FROM tables
[WHERE conditions];
Syntax: ( for all fields)
SELECT * FROM tables [WHERE conditions];
Example:
SELECT officer_name, address FROM officers
SELECT * FROM officers
MYSQL SELECT statement can also be used to retrieve records from multiple tables by
using JOIN statement.
Example
SELECT officers.officer_id, students.student_name
FROM students
INNER JOIN officers
ON students.student_id = officers.officer_id ORDER BY student_id;
4.7.2 Insert Statement
MYSQL INSERT statement is used to insert data in MYSQL table within the database.
We can insert single or multiple records using a single query in MYSQL.
Syntax:
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES
( value1, value2,...valueN );
Note: Field name is optional. If you want to specify partial values, field name is mandatory.
Example:
INSERT INTO emp VALUES (7, 'Sonoo', 40000);
(Or)
INSERT INTO emp(id,name,salary) VALUES (7, 'Sonoo', 40000);
4.7.3 Update Statement
MYSQL UPDATE statement is used to update data of the MYSQL table within the
database. It is used when you need to modify the table.
Syntax:
UPDATE table_name
SET field1=new-value1, field2=new-value2
[WHERE Clause]
Note:
 One or more field can be updated altogether.
 Any condition can be specified by using WHERE clause.
 You can update values in a single table at a time.
 WHERE clause is used to update selected rows in a table.
Example:
This query will update cus_surname field for a record having cus_id as 5.
UPDATE cus_tbl
SET cus_surname = 'Ambani'
WHERE cus_id = 5;
4.7.4 Delete Statement
MySQL DELETE statement is used to delete data from the MySQL table within the
database. By using delete statement, we can delete records on the basis of conditions.
Syntax:
DELETE FROM table_name
WHERE
(Condition specified);
Example:
DELETE FROM cus_tbl
WHERE cus_id = 6;
4.9 MYSQL JOINS
 MYSQL JOINS are used with SELECT statement.
 It is used to retrieve data from multiple tables.
 It is performed whenever you need to fetch records from two or more tables.
 There are three types of MYSQL joins:
o MYSQL INNER JOIN (or sometimes called simple join)
o MYSQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
o MYSQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
MYSQL Inner JOIN (Simple Join)
The MYSQL INNER JOIN is used to return all rows from multiple tables where the join
condition is satisfied. It is the most common type of join.
Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

Image representation:

Example:
SELECT officers.officer_name, officers.address, students.course_name
FROM officers
INNER JOIN students
ON officers.officer_id = students.student_id;
MYSQL Left Outer Join:
The LEFT OUTER JOIN returns all rows from the left hand table specified in the ON
condition and only those rows from the other table where the join condition is fulfilled.
Syntax:
SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON table1.column = table2.colu
mn;
Image representation:

Example:
SELECT officers.officer_name, officers.address, students.course_name
FROM officers
LEFT JOIN students
ON officers.officer_id = students.student_id;
MYSQL Right Outer Join:
The MYSQL Right Outer Join returns all rows from the RIGHT-hand table specified in
the ON condition and only those rows from the other table where the join condition is fulfilled.
Syntax:
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
Image representation:

Example:
SELECT officers.officer_name, officers.address, students.course_name,
students.student_name
FROM officers
RIGHT JOIN students
ON officers.officer_id = students.student_id;

You might also like