Ilovepdf Merged
Ilovepdf Merged
Explanation:
• The first line <!DOCTYPE html> defines the type of the document. It tells the web browser about
the language in which the web page is written.
• Next, the whole html code is enclosed within <html> …. </html> tag.
• Then, the html code is comprised of two sections i.e. Head section and Body section.
• The head section is defined within <head> ….. </head> tag. This section contains the meta
information (data about data) like document title, character set, style, script and other meta
information.
• The body section is defined within <body> …. </body> tag. This section contains main contents/
information that is visible on the web page.
Creating and running of HTML
• Step 1: Open any text/code editor like notepad/ notepad++ or sublime etc.
• Step 2: Write the HTML code.
• Step 3: Save the document by giving the desired primary name of the document with extension .html
or .htm
• Step 4: Open the document with using any of the web browser installed on the system like Chrome,
Firefox, Internet Explorer etc. to see the output of the html code.
HTML Tags/Elements
• Tags are the mark up and coded instructions referred to as source code. It is enclosed in a pair of
angle bracket. Usually there are opening (start) and closing (end) tags with containing some text
or objects in between.
• The opening tag begins with left angle bracket (<), followed by tagname and then right angle
bracket (>). For example:
• The closing tags are identical to opening tag except a forward slash (/) before the tag name.
For example:
Types of Tags
• Container tags are those tags that have both opening (on) tag and closing (off) tag. These tags
have some objects being affected between opening and closing tag.
Syntax:
Examples:
• Empty tags are those that have only opening tag and don’t have end tag associated. The reason
behind this is that they don’t act on block of objects. <br> and <hr> are examples of empty tag.
HTML Attributes
• Attributes are associated with tags. It allows to modify or change the appearance or behaviour of
the tag. The value of attribute is specified by percentage, pixels, unit value, names, directional etc.
Syntax:
-- This will set the nature.jpg picture on the background of the page and text color as white.
Note: If users don’t mention the attributes. These have some default value, like <body> tag has
the background color as white, text color as black and background picture as none by default.
Head Section and Elements of head section
• The head section is defined within <head> ... </head> tag. It consists of Meta information (data
about data) of the web page.
• The metadata is not displayed on the web page.
• It contains document title, character encoding, styles, scripts, links to the style sheet/ scripts files,
and other Meta information which is helpful for search engines.
• The elements of head section are:
1. <title>
2. <style>
3. <meta>
4. <link>
5. <script>
1. <title> tag: It is used to define the title of the web page. The title is displayed on browser’s tab,
and also displays in search engine’s result.
2. <style> tag: It is used to define internal CSS (Cascading Style Sheet). Internal CSS means
style information is applicable for single html page.
--The <p> elements of body section will be styled i.e. background color of the paragraph will
be black and text color will be white.
3. <meta> tag: It is used to define the meta information about the web page. Meta information
is helpful for web browsers and search engines. The meta information includes character
encoding, descriptions of web page, keywords for search engine, author information etc.
-- It is used to give the descriptions about page which helps to search engine for finding the page.
-- It is used to give the author name in web page.
-- It is used to specify the keywords in the web page which helps to search engine for indexing and
searching based on the keywords.
<meta> tag is also used to set the viewport of the web page i.e. visible area of the page for user. The
visible area depends on the device’ screen width where the web page is loaded and the screen size
differs from one device to another. Mobile phones have smaller screen rather than computer screen.
This viewport controls the scaling of screen.
-- width=device-width means the width of the page is set to follow the width of the device’
screen and initial-scale=1.0 means the initial zoom level is 1.0 when the page is loaded on the
browser for first time.
4. <link> tag: It is used to link the external style sheet to the html document. External CSS is
applicable for multiple web pages.
-- This will provide the link of external CSS file (styleA.css) to the HTML document.
5. <script> tag: It is used to define the client side scripting usually JavaScript to the HTML
document. The <script> tag can contain script elements/contents or it can also be used to point/link
the external script file.
-- This will provide the link of external JavaScript file (fileA.js) to the HTML document.
Formatting Elements
• Headings in HTML are defined by using <h1>, <h2>, <h3>, <h4>, <h5>,<h6> tags. These are level
of headings where <h1> is the largest level of heading and <h6> is the smallest level of heading.
Example: Heading Output: Heading
<!doctype html>
<html>
<head>
<title> HTML Heading </title>
</head>
<body bgcolor="green" text="white">
<h1> I am Heading Level 1 </h1>
<h2> I am Heading Level 2 </h2>
<h3> I am Heading Level 3 </h3>
<h4> I am Heading Level 4 </h4>
<h5> I am Heading Level 5 </h5>
<h6> I am Heading Level 6 </h6>
</body>
</html>
• Paragraph in HTML is defined by <p> tag.
Example: Paragraph Output: Paragraph
<!doctype html>
<html>
<head>
<title> HTML Paragraph </title>
</head>
<body bgcolor="lightgreen" text="darkwhite">
<p> I am Paragraph 1. kdirek djfepdf erede dkneir vbprnv
bknvhrand vjperisvn erdvk eineh nfei kneron jbeo jb enejoefn fenc
fkdd.</p>
<p> I am Paragraph 2. irpwnv derip mveroj ndfpn eirpe qwrie zcnp
mpeej eurbdjb euhclsjfb eocbjdb ueobdb euhdbk eln. </p>
</body>
</html>
• HTML defines various elements for text formatting and styling. These tag are container tags because
they act on block of text. These elements are:
Element (Tag) Description
<sup> It defines superscript text i.e. above the base line ( e.g. 10th)
<sub> It defines subscript text i.e. below the base line ( e.g. H2O)
<mark> It defines the marked/highlighted text.
<del> It defines the deleted/removed text.
<ins> It defines the inserted/edited text.
<tt> It defines teletype (monospace) text which means each letter is displayed with equal fixed size width.
Example1: Formatting Elements Output1: Formatting Elements
<!doctype html>
<html>
<head>
<title> HTML Formattng </title>
</head>
<body bgcolor="lightgreen" text="darkgreen">
<h1> Bold, Italic, Underlined Formattng </h1>
I am <b>Bold/dark</b> text. <br>
I am <i>Italic </i>text. <br>
I am <u> Underlined</u> text. <br>
I am <b> <i> <u>bold, italic and underlined </b></i></u> text.
<h1> Strong, Emphasized Formattng</h1>
I am <strong>strong </strong> text. I have extra importance.<br>
I am <em>emphasized </em>text. I have extra importance.
<h1> Big, Small Formattng</h1>
I am <big>big </big> text. I am little bigger than other text. <br>
I am <small>small </small>text. I am little smaller than other text.
</body></html>
Example2: Formatting Elements Output2: Formatting Elements
<!doctype html>
<html>
<head><title> HTML Formattng </title></head>
<body bgcolor="lightgreen" text="darkgreen">
<h1> Superscript</h1>
(A+B)<sup>2</sup> = A<sup>2</sup> + B<sup>2</sup> + 2AB <br>
(A-B)<sup>3</sup> = A<sup>3</sup> - B<sup>3</sup> - 3AB (A-B)
<h1> Subscript</h1>
Water - H<sub>2</sub>O <br>
Baking Soda - NaHCO<sub>3</sub> <br>
Vinegar - C<sub>2</sub>H<sub>4</sub>O<sub>2</sub>
<h1> Highlighted Text </h1>
<mark> This is highlighted text. </mark>
<h1> Deleted, Inserted Text </h1>
Price: <del>3000/- </del> <ins>2500/- </ins>(special discount)
<h1> Strikethrough text </h1>
<strike> I am strikethrough text. </strike> Same as deleted
text.</body></html>
• <pre> tag: It is used to define pre - formatted text.
Suppose user wants to present tabular data on the web page. Then, <pre> tag can be used to
display tabular data without using any additional tag. It preserves the spaces and line break as in
the code.
Example2: Pre Output2: Pre
<!doctype html>
<html>
<head><title> Pre tag </title></head>
<body bgcolor="lightgreen" text="darkgreen">
<h1> Pre formatted text </h1>
<pre>
Sr.No. Name Course
01 Rakesh O level
02 Shyam A level
03 Lakshmi CCC
</pre></body></html>
HTML Tables
• Tables are the combinations of rows and columns. Rows are arranged horizontally and columns are
arranged vertically.
• In HTML, <table> tag is used to define table. Each row of the table is defined by <tr> tag. Each
cell/data is defined by <td>. The header cell is defined by <th> tag.
• Attributes of <table> tag:
width: To specify the width of table.
height: To specify the height of table.
border: To specify the border of table.
bgcolor: To specify background color of table.
Example: Table Output: Table
<!doctype html>
<html>
<head><title> Table in HTML </title></head>
<body bgcolor="silver">
<h1> List of Products </h1>
<table width="80%" border="1">
<tr>
<th> Product Name</th>
<th> Make</th>
<th> Cost</th>
</tr>
<tr>
<td>Mouse</td>
<td>Dell </td>
<td>300</td>
</tr>
<tr>
<td>Keyboard</td>
<td>HP</td>
<td>400</td>
</tr>
<tr>
<td>Pen drive</td>
<td>Sony</td>
<td>800</td>
</tr>
</table></body></html>
In above table, there are 04 rows, and 03 columns. Therefore,
In the code, there are 04 set of <tr> ….. </tr>.
The first <tr> set has 03 set of <th> … </th>.
The next three <tr> has 03 set of <td> … </td>.
rowspan and colspan – attribute of <td> tag:
<!doctype html>
<html>
<head><title> Cellspacing and Cellpadding </title>
</head>
<body bgcolor="khaki" text="chocolate">
<h1> Cellspacing and Cellpadding in table </h1>
<table width="80%" border="1" cellspacing=30px
cellpadding=50px>
<tr> <td> N </td> <td> I </td> <td> E </td> </tr>
<tr> <td> L </td> <td> I </td> <td> T </td> </tr>
</table>
</body>
</html>
Adding caption in table
• The <caption> tag is used to title or name of the table. It gives the short descriptions about table.
Example2: Table Caption Output2: Table Caption
<!doctype html>
<html>
<head><title> Caption in table</title>
</head>
<body bgcolor="linen" text="chocolate">
<h1> Caption in table </h1>
<table width="60%" border="1" align="center">
<caption align="bottom">Table 1: Courses offered by NIELIT </caption>
<tr> <th> Course </th> <th> Duration </th> <th> Eligibility</th></tr>
<tr> <td> A level </td> <td> 01 Year </td> <td> Graduation or
diploma</td></tr>
<tr> <td> O level </td> <td> 01 Year </td> <td> 10+2</td></tr>
<tr> <td> CCC </td> <td> 80 hours </td> <td> No minimum
qualification</td></tr>
</table> </body> </html>
Images in HTML:
• Images can be inserted in web pages using <img> tag. Images are used to enhance the
design and appearance of web page. <img> tag is empty tag which means that it does not
have closing tag.
alt: This attribute provides alternate text for image. If for any reason the browser is not able to
display the image (because of slow internet connection, error in path, image corruption etc.), then
the alternate text will be displayed in place of image.
Syntax:
Example: Images Output: Images
<!doctype html>
<html>
<head>
<title> Inserting Images </title>
</head>
<body bgcolor="lightgreen" text="darkgreen">
• Hyperlinks are found in almost every web pages that allows to jump into another web document or
on specific location of same web page by clicking on it.
• <a> tag (Anchor) is used to define hyperlink and hypertext in the html. A link does not have to be
text only, but it can be images, videos or any other document.
• When the mouse is moved over hypertext, the mouse arrow turns into little hand shape.
• Syntax: <a href=“address/path of the file”> Type hypertext here….. </a>
• Attributes of <a> tag:
href: It defines the address or path the file which is being hyperlinked.
target: This attribute defines where to open the linked document.
• _blank, _self, _parent, _top, or name of the frame.
_blank: It opens the linked document in a new window or tab.
_self: It opens the linked document in same window or tab. This is default value.
_parent: It opens the linked document in parent frame.
_top: It opens the linked document in the full body of the window.
framename: It opens the linked document in that frame whose name is provided.
• title: This attribute specifies the extra information about an element. The extra information will be
shown as tooltip when mouse is moved over the element. It can be used with <img>, <a>, <h1>,
<p> etc elements.
Example– Hyperlinks Output-
<!doctype html>
<html>
<head>
<title> Links in HTML </title>
</head>
<body bgcolor="silver">
<a href="heading.html" target="_blank"> Link 1 :
Heading </a><br>
<a href="paragraph.html" target="_blank">Link 2:
Paragraph </a><br>
<a href="formatting.html" target="_blank">Link 3:
Formatting </a><br>
</body>
</html>
heading.html paragraph.html formatting.html
When user will click on Link 1: Heading, then the user will jump to heading.html web page.
Likewise, Link 2: Paragraph will follow the paragraph.html web page. Link 3: Formatting will
follow the formatting.html web page.
Images as Hyperlink: Images can be used as links using <img> tag enclosed within <a> tag.
Example- Image Hyperlink Output:
<!doctype html>
<html>
<head><title> Image as hyperlink </title>
</head>
<body bgcolor="silver">
<a href="dhoni.html" target="_blank">
<img src="dhoni.jpg" height="300px"
width="400px" title="Click to know more" When user will click on image, the
alt="pic of dhoni"> dhoni.html web page will be opened in new
tab/window.
</a>
When mouse is moved over the image, the
</body>
text “Click to know more” will be displayed
</html>
as Tooltip because of title attribute used.
Linking within same page:
• HTML bookmarks are used to allow jump over a specific part of web page. Bookmarks are
useful when the webpage is very long and have lots of contents.
• To create linking within same page, following two steps needs to be followed:
Step 1: First, create the bookmark. Use id attribute to define bookmark for element.
For e.g. <h1 id=“ch1”> Chapter 1 </h1>
Step 2: Then, create hyperlink to jump over the bookmark. Use # (hash) symbol while
defining href value of <a>. Hash (#) refers to the id.
For e.g. <a href=“#ch1”> Click here to go Chapter 1 </a>
While clicking on hypertext, it will move to that part of the webpage where id of element is ch1.
<p> dfdj dfld ri dkd ddfke ird ronerieokfbvjr dhkvl er vjpejih weorxcl
Example – Links within same page:
hov, n povepovn jokjhepe d dkfe dniu </p><p> dfdj dfld ri dkd ddfke
<!doctype html> ird ronerieokfbvjr dhkvl er vjpejih weorxcl hov, n povepovn jokjhepe d
<html> dkfe dniu </p><p> dfdj dfld ri dkd ddfke ird ronerieokfbvjr dhkvl er
<head><title> Links within same page </title></head> vjpejih weorxcl hov, n povepovn jokjhepe d dkfe dniu </p><p> dfdj
<body bgcolor="silver"> dfld ri dkd ddfke ird ronerieokfbvjr dhkvl er vjpejih weorxcl hov, n
<h1> Index </h1> povepovn jokjhepe d dkfe dniu </p><p> dfdj dfld ri dkd ddfke ird
<a href="#ch1"> Chapter 1 </a><br> ronerieokfbvjr dhkvl er vjpejih weorxcl hov, n povepovn jokjhepe d
<a href="#ch2"> Chapter 2 </a><br> dkfe dniu </p><p> dfdj dfld ri dkd ddfke ird ronerieokfbvjr dhkvl er
<a href="#ch3"> Chapter 3 </a><br> vjpejih weorxcl hov, n povepovn jokjhepe d dkfe dniu </p>
<hr> <h1 id="ch3"> Chapter 3 </h1>
<h1 id="ch1"> Chapter 1 </h1> <p> mkjt jr nrjt rtpr rtrk kikfdnk ortor yruypg peir awqw vnere
<p> dferi dkfkeird roner vner vnkie riero lsdreo df eejre dkf keriejk dkfjjk ehrkfi jk fjf</p> pweorvn vnnh ero hsfhdl dhls hf kdferi dkfkeird roner </p><p> mkjt jr
<p> dferi dkfkeird roner vner vnkie riero lsdreo df eejre dkf keriejk dkfjjk ehrkfi jk fjf</p> nrjt rtpr rtrk kikfdnk ortor yruypg peir awqw vnere pweorvn vnnh ero
<p> dferi dkfkeird roner vner vnkie riero lsdreo df eejre dkf keriejk dkfjjk ehrkfi jk fjf</p> hsfhdl dhls hf kdferi dkfkeird roner </p><p> mkjt jr nrjt rtpr rtrk
<p> dferi dkfkeird roner vner vnkie riero lsdreo df eejre dkf keriejk dkfjjk ehrkfi jk fjf</p> kikfdnk ortor yruypg peir awqw vnere pweorvn vnnh ero hsfhdl dhls hf
<p> dferi dkfkeird roner vner vnkie riero lsdreo df eejre dkf keriejk dkfjjk ehrkfi jk fjf</p> kdferi dkfkeird roner </p><p> mkjt jr nrjt rtpr rtrk kikfdnk ortor
<p> dferi dkfkeird roner vner vnkie riero lsdreo df eejre dkf keriejk dkfjjk ehrkfi jk fjf</p> yruypg peir awqw vnere pweorvn vnnh ero hsfhdl dhls hf kdferi
<p> dferi dkfkeird roner vner vnkie riero lsdreo df eejre dkf keriejk dkfjjk ehrkfi jk fjf</p> dkfkeird roner </p><p> mkjt jr nrjt rtpr rtrk kikfdnk ortor yruypg peir
awqw vnere pweorvn vnnh ero hsfhdl dhls hf kdferi dkfkeird roner
<p> dferi dkfkeird roner vner vnkie riero lsdreo df eejre dkf keriejk dkfjjk ehrkfi jk fjf</p> </p>
<h1 id="ch2"> Chapter 2 </h1> </body>
</html>
Output:
• Adding URL as hyperlink: URL can also be added as hyperlink.
Example – URL as hyperlink:
<!doctype html>
<html>
<head><title> URL as hyperlink </title> </head>
<body bgcolor="plum">
<a href="http:\\www.nielit.gov.in" target="_blank"> Go to the NIELIT's website
</a><br>
<a href="https:\\www.facebook.com" target="_blank"> Go to the Facebook's
website </a><br>
<a href="https:\\www.youtube.com" target="_blank"> Go to the YouTube's
website </a><br>
</body>
</html>
Output:
Audio in HTML:
The audio files can be embedded in web page using <audio> element.
Attribute of <audio> element:
controls :- It is used to specify audio controls like play, pause and volume.
loop :- It specifies that audio will play again every time when it is finished.
muted :- It specifies that the audio output should be muted.
autoplay :- It is used to start/play audio file automatically when the web page is loaded.
These attributes do not have any value.
<source> element:
The <source> element is used within <audio> element. It defines the audio file to be embedded into
web page. We can also specify alternative audio files; browser will use the first recognized format.
Attributes of <source> element:
src – It specifies the path of audio file.
type- It specifies the type of the audio file.
User can specify the text between <audio> ….. </audio> that will be displayed only when browser
does not support <audio> element.
Supported HTML Audio Media Types:
File Format Media Type
mp3 audio/mpeg
ogg audio/ogg
wav audio/wave
Example of <audio> element: output:
<html>
<head>
<title> Audio </title>
</head>
<body bgcolor="lightblue" text="gold">
<h1> Example of Audio file in HTML </h1>
<audio controls autoplay loop>
</audio>
</body>
</html>
Example of <video> element:
<html>
<head>
<title> Video </title>
</head>
<body bgcolor="lightblue" text="blue">
<h1> HTML Video Example </h1>
<video width="520" height="340" controls autoplay loop muted>
<source src="HTML5Tutorial.mp4" type="video/mp4">
</video>
</body>
</html>
Output:
Forms
• A HTML form or web form allows collecting user’s input. The users fill their information using
forms elements like textboxes, radio buttons, checkboxes etc.
• For example a web form can be used to collect feedback from user for the website.
• Another example of web form is login form (as shown in figure). This form contains two
textboxes asking for ‘username’ and ‘password’, and a button labeled as ‘login’ to send the
form’s information to server for processing. It also contains a hyperlink ‘Not registered’ to open
new page for creating new account.
Figure: An example of login form
• The <form> element defines a form in HTML:
<form>
….. form elements ……
</form>
Attributes of <form> element
When the form is submitted, this login_validate.php page contains the action to be
performed that is to handle the form’s data and where the data proceed further.
• target :- It specifies where to open result after submitting the form. It can have value:
_self :- The result will be displayed in same tab. It is default value.
_blank :- in new tab.
_top :- in the entire browser window i.e. “breaks out of all frames”.
_parent :- in the parent of the current frame.
For example: <form target=“_blank”>
• method :- It specifies the HTTP method to be used when submitting the form data. It can have
value:
get :- It is default value. It is not secure method because the submitted form’s data will
be visible in the address field of the browser.
post :- We must use post method when form contains sensitive or personal information
because it does not display the submitted form data in the address field of the
browser.
For example:
<form method=“post”>
Elements of <form>
The <form> element can contain one or more of the following form elements or controls:
<label>
<input>
<textarea>
<button>
<select> and <option>
<fieldset> and <legend>
<optgroup>
<label> element
• This element is used to define label or naming of form elements. It provide a usability
improvement for mouse users i.e. if a users clicks on the text within the <label> element, it
toggles the control associated with it.
Syntax :
<label for=“element_id”>
…
form content
…
</label>
• Attribute of <label>
for :- this attribute is used to specify id of the element that label is bound to.
<input> element
A login form is created which has two labels, two textboxes and two buttons.
In username label – for attribute is set to “uid”. Similarly for password textbox and password
label.
• The <input type= “radio”> defines radio buttons. Radio buttons allow a user to select a single
option from a group of options.
<input type="radio" id= " " name=" ">
Code: Radio Button Output: Radio Button
<html>
<head> <title>Radio Buttons </title> </head>
<body bgcolor="lightgreen" text="blue">
<h1> Radio Buttons</h1>
<form>
<label> Select Your Gender</label><br>
<input type="radio" name="gender" id="male"> <label
for="male"> Male </label>
<input type="radio" name="gender" id="female">
<label for="female"> Female </label>
</form>
</body>
</html>
<input> element – For creating check box
• The <input type= “checkbox”> defines check box. Check boxes allow a user to select multiple
options from a group of options.
<input type="checkbox" id= " " name= " ">
Code: Checkbox Output: Checkbox
<html>
<head> <title> Check Box </title> </head>
<body bgcolor="lightgreen" text="blue">
<h1> Check Boxes</h1
<form>
<label> Select Your Expertise</label> <br>
<input type="checkbox" name="expertise" id="HTML"> <label
for="HTML"> HTML </label>
<input type="checkbox" name="expertise" id="CSS"> <label
for="CSS"> CSS </label>
<input type="checkbox" name="expertise" id="Bootstrap"> <label
for="Bootstrap">
Bootstrap </label>
<input type="checkbox" name="expertise" id="PHP"> <label
for="PHP"> PHP </label>
<input type="checkbox" name="expertise" id="Java"> <label
for="Java"> Java </label>
</form></body></html>
Variations of <input> element
There are also some other variation of <input> element that can be used in several ways by defining
<input type= “month">
value of type attribute: <input type= “button">
• Output: Button
<form autocomplete="on">
<input type="text" placeholder="Username" id="uid">
<input type="text" placeholder="Password"
autocomplete="off"> <br><br>
<label> Login As:
<input type="radio" id="fac" name="loginas"
disabled><label for="fac"> Faculty </label>
<input type="radio" checked id="stu" name="loginas">
<label for=stu"> Student </label>
<br><br> <input type="Submit" value="login"> </form>
<textarea> element
• Multiline input controls are created using <textarea> tag. It is used whenever large text needs to be
entered.
cols: It defines the number of visible characters in the columns/width of the textarea.
autofocus, disabled, maxlength, name, placeholder, readonly, required etc attributes can also
be used.
Code: Output:
<label for="comment">
Enter Your Comments/Suggestions: </label> <br>
<textarea id="comment" rows=8 cols=25> </textarea>
<br> <br>
<label for="comment">
Enter Your Address: </label> <br>
<textarea id="address" rows=8 cols=25> </textarea>
<button> element
• This tag/element is used to create clickable button. We can place text or images inside <button>
…… </button>.
• Attributes of <button>:
autofocus, disabled, name, type (button, submit, reset) , value etc. are attributes of
<button>.
• Output:
<select> and <option> element
• These elements are used to create drop down box where users have to select options form available
pre-defined options.
• <option> : It is used inside <select> … </select>. It defines the options of drop down box.
• Attributes of <select>
size: It specifies the number of options visible in the dropdown box.
Code: Output:
<label for="course"> Select Course </label>
<select id="course">
<option> O level </option>
<option> A level </option> When user will click on drop down box, a list of
<option> CCC </option> options will drop like:
</select>
Listbox
• List box can be created using size attribute with <select> tag
Code: Output:
<label for="course"> Select Course </label>
<select id="course" size=4 multiple>
<option> O level </option>
<option> A level </option>
<option> CCC </option>
<option> Certificate Course in C </option>
<option> Certificate Course in Python </option>
In the code, the value of size is 4, therefore
<option> Certificate Course in Java </option>
<option> Certificate Course in PHP </option> 4 option is displayed, rest of the option can
</select> be chosen using scroll button.
<fieldset> and <legend> element
• The <fieldset> element is used to group the related data of form. It makes a box around the related
data.
• The <legend> element is used to give caption to the <fieldset>. It is placed within <fieldset> …..
</fieldset> element.
• Attributes of <fieldset>
name: It gives the name for the fieldset.
form: It specifies which form belongs to fieldset. The id of the form is given as value to this
attribute.
Code Output
<form autocomplete="on">
<fieldset>
<legend> Personal Details </legend>
<label for="name"> Name : <input id="name" type="text"><br>
<label for="fname"> Father's Name :<input id="fname" type="text"><br>
<label for="dob"> Date of Birth :<input id="dob" type="date"><br>
</fieldset>
<fieldset>
<legend> Contact Details </legend>
<label for="mobile"> Mobile : <input id="mobile" type="number"><br>
<label for="emailid"> Email Id :<input id="emailid" type="email"><br>
</fieldset>
<input type="submit">
<input type="reset">
</form>
<optgroup> element
Syntax
In example1, selector is h1 element/tag. CSS properties will be applicable for h1 tag. It will set
the background color as lightgreen and the color of text as green.
In example2, selector is p element/tag. CSS properties will be applicable for p tag. It will set the
background color as lightblue and the color of text as blue.
Code output
<html>
<head><title> CSS </title>
<style>
p
{
background-color: lightblue;
color: blue;
}
h1
{
background-color: lightgreen;
color: green;
}
</style>
</head>
<body>
<h1> About NIELIT Gorakhpur </h1>
<p> NIELIT, Gorakhpur Centre (Formerly DOEACC Society, Gorakhpur Centre ) was established
as Centre for Electronics Design & Technology of India (CEDTI) in June, 1989. It is an
Autonomous Scientific Society under the administrative control of Ministry of Communications
and Information Technology, Govt. of India. It caters to the training, Consultancy, Design and
Product Development needs of small scale IT Industries and allied sectors. It also conducts
training programmes for promotion of Entrepreneurs. </p> Note: Don’t forget to write CSS code in head
<p> The centre has a total covered area of 3450 sq. mtrs and hostel building for 70 students. It is section of the HTML within <style> …..
now under the Administrative control of NIELIT , Govt. of India as per the decision of the
government (DeitY) office Memorandum No. 15 (45)/2002 Gov. dated 29 Nov. 2002. </p> </style> tag.
</body>
</html>
• There are following three types of CSS:
The type of CSS is actually concerned with how we add or insert the CSS code into HTML
document.
• Inline CSS is used to apply CSS on single element. It is written as value using style attribute
of element/tag.
• Internal CSS is used to apply CSS on a single document or page. It is written inside the
<style> …</style> tag within head section of html.
• External CSS is used to apply CSS on multiple pages. The CSS code is written in a CSS file
(.css) and then included/linked in HTML documents.
Inline CSS
It is defined by writing CSS code as the value using style attribute of element.
It is defined by writing CSS code inside the <style> …</style> tag within head section of html.
<style>
p{
color:white;
background-color:blue;
h1 {
color:white;
background-color:green;
</style>
Internal CSS output
<html>
<head>
<title> Internal CSS </title>
<style>
p{
color:white;
background-color:blue;
}
h1 {
color:white;
background-color:green;
}
</style> CSS styles are applied to all elements
</head>
<body>
of the page for which these are
<h1>I am Heading 1 </h1> specified using <style> … </style>
<p>I am Paragraph 1 </p>
<h1> I am Heading 2 </h1> tag in head section.
<p> I am Paragraph 2 </h1>
</body>
</html>
External CSS
External CSS is used to apply CSS on multiple pages. The CSS code is written in a CSS file (.css) and
then it is included/ linked in HTML documents.
Following two steps are strictly followed to use External CSS:
Step 1: Write your CSS code using text editor and save it with .css extension (for example
style.css). The CSS file must contain only CSS code. Do not write <style> or any other HTML
tag/elements in CSS file.
Step 2: Use <link> tag to include/link external CSS file in HTML file within <head> .. </head>
section. The external CSS can be included in multiple HTML documents like:
Code explaining External CSS
code for style.css code for fileA.html Output (File A)
p{ <html>
<head>
color:white;
<title> File A </title>
background-color:blue; <link rel="stylesheet" type="text/css" href="style.css">
text-align:justify; </head>
<body>
}
<h1>Front End </h1>
h1 { <p>Front end refers to client side design of website. Front end is involved with what the
users see and interact with the website i.e. the User Interface (UI) which includes the
color:white; design, layout, navigation menu, text, images, videos, image gallery etc.</p>
<p>Back end refers to server side development of website. It is involved with what the
text-align:center; user cannot see in the browser like database and server. It concerns with security aspects,
data storage and manipulation, content management, user authentication etc.</p>
}
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Day-7: JavaScript
Topics to be covered
JavaScript Basics
Operators
Variables
Decision making
Switch-case
Loops
JavaScript Basics
What is JavaScript:
Features of JavaScript:
All popular web browsers support JavaScript as they provide built-in execution
environments.
JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
It is a light-weighted and interpreted language.
It is a case-sensitive language.
JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
It provides good control to the users over the web browsers.
By using JavaScript we are able to create games, animated 2D and 3D graphics,
comprehensive database-driven apps, and much more!
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Language – to specify scripting language like JavaScript. Now in the recent versions of
HTML (and XHTML, its successor) it is not used.
Type – Indicates the scripting language in use and for JavaScripts, it shall be set to
"text/JavaScript".
Src-It is used to specify the URL of an external script file.
. . . . . . . . . . . . . . . . .
JavaScript Code . . . . . . . . . . . . . . . . .
</script>
Add javascript
<html>
<head>
<title>First JavaScript program</title>
</head>
<body>
<script type="text/javascript">
alert("Hello World");
</script>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello World");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
</body> </html>
main.js:
function msg(){
alert("Hello World");
}
index.html:
<html>
<head>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
Javascript output
The following method / properties are used to do so:
document.write() method:
<html>
<body>
<script>
</script>
</body>
</html>
window.alert() method:
<html>
<body>
<script>
</script>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
console.log() method:
console.log() method is used to check whether the data in reaching upto the browser or not. This is
mainly used for debugging purposes and the data is displayed only in debugging console mode.
This mode can be activated by pressing F12 or through setting options.
<!doctype html>
<html>
<body>
<script type="text/javascript">
var x = 10;
var y = 20;
var z=y-x;
document.write("nielit");
console.log(34);
console.log(true);
console.log(x+3);
console.log(z);
</script>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
innerHTML property:
<html>
<head>
<title>innerHTML property</title></head>
<body>
<p id="greet"></p>
<script>
</script>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables
in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore (_), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value 1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
Local variable:
A local variable is declared inside block or function. It is accessible within the function or
block only. For example:
Example: Example:
<script> <script>
function abc(){ if(10<13){
var x=10;//local variable var y=20;//local variable
} }
</script> </script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Global variable:
A global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:
Example:
<script>
var data=200;//global variable
function a(){
document.write(data);
}
function b(){
document.write(data);
}
a();//calling JavaScript function
b();
</script>
JavaScript Operators:
JavaScript operators are symbols that are used to perform operations on operands. For
example:
var sum=10+20;
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
Arithmetic Operators:
Comparison Operators:
Bitwise Operators:
Logical Operators:
Assignment Operators:
Decision Making
The decision making is done through if-else statement that is used to execute the code
whether condition is true or false. There are three forms of if statement:
1. If Statement
2. If else statement
3. if else if statement
If Statement: False
If
It evaluates the content only if expression is true. Condition
Syntax:
True
if (expression){
//content to be evaluated
} If block
Example:
<script>
var x=20;
if(x>10){
document.write("The value of x is greater than 10");
}
</script> Output:
The value of x is greater than 10
If else Statement:
Syntax:
if(expression){
//content to be evaluated if condition is true
}
else{
The nested if...else statement is used when a program requires more than one test
expression. When an if else statement is present inside the body of another “if” or “else” then
this is called nested if else.
Example:
Syntax:
/* Program to find greatest among three numbers */
if(expression)
{ <script>
if(expression1) var a=10,b=20,c=30;
{ if(a>b)
statement-block1; {
} if(a>c)
else {
{ document.write(a+ “is greatest");
statement-block 2; }
} else
} {
else document.write(c+ “is greatest");
{ }
if( expression3 ) }
{ else
statement-block3; {
} if(b>c)
else {
{ document.write(b+ “is greatest");
statement-block 4; }
} else
} {
document.write(c+ “is greatest");
}
Output: }
30 is greatest </script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Syntax:
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Example:
<script>
var x=50;
if(x==10){
document.write("x is equal to 10");
}
else if(x==30){
document.write("x is equal to 30");
}
else if(x==50){ Output:
document.write("x is equal to 50"); x is equal to 50
}
else{
document.write("x is not equal to 10, 30 or 50");
}
</script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Switch-case Statement
The switch statement is used to execute one code from multiple expressions.
Syntax:
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example:
<script>
var grade='C';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
Output:
}
C Grade.
document.write(result);
</script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Loops:
A Loop executes the sequence of statements many times until the stated condition becomes
false. The loops are used to iterate the piece of code. It makes the code compact.
1. for loop
2. while loop
3. do-while loop
For loop:
The ‘for’ loop iterates the elements for fixed number of times. It should be used if number of
iteration is known.
Syntax:
for (initialization; condition; increment or decrement)
{
code to be executed
}
Example:
<script> Output:
for (i=1; i<=5; i++) 1
{ 2
document.write(i + "<br/>") 3
} 4
</script> 5
while loop:
The while loop is used to iterate over a block of code as long as the test expression
(condition) is true.
Syntax:
initializtion
while (condition)
{
code to be executed
increment or decrement
}
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example:
<script>
var i=11; Output:
while (i<=15) 11
{ 12
document.write(i + "<br>"); 13
i++; 14
} 15
</script>
do while loop:
The do while loop iterates the elements for the finite number of times like while loop. But,
code is executed at least once whether condition is true or false.
Syntax:
do{
code to be executed
}while (condition);
Example: Output:
<script> 21
var i=21; 22
do{ 23
document.write(i + "<br/>"); 24
i++;
}while (i<=25); 25
</script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Day 7- assignment
1. Write a JavaScript code that take two variables and interchange their values.
2. Write a JavaScript code that take two variables and interchange their values
without take third variable.
3. A student got marks 76, 78, 65, 90 and 85 in his five subjects Physics,
Chemistry,
Biology, Mathematics and Computer respectively, write a program to
calculate
Total marks and percentage obtained by the student. Also assign a grade on
the
basis of the following criteria:
percentage 85 or more: assign S grade,
percentage 75 or more but less than 85: assign A grade,
percentage 65 or more but less than 75: assign B grade,
percentage 55 or more but less than 65: assign C grade,
percentage 50 or more but less than 55: assign D grade,
percentage less than 50: assign Fail status.
4. Write a JavaScript code to print numbers between 1 to 10.
5. Write a JavaScript code to print numbers between 10 to 1.
6. Write a JavaScript code to print all even numbers between 1 to 50.
7. Write a JavaScript code to print all odd numbers between 1 to 50.
8. Write a JavaScript code to print all even numbers between 1 to 10 and print
sum of all even numbers.
9. Write a JavaScript code to print factorial value of a number.
10.Write a JavaScript code to print the is prime number or not.
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Functions
Functions are used to perform a particular tasks or operations. We can call function many
times to reuse the code. There are mainly two advantages of functions:
1. Code reusability: We can call a function several times so it saves coding.
2. Less coding: It makes our program compact. We don’t need to write many lines of
code each time to perform a common task.
Note:
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
Syntax:
{
// code to be executed
}
Function without passing Arguments:
Output:
Example:
<script>
function msg(){
alert("hello! Welcome to my home page"); (After clicking the above button the
} alert box will appear)
</script>
<input type="button" onclick="msg()"
value="Click to call function"/>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Function Arguments:
Example:
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(3)"/>
</form>
Output:
27
Function with Return Value:
We can call function that returns a value and use it in our program.
<script>
function getInfo(){
return "hello javascript";
}
</script>
<script> Output:
document.write(getInfo()); hello javascript
</script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<html>
<body>
<script type="text/javascript">
function fact(a)
var i;
var f=1;
for(i=a;i!=0;i--)
f=f*i;
return f;
document.write("<br>",fact(4));
document.write("<br>",fact(5)); 24
120
document.write("<br>",fact(6)); 720
</script>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Output:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
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. User clicks either OK or Cancel to proceed. 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.
<html>
<head>
<script type = "text/javascript">
function getConfirmation()
{
var qry = confirm("Do you want to continue ?");
if (qry == true)
{ //or we can write: if(qry)
document.write ("User wants to continue!");
}
else {
document.write ("User does not want to continue!");
}
}
</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>
Output:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Prompt Dialog Box:
The prompt box contains a text box with OK and Cancel buttons. It returns a text string when
OK is clicked and null when Cancel is clicked.
<html>
<head>
<script type = "text/javascript">
function getValue() {
var name = prompt("Enter your name : ", "your name here");
document.write("Hi “+name+” ,Welcome to JavaScript”);
}
</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>
Output:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Write a JS code that takes two values in two variables from user (via prompt box),and
print the addition,subtraction,multiplication and division values.
<html>
<body bgcolor=lightgreen>
<script>
document.write("<br>addition= ",parseInt(a)+parseInt(b));
document.write("<br>addition= ",a-b);
</script>
</body>
</html>
Output:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Write a JS code that takes a values in a variables from user (via prompt box),and print
the factorial value of a number.
<html>
<body bgcolor="aqua">
<script >
var f=1;
while(n!=0){
f=f*n;
n--;
</script>
</body>
</html>
Output:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Write a JS code that takes a values in a variables from user (via prompt box),and print
is prime number or not.
<html><body bgcolor=lightgreen>
<script>
var i;
var temp=0;
if(n==0 || n==1)
temp=1;
for(var i=2;i<=n/2;i++)
if(n%i==0)
temp=1;
if(temp==0){
else{
</script></body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Output:
}
}
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Form Validations
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and other
fields.
<html>
<body>
<script type="text/javascript">
function data(){
var a=document.getElementById("n1").value;
var b=document.getElementById("n2").value;
var c=document.getElementById("n3").value;
var d=document.getElementById("n4").value;
if(a==""||b==""||c==""||d=="")
return false;
}
National Institute of Electronics & Inf ormation Technology
Gorakhpur
else if(b.length<10||b.length>10){
return false;
else if(isNaN(b))
return false;
else if(c.length<6)
return false;
else if(c!=d)
return false;
else {
true; }
</script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
</form>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Email validation:
There are many criteria that need to be follow to validate the email id such as:
email id must contain the @ and . character
There must be at least one character before and after the @.
There must be at least two characters after . (dot).// [email protected]
<html><body>
<script type="text/javascript">
function data(){
var e=document.getElementById("n5").value;
if(e.indexOf('@')<=0)
return false;
return false;
} else{ true;
}}
</script>
</form></body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
JavaScript Events:
The change in the state of an object is known as an Event. In html, there are various events
which represents that some activity is performed by the user or by the browser. When
JavaScript code is included in HTML, JS react over these events and allow the execution. This
process of reacting over the events is called Event Handling. Thus, js handles the HTML
events via Event Handlers.
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Form events:
change onchange When the user modifies or changes the value of a form
element
Window/Document events:
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Examples:
onclick Event:
This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.
<html>
<head>
<body>
<p>Click the following button</p>
<form>
<input type = "button" onclick = "display()" value =
"Click Me"
</form>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<html><head>
<style>
div{
height:20%;
width:100%;
background-color:red;
color:white;
</style></head><body>
<script type="text/javascript">
function over()
document.getElementById("d").innerHTML="mouse over!!";
function out()
document.getElementById("d").innerHTML="mouse out!!";
</script>
<p id="d"></p>
</div>
</body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Keyboard event
<html>
<head>
<body>
<script type="text/javascript">
function keyd()
var change=document.getElementById("input");
change.style.backgroundColor="red";
function keyup()
var change2=document.getElementById("input");
change2.style.backgroundColor="aqua";
</script>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Focus Event:
<html>
<head>
<script>
function focusevent()
document.getElementById("input1").style.background=" aqua";
</body> </html>
Load event:
<html> <head>
<script>
function msg()
</script> </head>
<body onload="msg()">
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
onchange event
<html>
<head>
<body>
<option>BMW</option>
<option>audi</option>
<option>valvo</option>
</select>
<hr>
<script type="text/javascript">
function car()
var c=document.getElementById("myselect").value;
</script>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Assignment – Day 08
1. Write a JS code that takes distance in Kilometer from user (via prompt box) and
convert it in meters, feet, inches, and centimeters.
2. WAP that displays two textboxes and four buttons (named as Addition,
Subtraction, Multiplication and Division). When user enters both numbers in
textboxes and hits a particular button it shows the result accordingly to a
particular button. (You can display the result either on textbox or inner HTML
document as per your choice.)
3. Create a form having following fields by fulfilling the criteria given below:
Name: (textbox)
Father name: (textbox)
Mother name: (textbox)
Mobile no.(textbox)
City (dropdown: at least 5 cities)
Password:
Re-enter password:
(Checkbox) I accept terms and conditions.
Submit (button)
Apply the following validations (show alert box for validation messages by using
JavaScript) before submitting the form:
Conditional Statements
A conditional statement enables you to test whether a specific condition is true or false,
and to perform different actions on the basis of the test result. There are various ways to
use conditional statement in PHP.
If
If-else
If-else-if
If Statement
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
If-else Statement
It executes one block of code if the specified condition is true and another block of code
if the condition is false.
Example <?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
If-else-if Statement
we can check multiple conditions using this statement.
Example <?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions.
Example:
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
10. case 30:
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30");
15. }
16. ?>
Output:
number is equal to 20
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Loops:
PHP loop can be used to traverse set of code for the specified number of times.
For Loop:
Syntax
for(initialization; condition; increment/decrement){
//code to be executed
}
Example:
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
Note: All three parameters are optional, but semicolon (;) is must to pass in for loop. If
we don't pass parameters, it will execute infinite.
<?php
$i = 1;
//infinite loop
for (;;) {
echo $i++;
echo "</br>";
}
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<?php Output: 1 1
for($i=1;$i<=3;$i++){ 1 2
for($j=1;$j<=3;$j++){ 1 3
2 1
echo "$i $j<br/>";
2 2
} 2 3
} 3 1
?> 3 2
3 3
While Loop
PHP while loop can be used to traverse set of code like for loop. The while loop is also
called an Entry control loop because the condition is checked before entering the loop
body.
Syntax: while(condition){
//code to be executed
}
Example
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:
<?php
$i = 'A'; A
while ($i < 'H') { B
C
echo $i; D
$i++; E
F
echo "</br>"; G
}
?>
Syntax while(true) {
//code to be executed }
National Institute of Electronics & Inf ormation Technology
Gorakhpur
do-while loop
The PHP do-while loop is guaranteed to run at least once. The do-while loop is also
named as exit control loop.
Syntax
do{
//code to be executed
}while(condition);
Example: output:
<?php 2
1 is not greater than 10.
$x = 1;
do {
echo "1 is not greater than 10.";
echo "</br>";
$x++;
} while ($x > 10);
echo $x;
?>
Break statement
PHP break statement breaks the execution of the current for, while, do-while, switch, and
for-each loop. If you use break inside inner loop, it breaks the execution of inner loop
only. The break keyword immediately ends the execution of the loop or switch structure.
Syntax
jump statement;
break;
EXAMPLE: OUTPUT:
<?php
1
for($i=1;$i<=10;$i++){ 2
echo "$i <br/>"; 3
4
if($i==5){ 5
break;
}
}
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
continue statement
The PHP continue statement is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition.
Syntax
jump-statement;
continue;
EXAMPLE:
<?php
Output:
echo "Even numbers between 1 to 20: </br>";
$i = 1;
while ($i<=20) { Even numbers
if ($i %2 == 1) { between 1 to 20:
$i++; 2
4
continue; //here it will skip rest of statements
6
} 8
echo $i; 10
10. echo "</br>"; 12
11. $i++; 14
12. } 16
18
13. ?> 20
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Day-11:
Topic to covered
PHP function
PHP Array
PHP function
PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP.
Code Reusability: PHP functions are defined only once and can be invoked many times,
like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By
the use of function, you can write the logic only once and reuse it.
Note: Function name must be start with letter and underscore only like other labels
in PHP. It can't be start with numbers or special symbols.
Type of Functions
User-Defined Functions
In-built Functions
Syntax:
function functionname(){
//code to be executed
}
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
We can pass the information in PHP function through arguments which is separated by
comma. PHP supports Call by Value (default), Call by Reference
Value passed to the function doesn't modify the actual value by default (call by value). But
we can do so by passing value as a reference. To pass value as a reference, you need to
use ampersand (&) symbol before the argument name.
<?php Output:
function adder(&$str2)
{ Hello Call By Reference
Cube of 3 is: 27
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Example:
<?php
//Adding two numbers
function add($x, $y) {
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);
In-built Functions:A function that is built into PHP application and can be accessed by
Developer . PHP has over 700 functions built in that perform different tasks. They can
categories into following category.
String Functions
Array Functions
File & Directory Functions
Date/Time & Calendar Functions
Database Functions
Mail Functions
HTTP Functions
Error Functions , etc
National Institute of Electronics & Inf ormation Technology
Gorakhpur
PHP array
An array is a complex variable that enables you to store multiple values in a single
variable; it comes in handy when you need to store and represent related information. An
array variable can best be thought of as a “container” variable, which can contain one or
more values.
Creating Array Object
<?php
// define an array
$city = array('Lucknow', 'Kanpur', 'Ghaziabad', Agra', Meerut', 'Varanasi',
'Prayagraj', 'Bareilly', 'Aligarh', 'Moradabad', 'Saharanpur',
'Gorakhpur',);
?>
Here, $city is an array variable, which contains the values Lucknow, Kanpur, Ghaziabad,
Agra, Meerut, Varanasi, Prayagraj, Bareilly, Aligarh, Moradabad, Saharanpur and
Gorakhpur
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example1.php
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Example2.php
<?php
$size[0]="Big";
$size[1]="Medium";
$size[2]="Short";
echo "Size: $size[0], $size[1] and $size[2]";
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example3.php
<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
echo "the size of array is :";
echo count($size);
?>
2nd way:
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
Example
$fruits = array('red' => 'apple', 'yellow' => 'banana', 'purple' => 'plum',
'green' => 'grape');
?>
here, $fruits is an array variable containing four key-value pairs. The => symbol is used to
indicate the association between a key and its value. To access the value banana, use the
notation $fruits['yellow'].
National Institute of Electronics & Inf ormation Technology
Gorakhpur
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example6.php
<?php
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
<?php
// define an array
$flavors = array('strawberry', 'grape', 'vanilla');
// extract values into variables
list ($flavor1, $flavor2, $flavor3) = $flavors;
// returns "strawberry"
echo $flavor1;
?>
Example9.php
<?php
// define associative array
$fruits = array('red' => 'apple', 'yellow' => 'banana', 'purple' => 'plum', 'green' =>
'grape');
// extract values into variables
extract ($fruits);
// returns "banana"
echo $yellow;
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example10.php
<?php
// define array
$students = array('Tom', 'Jill', 'Harry');
echo "<br>initial list : ";
print_r($students);
// remove an element from the beginning
array_shift($students);
echo "<br> After remove from beginning :";
print_r($students);
// remove an element from the end
array_pop($students);
echo "<br> After remove from end :" ;
print_r($students);
// add an element to the end
array_push($students, 'John');
echo "<br> After add an element to the end : " ;
print_r($students);
// add an element to the beginning
array_unshift($students, 'Ronald');
// array now looks like ('Ronald', 'Jill', 'John')
echo "<br>After add an element to the beginning : ";
print_r($students);
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
The explode() function splits a string into smaller components on the basis of a user-
specified pattern, and then returns these elements as an array. This function is particularly
handy if you need to take a string containing a list of items (for example, a comma-
delimited list) and separate each element of the list for further processing. Here’s an
example:
Example11.php
<?php
// define string
$string = 'English Latin Greek Spanish';
// split on whitespace
$languages = explode(' ', $string);
// $languages now contains ('English', 'Latin', 'Greek', 'Spanish')
print_r($languages );
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Obviously, you can also do the reverse. The implode() function creates a single string from
all the elements of an array, joining them together with a user defined separator. Revising
the previous example, you have the following:
Example12.php
<?php
// define string
$string = 'English Latin Greek Spanish';
// split on whitespace
$languages = explode(' ', $string);
// create new string
// returns "English and Latin and Greek and Spanish"
$newString = implode(" and ", $languages);
echo $newString ;
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Day-12:
Topic to covered
PHP API
PHP Global Variables
PHP API
PHP comes with a powerful and flexible file manipulation API(Application Programming
Interface), which enables developers to view and modify file attributes, read and list
directory contents, alter file permissions, retrieve file contents into a variety of native data
structures, and search for files based on specific patterns.
Syntax
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [,
resource $context ]] )
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts
at the end of the file. Creates a new file if the file doesn't exist
Creates a new file for write only. Returns FALSE and an error if file already exists
x
r+ Open a file for read/write. File pointer starts at the beginning of the file
National Institute of Electronics & Inf ormation Technology
Gorakhpur
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts
at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
The PHP fread() function is used to read data of the file. It requires two arguments: file
resource and file size.
Syntax:
string fread (resource $handle , int $length )
$handle represents file pointer that is created by fopen() function.
$length represents length of byte to be read.
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Eaxmple.php
<?php
$filename = "f://myfile.txt";
$fp = fopen($filename, "r"); //open file in read mode
Syntax
String fgets ( resource $handle [, int $length ] )
Eaxmple
<?php
$fp = fopen("f:\\myfile.txt", "r"); //open file in read mode
Echo fgets($fp);
fclose($fp);
?>
Syntax:
string fgetc ( resource $handle )
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Eaxmple
<?php
$fp = fopen("f:\\myfile.txt", "r"); //open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Syntax:
int fwrite ( resource $handle , string $string [, int $length ] )
Eaxmple6.php
<?php
$fp = fopen('f:\\myfile.txt', 'w'); //opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
fputs() function
Write to an open file using the fputs() function in PHP. It is an alias of fwrite(). The fputs()
function returns the number of bytes written on success. It returns FALSE on failure.
The fputs() function halts at the end of the file or when it reaches the specified length
whichever comes first.
Syntax:
fputs(file_pointer, string, length)
Parameters
file_pointer − A file pointer created using fopen(). Required.
string − A string to be written. Required.
length − Maximum bytes to write. Optional.
Eaxmple
<?php
$file_pointer = fopen("f:\\myfile.txt","w");
Echo fputs($file_pointer,"This is demo text!");
fclose($file_pointer);
?>
Eaxmple
<?php
//$file_pointer = fopen("f:\\myfile.txt","w");
//Echo fputs($file_pointer,"This is demo text!",4);
//fclose($file_pointer);
$fp=fopen("f:\\myfile.txt", "r");
echo fread($file_pointer, filesize("f:\\myfile.txt"));
fclose($file_pointer);
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<?php
$fp = fopen('f:\\myfile.txt', 'a'); //opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);
echo "File appended successfully";
?>
Eaxmple:
<?php
$status=unlink('f:\\myfile.txt');
if($status==true){
echo "File deleted successfully";
}else{
echo "Sorry!";
} ?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Eaxmple:
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
// invoke function
addition();
echo $z;
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Eaxmple14.php
Filename: form1.php filename:testform.php
<html> <?php
</form>
</body>
</html>
Output:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
PHP $_POST is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="post". $_POST is also widely used to pass
variables.
Filename:form1.php filename:testform.php
<html> <?php
</form>
</body>
</html>
$_REQUEST
$_REQUEST is a PHP super global variable which contains submitted form data, and all
cookie data. In other words, $_REQUEST is an array containing data from $_GET, $_POST,
and $_COOKIE.
FILENAME: form1.php Filename:testform.php
<html><body>
</form> ?>
</body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
$_SERVER
$_SERVER is a PHP super global variable which holds information about headers, paths,
and script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
echo $_SERVER['PHP_SELF'];
echo $_SERVER['SERVER_NAME'];
echo $_SERVER['HTTP_HOST'];
echo $_SERVER['HTTP_REFERER'];
echo $_SERVER['HTTP_USER_AGENT'];
echo $_SERVER['SCRIPT_NAME'];
EXAMPLE:
<html>
<body> <?php
</form> ?>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
How does the PHP file handle know some basic information like file-name, file-size, type
of the file and few attributes about the file which have selected to be uploaded? Let’s
have a look what is playing behind the scene.
$_FILES is a two dimensional associative global array of items which are being uploaded
by via HTTP POST method and holds the attributes of files such as:
ATTRIBUTE DESCRIPTION
[name] Name of file which is uploading
[size] Size of the file
[type] Type of the file (like .pdf, .zip, .jpeg…..etc)
A temporary address where the file is located before processing the upload
[tmp_name]
request
[error] Types of error occurred when the file is uploading
Eaxmple16.php
<html><body>
<?php
if(isset($_FILES['image']))
echo "<pre>";
print_r($_FILES);
echo "</pre>";
echo $file_name=$_FILES['image']['name'];
}?>
</form></body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Output:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Day-13:
Topic to covered
PHP Sessions
PHP Cookie
String function
PHP Sessions
In PHP, the session_start() function is used to create a client session and generate a
session ID. Once a session has been created, it becomes possible to register any number
of session variables; these are regular variables which can store textual or numeric
information and can be manipulated by standard PHP functions, but are unique to each
client. In a PHP script, session variables may be registered as key-value pairs in the special
$_SESSION associative array.
When you work with an application, you open it, do some changes, and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server
does not know who you are or what you do, because the HTTP address doesn't maintain
state.
Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc). By default, session variables last until
the user closes the browser.
So; Session variables hold information about one single user, and are available to all
pages in one application.
Delete session
Session_unset(); // remove all session variables
Session_destroy(); // destroy the session
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Create session
Filename:session_create.php
<?php
session_start();
$_SESSION ["favcolor"]="green";
?>
View session
Filename:session_view.php
<?php
session_start();
print_r($_SESSION);
?>
<html>
<body>
<?php
?>
</body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Sessioncounter.php
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>
Destroying a Session
Filename:session_delete.php
<?php
session_start();
session_unset();
session_destroy();
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received
at the server side.
Cookies allow web sites to store client-specific information in a file on the client system,
and retrieve this information on an as-needed basis. Cookies are typically used to bypass
the stateless nature of the HTTP protocol, by using the client’s disk as a storage area for
persistent data; however, they’re dependent on the client browser being configured to
accept cookies. PHP has included support for cookie generation and retrieval since PHP
3.x. Using PHP’s built-in functions, you can create client-side cookies, store values in them,
and delete them after a specified period has passed.
When dealing with cookies, you should be aware of some ground rules:
Because cookies are used to record information about your activities on a
particular site, they can only be read by the site that created them.
A single domain cannot set more than 20 cookies, and each cookie is limited to a
maximum size of 4KB.
A cookie usually possesses five types of attributes(Name, Expires, path, domain,
secure).
Of all the five attributes, only the first is not optional.
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Setting Cookies
In PHP, cookies are set with the setcookie() function, which accepts six arguments: the
cookie name, its value, its expiry date (in UNIX timestamp format), its path and domain,
and a Boolean flag indicating its security status. Only the first argument is required, all the
rest are optional.
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you
can access it by $_COOKIE superglobal variable.
Note:
Create cookie
Setcookie(name,value,expire,path,domain,secure,httponly)
$_COOKIE[name]
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example:
<?php
$cookie_name="user";
$cookie_value="nielit";
setcookie($cookie_name,$cookie_value,time()+(86400*30),"/");
?>
<html><body>
<?php
if(!isset($_COOKIE[$cookie_name]))
}else
echo $_COOKIE[$cookie_name];
?>
</body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<?php
?>
Delete cookie:
<?php
setcookie("user"," ",time()-(86400*30),"/");
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Example 1:
<!DOCTYPE html><html><body>
<?php
$str = "Welcome to my humble Homepage!";
echo $str."<br>";
echo addcslashes($str,'H')."<br>";
echo addcslashes($str,'A..Z')."<br>";
echo addcslashes($str,'a..z')."<br>";
echo addcslashes($str,'a..g');
?>
</body></html>
OUTPUT
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example 3:
<!DOCTYPE html><html><body>
<?php
Echo chr(52) . "<br>"; // Decimal value
Echo chr(052) . "<br>"; // Octal value
Echo chr(0x52) . "<br>"; // Hex value
?>
</body></html>
OUTPUT
Example 4:
<!DOCTYPE html><html><body>
<?php
echo $str = bin2hex("Hello World!");
echo "<br>".hex2bin($str);
?>
</body></html>
OUTPUT
National Institute of Electronics & Inf ormation Technology
Gorakhpur
MD5
The md5() function calculates the MD5 hash of a string. The md5() function uses the RSA Data Security,
Inc. MD5 Message-Digest Algorithm.
Example 5:
<!DOCTYPE html><html><body>
<?php
$str = "Hello";
echo md5($str);
?>
</body></html>
OUTPUT
Example 6:
<!DOCTYPE html><html><body>
<?php
echo "One line.\nAnother line.";
echo "<br>";
echo nl2br("One line.\nAnother line.");
?>
</body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
OUTPUT
Example 7:
<!DOCTYPE html><html><body>
<?php
$number = 9;
$str = "Beijing";
?>
</body></html>
OUTPUT
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example 8:
<!DOCTYPE html><html><body>
<?php
?>
</body>
</html>
OUTPUT
Example 9:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<!DOCTYPE html><html><body>
<?php
?>
</body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example 10:
<!DOCTYPE html><html><body>
<?php
Echo wordwrap($str,15,"<br>\n");
?>
</body></html>
OUTPUT
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Day-14:
Topic to covered
Relational Database
Relational Database
A relational database is a type of database that stores and provides access to data
points that are related to one another. Relational databases are based on Relational
Databases are useful for storing information categorically. In a relational database, each
row in the table is a record with a unique ID called the key. The columns of the table hold
attributes of the data, and each record usually has a value for each attribute, making it
easy to establish the relationships among data points.
For example : A company may have a database with the following tables:
1. Employees
2. Products
3. Customers
4. Orders
National Institute of Electronics & Inf ormation Technology
Gorakhpur
MySQL
MySQL is an open source SQL database, which is developed by a Swedish company –
MySQL AB. MySQL is pronounced as "my ess-que-ell," in contrast with SQL, pronounced
"sequel."
MySQL is supporting many different platforms including Microsoft Windows, the major
Linux distributions, UNIX, and Mac OS X.
MySQL has free and paid versions, depending on its usage (non-commercial/commercial)
and features. MySQL comes with a very fast, multi-threaded, multi-user and robust SQL
database server.
History
Development of MySQL by Michael Widenius & David Axmark beginning in 1994.
First internal release on 23rd May 1995.
Windows Version was released on the 8th January 1998 for Windows 95 and NT.
Version 3.23: beta from June 2000, production release January 2001.
Version 4.0: beta from August 2002, production release March 2003 (unions).
Version 4.1: beta from June 2004, production release October 2004.
Version 5.0: beta from March 2005, production release October 2005.
Sun Microsystems acquired MySQL AB on the 26th February 2008.
Version 5.1: production release 27th November 2008.
Features
High Performance.
High Availability.
Scalability and Flexibility Run anything.
Robust Transactional Support.
Web and Data Warehouse Strengths.
Strong Data Protection.
Comprehensive Application Development.
Management Ease.
Open Source Freedom and 24 x 7 Support.
Lowest Total Cost of Ownership.
National Institute of Electronics & Inf ormation Technology
Gorakhpur
MS SQL Server
MS SQL Server is a Relational Database Management System developed by Microsoft Inc.
Its primary query languages are −
T-SQL
ANSI SQL
History
1987 - Sybase releases SQL Server for UNIX.
1988 - Microsoft, Sybase, and Aston-Tate port SQL Server to OS/2.
1989 - Microsoft, Sybase, and Aston-Tate release SQL Server 1.0 for OS/2.
1990 - SQL Server 1.1 is released with support for Windows 3.0 clients.
Aston - Tate drops out of SQL Server development.
2000 - Microsoft releases SQL Server 2000.
2001 - Microsoft releases XML for SQL Server Web Release 1 (download).
2002 - Microsoft releases SQLXML 2.0 (renamed from XML for SQL Server).
2002 - Microsoft releases SQLXML 3.0.
2005 - Microsoft releases SQL Server 2005 on November 7th, 2005.
Features
High Performance
High Availability
Database mirroring
Database snapshots
CLR integration
Service Broker
DDL triggers
Ranking functions
Row version-based isolation levels
XML integration
TRY...CATCH
Database Mail
National Institute of Electronics & Inf ormation Technology
Gorakhpur
ORACLE
It is a very large multi-user based database management system. Oracle is a relational
database management system developed by 'Oracle Corporation'.
Oracle works to efficiently manage its resources, a database of information among the
multiple clients requesting and sending data in the network.
It is an excellent database server choice for client/server computing. Oracle supports all
major operating systems for both clients and servers, including MSDOS, NetWare,
UnixWare, OS/2 and most UNIX flavors.
History
Oracle began in 1977 and celebrating its 32 wonderful years in the industry (from 1977 to
2009).
1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development
Laboratories to undertake development work.
1979 - Version 2.0 of Oracle was released and it became first commercial relational
database and first SQL database. The company changed its name to Relational
Software Inc. (RSI).
1981 - RSI started developing tools for Oracle.
1982 - RSI was renamed to Oracle Corporation.
1983 - Oracle released version 3.0, rewritten in C language and ran on multiple
platforms.
1984 - Oracle version 4.0 was released. It contained features like concurrency control -
multi-version read consistency, etc.
1985 - Oracle version 4.0 was released. It contained features like concurrency control -
multi-version read consistency, etc.
2007 - Oracle released Oracle11g. The new version focused on better partitioning, easy
migration, etc.
Features
Concurrency
Read Consistency
Locking Mechanisms
Quiesce Database
Portability
Self-managing database
SQL*Plus
ASM
Scheduler
Resource Manager
Data Warehousing
National Institute of Electronics & Inf ormation Technology
Gorakhpur
The relational model specifies that the tuples of a relation have no specific order and that
the tuples, in turn, impose no order on the attributes. Applications access data by
specifying queries, which use operations such as select to identify tuples, project to
identify attributes, and join to combine relations. Relations can be modified using the
insert, delete, and update operators. New tuples can supply explicit values or be derived
from a query. Similarly, queries identify tuples for updating or deleting.
Tuples by definition are unique. If the tuple contains a candidate or primary key then
obviously it is unique; however, a primary key need not be defined for a row or record to
be a tuple. The definition of a tuple requires that it be unique, but does not require a
primary key to be defined. Because a tuple is unique, its attributes by definition constitute
a superkey.
What is table?
The RDBMS database uses tables to store data. A table is a collection of related data
entries and contains rows and columns to store data.
A table is the simplest example of data storage in RDBMS.
Let's see the example of student table.
What is field?
Field is a smaller entity of the table which contains specific information about every record
in the table. In the above example, the field in the student table consist of id, name, age,
course.
1suraj24B.Tech
What is column?
A column is a vertical entity in the table which contains all information associated with a
specific field in a table. For example: "name" is a column in the above table which contains
all information about student's name.
suraj
Aryan
sita
geeta
Vimal
NULL Values
The NULL value of the table specifies that the field has been left blank during record
creation. It is totally different from the value filled with zero or a field that contains space.
Data Integrity
There are the following categories of data integrity exist with each RDBMS:
Entity integrity: It specifies that there should be no duplicate rows in a table.
Domain integrity: It enforces valid entries for a given column by restricting the type, the
format, or the range of values.
Referential integrity: It specifies that rows cannot be deleted, which are used by other
records.
User-defined integrity: It enforces some specific business rules that are defined by users.
These rules are different from entity, domain or referential integrity.
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Primary key
It is the first key which is used to identify one and only one instance of an entity
uniquely. An entity can contain multiple keys as we saw in PERSON table. The key
which is most suitable from those lists become a primary key.
In the EMPLOYEE table, ID can be primary key since it is unique for each employee. In
the EMPLOYEE table, we can even select License_Number and Passport_Number as
primary key since they are also unique.
For each entity, selection of the primary key is based on requirement and developers.
Foreign key
Foreign keys are the column of the table which is used to point to the primary key of
another table.
In a company, every employee works in a specific department, and employee and
department are two different entities. So we can't store the information of the
department in the employee table. That's why we link these two tables through the
primary key of one table.
We add the primary key of the DEPARTMENT table, Department_Id as a new attribute
in the EMPLOYEE table.
Now in the EMPLOYEE table, Department_Id is the foreign key, and both the tables are
related.
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Normalization
Normalization is the process of organizing the data in the database.
Normalization is used to minimize the redundancy from a relation or set of relations.
It is also used to eliminate the undesirable characteristics like Insertion, Update and
Deletion Anomalies.
Normalization divides the larger table into the smaller table and links them using
relationship.
The normal form is used to reduce redundancy from the database table.
Types of Normal Forms
There are the four types of normal forms:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example: 1NF Relation EMPLOYEE is not in 1NF because of multi-valued attribute EMP_PHONE.
EMPLOYEE table:
The decomposition of the EMPLOYEE table into 1NF has been shown below:
.
SQL SELECT Statement
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SQL COUNT Clause
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
SQL HAVING Clause
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
National Institute of Electronics & Inf ormation Technology
Gorakhpur
DESC table_name;
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
National Institute of Electronics & Inf ormation Technology
Gorakhpur
USE database_name;
SQL COMMIT Statement
COMMIT;
SQL ROLLBACK Statement
ROLLBACK;
National Institute of Electronics & Inf ormation Technology
Gorakhpur
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
•Inner Join
•Left Join
•Right Join
•Full Outer Join
For example :
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
National Institute of Electronics & Inf ormation Technology
Gorakhpur
To open :
http://localhost/phpmyadmin/
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Day-15:
Topic to covered
Database Queries
SQL Commands
Database Queries
C:\>cd xampp
C:\xampp>cd mysql
C:\xampp\mysql>cd bin
C:\xampp\mysql\bin>mysql -u root –p
Enter password:
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| phpmyadmin |
| student |
| test |
+--------------------+
MariaDB [(none)]>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Creating table
MariaDB [(none)]> use student
Database changed
MariaDB [student]> create table employee(id int(5),fname varchar(25),lname
varchar(25),address varchar(50),city varchar(25));
Query OK, 0 rows affected (0.533 sec)
Structure of Table
MariaDB [student]> desc employee;
ALTER: MODIFY column in the table The MODIFY command is used to change the
column definition of the table.
MariaDB [student]> ALTER TABLE employee MODIFY fname varchar(50) null;
Query OK, 0 rows affected (0.134 sec)
Records: 0 Duplicates: 0 Warnings: 0
DROP: This removes records of a table as well as the structure of a table. This can’t be
rolled back/undo DROP TABLE Employee;
TRUNCATE: This empties the records only, leaves the structure for future records.
TRUNCATE TABLE employee
Assignment
Day-16:
Topic to covered
Database Connection methods
Sl.
No. Function Description
Returns the number of affected rows in the
1mysqli_affected_rows() previous MySQL operation
Turns on or off auto-committing database
2mysqli_autocommit() modifications
Changes the user of the specified database
3mysqli_change_user() connection
4mysqli_character_set_name() Returns the default character set for the
National Institute of Electronics & Inf ormation Technology
Gorakhpur
database connection
Closes a previously opened database
5mysqli_close() connection
6mysqli_commit() Commits the current transaction
Returns the error code from the last
7mysqli_connect_errno() connection error
Returns the error description from the last
8mysqli_connect_error() connection error
Opens a new connection to the MySQL
9mysqli_connect() server
Adjusts the result pointer to an arbitrary
10mysqli_data_seek() row in the result-set
11mysqli_debug() Performs debugging operations
12mysqli_dump_debug_info() Dumps debugging info into the log
Returns the last error code for the most
13mysqli_errno() recent function call
Returns a list of errors for the most recent
14mysqli_error_list() function call
Returns the last error description for the
15mysqli_error() most recent function call
Fetches all result rows as an associative
16mysqli_fetch_all() array, a numeric array, or both
Fetches a result row as an associative, a
17mysqli_fetch_array() numeric array, or both
18mysqli_fetch_assoc() Fetches a result row as an associative array
Returns meta-data for a single field in the
19mysqli_fetch_field_direct() result set, as an object
Returns the next field in the result set, as an
20mysqli_fetch_field() object
Returns an array of objects that represent
21mysqli_fetch_fields() the fields in a result set
Returns the lengths of the columns of the
22mysqli_fetch_lengths() current row in the result set
Returns the current row of a result set, as
23mysqli_fetch_object() an object
Fetches one row from a result-set and
24mysqli_fetch_row() returns it as an enumerated array
25mysqli_field_count() Returns the number of columns for the
National Institute of Electronics & Inf ormation Technology
Gorakhpur
most recent query
26mysqli_field_seek() Sets the field cursor to the given field offset
27mysqli_field_tell() Returns the position of the field cursor
28mysqli_free_result() Frees the memory associated with a result
29mysqli_get_charset() Returns a character set object
30mysqli_get_client_info() Returns the MySQL client library version
31mysqli_get_client_stats() Returns statistics about client per-process
Returns the MySQL client library version as
32mysqli_get_client_version() an integer
Returns statistics about the client
33mysqli_get_connection_stats() connection
Returns the MySQL server hostname and
34mysqli_get_host_info() the connection type
35mysqli_get_proto_info() Returns the MySQL protocol version
36mysqli_get_server_info() Returns the MySQL server version
Returns the MySQL server version as an
37mysqli_get_server_version() integer
Returns information about the most
38mysqli_info() recently executed query
Initializes MySQLi and returns a resource
39mysqli_init() for use with mysqli_real_connect()
Returns the auto-generated id used in the
40mysqli_insert_id() last query
41mysqli_kill() Asks the server to kill a MySQL thread
Checks if there are more results from a
42mysqli_more_results() multi query
Performs one or more queries on the
43mysqli_multi_query() database
Prepares the next result set from
44mysqli_next_result() mysqli_multi_query()
45mysqli_num_fields() Returns the number of fields in a result set
46mysqli_num_rows() Returns the number of rows in a result set
Sets extra connect options and affect
47mysqli_options() behavior for a connection
Pings a server connection, or tries to
48mysqli_ping() reconnect if the connection has gone down
49mysqli_prepare() Prepares an SQL statement for execution
50mysqli_query() Performs a query against the database
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Opens a new connection to the MySQL
51mysqli_real_connect() server
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE User (
id INT(6) PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table User created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example4.php
}
$sql = "INSERT INTO User(firstname, lastname, email)
VALUES ('Ramesh', 'Doe','[email protected]')";
if (mysqli_query($conn, $sql))
{
echo "New record created successfully";
}
Else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example5.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM User";
$result = mysqli_query ($conn,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " .
$row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example6.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM User WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example7.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE User SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
MySQL provides a LIMIT clause that is used to specify the number of records to return.
The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is
very useful on large tables. Returning a large number of records can impact on
performance.
Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders".
The SQL query would then look like this:
The SQL query below says "return only 10 records, start on record 16 (OFFSET 15)":
$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";
You could also use a shorter syntax to achieve the same result:
$sql = "SELECT * FROM Orders LIMIT 15, 10";
Notice that the numbers are reversed when you use a comma.
National Institute of Electronics & Inf ormation Technology
Gorakhpur
National Institute of Electronics & Inf ormation Technology
Gorakhpur
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Day-17:
Topic to covered
PHP PDO
MySQLi(Object-oriented)
PHP PDO
PDO refers to PHP Data Object, which is a PHP extension that defines a lightweight and
consistent interface for accessing a database in PHP. It is a set of PHP extensions which
provide a core PDO class and database-specific driver. PDO provides various ways to work
with objects and retrieves prepared statements that make work much easier.
Database Connection
<?php
$dbHost="localhost";
$dbName="myDB";
$dbUser="root"; //by default root is user name.
$dbPassword=""; //password is blank by default
try{
$dbConn= new PDO("mysql:host=$dbHost;dbname=$dbName",$dbUser,$dbPas
sword);
Echo "Successfully connected with myDB database";
} catch(Exception $e){
10. Echo "Connection failed" . $e->getMessage();
11. }
12. ?>
$servername="localhost";
$username= "root";
$password="";
$conn=new mysqli($servername,$username,$password);
if($conn->connect_error)
die("connection failed:".$conn->connect_error);
$conn->close();
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
// Check connection
if ($conn->connect_error) {
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
} else {
$conn->close();
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
The following example selects the id, firstname and lastname columns from the MyGuests
table and displays it on the page:
Example3.php
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
</style>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student";
// Create connection
// Check connection
National Institute of Electronics & Inf ormation Technology
Gorakhpur
if ($conn->connect_error) {
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th><th>code</th></tr>";
while($row = $result->fetch_assoc()) {
echo "</table>";
} else {
$conn->close();
?>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example4.php
<html>
<head>
<title>read-excel-file</title>
<meta charset="utf-8">
<script src="https://unpkg.com/[email protected]/bundle/read-excel-
file.min.js"></script>
<!--script src="./read-excel-file.min.js"></script-->
<style>
body
{
margin : 20px;
font-family : Arial, Helvetica;
}
#input
{
margin-top : 20px;
margin-bottom : 10px;
}
#result-table table
{
width : 100%;
border-collapse : collapse;
margin-top : 2.5em;
margin-bottom : 2.5em;
font-size : 12px;
}
#result-table table td
{
border : 1px solid black;
padding : 0.5em;
text-overflow : ellipsis;
overflow : hidden;
National Institute of Electronics & Inf ormation Technology
Gorakhpur
max-width : 10em;
white-space : nowrap;
}
#main-link
{
display : block;
font-size : 24px;
color : #0093C4;
font-family : monospace;
text-decoration : none;
}
</style>
</head>
<body>
<a id="main-link" href="https://github.com/catamphetamine/read-excel-file">
read-excel-file
</a>
<input type="file" id="input" />
<div style="font-size: 12px">
* Parsing to JSON with a strict schema is supported. <a target="_blank"
href="https://github.com/catamphetamine/read-excel-file#json" style="color: #0093C4;
text-decoration: none">Read more</a>.
</div>
<div id="result-table"></div>
<!--pre id="result"></pre -->
<script>
var input = document.getElementById('input')
input.addEventListener('change', function() {
readXlsxFile(input.files[0], { dateFormat: 'MM/DD/YY' }).then(function(data) {
// `data` is an array of rows
// each row being an array of cells.
<?php
// set file to read
$file = 'files/projects.txt';
// read file into array
$data = file($file) or die('Could not read file!');
// loop through array and print each line
foreach ($data as $line)
echo $line;
?>
Example6.php
<?php
// set file to write
$file = 'files/projects.txt';
// open file
$fh = fopen($file, 'a') or die('Could not open file!');
// write to file
fwrite($fh, '\n Hello, file!') or die('Could not write to file');
// close file
fclose($fh);
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur