0% found this document useful (0 votes)
42 views228 pages

Ilovepdf Merged

Uploaded by

ukesharwani43
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views228 pages

Ilovepdf Merged

Uploaded by

ukesharwani43
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 228

Basic Structure of HTML

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

• HTML tags are two types: 1. Container tag 2. Empty tag

• 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:

• For example: <body> tag has basically three attributes :


1. bgcolor : It is used to specify the background color of the web page.
2. text: It is used to specify the text color of the web page.
3. background: It is used to set the picture on the background of the page.
-- This will change the page’s background color as yellow and text color as red.

-- 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.

-- The text in webpage is encoded using Unicode.

-- 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

<b> To bold/ dark the text


<i> To italic the text
<u> To underline the text
<strong> It defines strong text, same as <b> tag, but with extra importance on text.
<em> It defines emphasized text, same as <i>, but with extra importance on text.
<small> It defines the smaller text than other text ( in size)
<big> It defines the bigger text than other text (in size)
<strike> or <s> It defines the strikethrough effects on text.

<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:

• rowspan: This attribute spans the cell in rows. For e.g.

-- This will span the cell in two lower rows.

-- This will span the cell in three lower rows.


• colspan: This attribute spans the cell in columns. For e.g.

-- This will span the cell in two right columns.

-- This will span the cell in three right columns.


Example: Table (rowspan, colspan) Output2: Table (rowspan, colspan)
<!doctype html>
<html>
<head><title> Rowspan and Colspan </title>
</head>
<body bgcolor="cyan" text="brown">
<h1> rowspan and colspan in table </h1>
<table width="80%" border="1">
<tr>
<th rowspan="2"> </th>
<th colspan="2"> Average</th>
<th rowspan="2"> Red Eyes</th>
</tr>
<tr>
<th> Height (in cm)</th>
<th> Weight (in kg) </th>
</tr>
<tr align="center">
<td> Males </td>
<td> 1.9 </td>
<td> 75</td>
<td> 12%</td>
</tr>
<tr align="center">
<td> Females </td>
<td> 1.7</td> Note: In first row, first cell is spanned in two
<td> 65</td>
<td> 10%</td>
</tr> rows (rowspan=2), second cell is spanned in
</table>

</body> two columns (colspan)=2, third cell is


</html>

spanned in two rows (rowspan=2).


cellspacing and cellpadding – attribute of <table> tag:

• cellspacing: This attribute is used to add space between adjacent cells.


• cellpadding: This attribute is used to add space between the edge of the cell and contents of the
cell.
Example2: Table (cellspacing, cellpadding) Output2: Table (cellspacing, cellpadding):

<!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.

• Attributes of <img> tag:

 src: It specifies the address or path of the image.

 height: It specifies the height of the image.

 width: It specifies the width of the image.

 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">

<h1> Image 1 </h1>


<img src="quote.jpg" height="200px" width="300px" alt="Inspirational
Quote 1" >

<h1> Image 2 </h1>


<img src="inspirational-bird-quote-freedom.jpg" height="200px"
width="300px" alt="Inspirational Quote 2">
</body>
</html>
Links

• 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:

Link 1 Link 2 Link 3


Multimedia Elements

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>

<source src=“geet.mp3" type="audio/mpeg">

</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

• action :- It defines the process to be performed when the form is submitted.


For example: <form action=“login_validate.php”>

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

• The <input> element is used based on the type attribute.


For example:
<input type= “text”>

-- It defines the textbox.


<input type= “password”>
--It defines the textbox for entering password. It masks the character.

<input type= “submit”>


--It defines the submit button
<input type= “reset”>

--It defines the reset button


o Code: Label, Textbox, Password textbox Output:label,textbox Password textbox
<html>
• <head>
<title> HTML Login form </title>
</head>
<body bgcolor="lightgreen" text="blue">
<h1> Login Form</h1>
<form method="post">
<label for="uid"> Username </label> <input
type="text" id="uid"> <br> <br>
<label for="pwd"> Password </label> <input
type="password" id="pwd"> <br> <br>
<input type="submit" value="Login"> <input
type="reset">
</form>
<img src="login.png"> <br>
</body>
</html>
Important point:

A login form is created which has two labels, two textboxes and two buttons.

In username textbox – id attribute is set to “uid”

In username label – for attribute is set to “uid”. Similarly for password textbox and password
label.

See its significance by clicking on label text on the output page.


<input> element – For creating radio buttons

• 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">

<input type= “number"> <input type= “week">

<input type= “email">


<input type= “file">

<input type= “image">


<input type= “hidden">

<input type= “color">


<input type= “search">

<input type= “date"> <input type= “range">

<input type= “datetime-local">


<input type= “tel">

<input type= “time"> <input type= “url">


• Attributes of <input> element

 value: It specifies the initial value of element.


 name: It specifies the name of the element.
 height: It specifies the height of the element.
 width: It specifies the width of the element.
 readonly : It specifies that <input> field is read only. It does not have value.
 disabled: It specifies that <input> field is disabled. It also does not have value.
 required: It specifies that input must be filled out before submitting the form.
 placeholder: It specifies the hint for input that are to be given.
 autocomplete: It can have value “on” or “off”. When user starts typing in the input field, it
predicts the texts that are typed earlier.
 checked : It is used with radio and checkbox. It does not have any value. It is used to select
option automatically when web page loads.
 autofocus: It specifies that the input field will be focused when web page loads.
 max: It specifies the maximum value for an input field.
 min: It specifies the minimum value for an input field.
 size: It specifies the width (in characters) of an input field.
• Code: Button
<input type="button" value="Click here">

• Output: Button

• Code: Clickable Image


<input type="image" src="home.jpg" alt="Home" height="70px" width="70px">

Note: This makes clickable image.


• Output:
• Code: Number Input
<label for="marks">
Enter Marks (0-100): </label>
<input type="number" id="marks" min=0 max=100> <input type="submit">
• Output: Number Input

• Code: Email Input


<label for="email"> Email : </label>
<input type="email" id="email"> <input type="submit">

• Output: Email Input


• Code: Color Input
<label for="color"> Select Color : </label>
<input type="color" id="color">

• Output: Color Input


• Code: Date Input
<label for="dob"> Select Your DOB : </label>
<input type="date" id="dob">
• Output: Date Input

• Code: File Input


<label for="docs"> Select file : </label> <input type="file" id="docs">

• Output: File Input


Code: Output:

<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.

• Attributes of <textarea> tag:


 rows: It defines the number of visible lines/rows in textarea.

 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>.

• Code: <button type="button"> Click Here </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.

• <select> : It specifies the drop-down box.

• <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.

 multiple: It specified that multiple options can be chosen.

 autofocus, disabled, name, required etc are also attribute of <select>.


• Attributes of <option>
 selected: It specifies preselected option when page loads.

 value, disabled etc are also attribute of <option>.

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.

 disabled: It disables the elements of 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

• <optgroup> is used to group the related options in the drop-down box.


• Attributes of <optgroup>
 label: It gives the label to the option group.
 disabled: It disables the option group.
Code: Output:
<form autocomplete="on">
<label for="courses"> Select Course </label>
<select id="courses">
<optgroup label="Long Term Courses">
<option value ="Olevel"> O level </option>
<option value ="Alevel"> A Level </option>
</optgroup>
<optgroup label ="Short Term Courses">
<option value ="CCC"> CCC </option>
<option value ="C"> Programming In C </option>
<option value ="Python"> Programming In Python
</option>
<option value="PHP"> Programming in PHP with
MySql </option>
</optgroup>
</select>
</form>
Note: Options are grouped as “Long Term
Courses” and “Short Term Courses”.
Cascading Style Sheet (CSS)

• CSS stands for Cascading Style Sheets.


• It is used to describe the look and formatting of a document written in mark-up language.
• It provides an additional feature and powerful control over HTML. It changes the style of web pages
and user interfaces.
• CSS makes the website more stylish, attractive and responsive.
• History of CSS
CSS was first proposed by Hakon Wium Lie on October 10, 1994. Its first version CSS1 was released
in 1996 by World Wide Web Consortium (W3C). Bert Bos is regarded a co-creator of CSS because
CSS1 was influenced by him.
• Version of CSS
CSS1 - published on December 17, 1996.
CSS2 - published on May 1998.
CSS3 - published on June 1999.

Syntax

• A CSS rule set contains a selector and a declaration block.


• Selector is used to select the HTML elements where the CSS property will applicable.

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.

1. To style a paragraph, use inline CSS as follows:

<p style="color:white; background-color:blue;">Paragraph 1 </p>


2. To style a heading, use inline CSS as follows:

<h1 style="color:white; background-color:green;">Heading 1 </h1>


Inline CSS output
<html>
<head>
<title> Inline CSS </title>
</head>
<body>

<h1 style="color:white; background-color:green;">I am Heading 1


</h1>

<p style="color:white; background-color:blue;">I am Paragraph 1 </p>


CSS styles are applied to only
<h1> I am Heading 2 </h1>
those elements where these are
<p> I am Paragraph 2 </h1>
written using style attribute of
</body>
</html> element.
Internal CSS

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>

background-color:green; <h1>Back End</h1>

<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:

 JavaScript is a light-weight object-oriented programming language which is used by


several websites for scripting the web pages.
 It makes the web page dynamic so that it can interact with the user.
 Easily embedded within HTML code and interpreted by browser.
 It was introduced Perform various tasks like performing arithmetic or logical
operations; apply validations, display date and time etc.
 The previous name of JavaScript was Live Script and it was joint work of Sun
Microsystem and Netscape. It was developed by Branden Eich in the year 1995 for
adding programs to the webpages in the Netscape Navigator browser.

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

The script tag has two important attributes –

 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.

<script language = "JavaScript" type = "text/JavaScript">

. . . . . . . . . . . . . . . . .

JavaScript Code . . . . . . . . . . . . . . . . .

</script>

Add javascript

Between the body tag of html:

<html>
<head>
<title>First JavaScript program</title>
</head>
<body>
<script type="text/javascript">
alert("Hello World");
</script>
</body>
</html>

Between the head tag:

<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>

External JavaScript file:

An external JavaScript file is saved by .js extension.

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>

<input type="button" value="click" onclick="msg()"/>


</form>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Javascript output
The following method / properties are used to do so:

 document.write() method– To write into the HTML output


 window.alert() method-To write into an alert box
 console.log() method – To write into the browser console
 innerHTML property – To write into an HTML element

document.write() method:

<html>

<body>

<script>

document.write("Hello! How're you?");

</script>

</body>

</html>

window.alert() method:

<html>

<body>

<script>

window.alert("Hello! How're you?");

</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("hello console ");

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:

document.getElementById(id) method of JavaScript is used to access an HTML element. The ‘id’


attribute in the method defines the HTML element. The Content / data to be displayed is specified with
innerHTML property of document.getElementById() method.

<html>

<head>

<title>innerHTML property</title></head>

<body>

<p id="greet"></p>

<script>

document.getElementById("greet").innerHTML = "Hello! How're you?";

</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.

var x = 10; Example:


var _value="sonoo";
<script>
Incorrect variable declaration: var x = 10;
var y = 20;
var 123=30; var z=x+y;
var *aa=320; document.write(z);
</script>

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;

Here, + is the arithmetic operator and = is the assignment operator.

Types of Operators: There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators

Arithmetic Operators:

Operator Description Example


+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
National Institute of Electronics & Inf ormation Technology
Gorakhpur
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9

Comparison Operators:

Operator Description Example


== Is equal to 10==10 = true
=== Identical (equal and of same type) “10”===10 =false
!= Not equal to 10!=20 = true
!== Not Identical 20!==20 = false
> Greater than 20>10 = true
>= Greater than or equal to 20>=10 = true
< Less than 20<10 = false
<= Less than or equal to 20<=10 = false

Bitwise Operators:

Operator Description Example


& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2

Logical Operators:

Operator Description Example


&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true

Assignment Operators:

Operator Description Example


= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
National Institute of Electronics & Inf ormation Technology
Gorakhpur

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:

It evaluates the content whether condition is true or false.

Syntax:

if(expression){
//content to be evaluated if condition is true
}
else{

//content to be evaluated if condition is false


}
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example:

/* Program to check a number is even or odd */


False
<script>
If
var a=20;
if(a%2==0){ Condition
document.write("a+ “is even number");
} True
else{
document.write("a+ “is odd number"); If block Else block
}
</script>

Nested If-else statement:

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

JavaScript If...else if ladder:


It is used when multipath decisions are required. The test-expressions are evaluated from
top to bottom. Whenever a true test-expression if found, statement associated with it is
executed. When all the test-expressions becomes false, then the default else statement is
executed.

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.

There are three types of loops in JavaScript.

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

Day-8: JavaScript contd.


Topics to be covered
 Functions
 Working with alert box,
 Confirm box
 Prompt boxes
 Form Validations
 JS Events.

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:

function name(parameter1, parameter2, parameter3)

{
// 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:

We can call function by passing 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

Write a js function to find the factorial value of a number.

<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

Dialog Boxes or Popup Boxes in JavaScript


JavaScript supports three types of dialog boxes that can be used to raise and alert, or to get
confirmation or take any input from the users.

Alert Dialog Box:


An alert dialog box is mostly used to give a warning message to the users. For example, if one
input field requires entering some text but the user does not provide any input, then as a part
of validation, we can give a warning message by using an alert message. An alert box can also
be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.
<html>
<head>
<script type = "text/javascript">
function warn() {
alert ("This is a warning message!");
}
</script>
</head>
<body>
<form>
<input type = "button" value = "Click Me" onclick = "warn();" />
</form>
</body>
</html>

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>

var a= prompt("enter the value of a:");

var b=prompt("enter the value of b:");

document.write("<br>addition= ",parseInt(a)+parseInt(b));

document.write("<br>addition= ",a-b);

document.write("<br>addition= ", a* 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 n=prompt("enter a number: ");

var f=1;

while(n!=0){

f=f*n;

n--;

document.write("factorial of no: ",f);

</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 n=prompt("enter a number: ");

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){

document.write("<br> prime number",n);

else{

document.write("<br> not prime",n); } }

</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=="")

alert("all fields are mendatory");

return false;

}
National Institute of Electronics & Inf ormation Technology
Gorakhpur

else if(b.length<10||b.length>10){

alert("number should be of 10 digits!please enter valid number");

return false;

else if(isNaN(b))

alert("only numbers are allowed !please enter valid number");

return false;

else if(c.length<6)

alert("password must be 6 character long!");

return false;

else if(c!=d)

alert("please enter same password");

return false;

else {

true; }

</script>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

<form onsubmit="return data()" action="submit.html"><br><br>

name: <input type="text" id="n1"><br><br>

contact: <input type="text" id="n2"><br><br>

password: <input type="password" id="n3"><br><br>

confirm password: <input type="password" id="n4"><br><br><br>

<input type="submit" value="submit" id="">

</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)

alert("invalid email id !please correct '@' place");

return false;

else if((e.charAt(e.length-4)!='.') && (e.charAt(e.length-3)!='.'))

alert("invalid email id! please correct '.' place");

return false;

} else{ true;

}}

</script>

<form onsubmit="return data()" action="submit.html"><br><br>

<h1> Email validation </h1>

email:<input type="text" id="n5"><br><br>

<input type="submit" value="submit" id="">

</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:

Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Form events:

Event Event Description


Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form
element

Window/Document events:

Event Event Description


Performed Handler

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>

<script type = "text/javascript">


function display() {
alert("Hello World")
}
</script>
</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

onmouseover and onmouseout Event:

<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>

<div onmouseover="over()" onmouseout="out()" >

<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>

<h1> keyboard event</h1>

name: <input type="text" id="input" onkeydown="keyd()" onkeyup="keyup()">

</body>

</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Focus Event:

<html>

<head>

<script>

function focusevent()

document.getElementById("input1").style.background=" aqua";

</script> </head> <body>

<h2> Enter something here</h2>

<input type="text" id="input1" onfocus="focusevent()"/>

</body> </html>

Load event:
<html> <head>

<script>

function msg()

alert(“Welcome to my home page!”)

</script> </head>

<body onload="msg()">

<p>The page is load successfully</p>

</body>

</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
onchange event

<html>

<head>

<body>

<h1>select a new car</h1>

<select id="myselect" onchange="car()">

<option>BMW</option>

<option>audi</option>

<option>valvo</option>

</select>

<hr>

<p id="car1"> </p>

<script type="text/javascript">

function car()

var c=document.getElementById("myselect").value;

document.getElementById("car1").innerHTML="my selected car : " +c;

</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:

 No fields should be blank.


 Name, Father Name, Mother Name fields should not contain less than three
characters and not more than 30 characters and should only contain alphabets.
 Mobile no. field should contain only 10 digits and should contain numeric value
only.
 Password should be at least 8 characters long.
 Both password fields should be same.
 Checkbox should be checked.
National Institute of Electronics & Inf ormation Technology
Gorakhpur
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-10: control statement

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.

Important points to be noticed about switch case:


1. The default is an optional statement. Even it is not important, that default must
always be the last statement.
2. Each case can have a break statement, which is used to terminate the sequence of
statement.
3. The break statement is optional to use in switch. If break is not used, all the
statements will execute after finding matched case value.
4. PHP allows you to use number, character, string, as well as functions in switch
expression.
5. You can use semicolon (;) instead of colon (:). It will not generate any error.

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

Nested For Loop

<?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

For Each Loop


PHP for each loop is used to traverse array elements.

Syntax: foreach( $array as $var ){


//code to be executed
}
?>
Example:
Output:
<?php
$season=array("summer","winter","spring","autumn"); Season is: summer
Season is: winter
foreach( $season as $arr ){ Season is: spring
echo "Season is: $arr<br />"; Season is: autumn
}
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

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++;
}
?>

Example printing alphabets using while loop.

Output:
<?php
$i = 'A'; A
while ($i < 'H') { B
C
echo $i; D
$i++; E
F
echo "</br>"; G
}
?>

Infinite While Loop


If we pass TRUE in while loop, it will be an infinite loop.

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;
?>

Controlling Loop Iteration with break and continue

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.

Advantage of PHP Functions

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

PHP User-defined Functions

Syntax:
function functionname(){
//code to be executed
}

Example1 Function without Arguments Output:

<?php Hello PHP Function

function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function

?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by
comma. PHP supports Call by Value (default), Call by Reference

Example: Call by Value


Output:
<?php
Hello Sonoo
function sayHello($name){
Hello Vimal
echo "Hello $name<br/>"; Hello John
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>

Example: 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

$str2 .= 'Call By Reference';


}
$str = 'Hello ';
adder($str);
echo $str;
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

PHP Function: Returning Value Output:

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);

//Subtracting two numbers


function sub($x, $y) {
$diff = $x - $y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);
?>

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

To define an array object, array ( ) function is used.


For example,

<?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

There are 3 types of array in PHP.


 Indexed Array
 Associative Array
 Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by
default.
National Institute of Electronics & Inf ormation Technology
Gorakhpur

There are two ways to define indexed array:


1st way:
$season=array("summer","winter","spring","autumn");

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);
?>

PHP Associative array


There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

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

Note: This type of array is sometimes referred to as a hash or associative array.


To look inside structure, key and data of array , print_r( )function is used.
An alternative way to define an array is by specifying values for each element using index
notation, like this:
Example4.php
<?php
// define an array
$city[0]='Lucknow';
$city[1]='Kanpur';
$city[2]='Ghaziabad';
$city[3]='Agra';
$city[4]='Meerut';
$city[5]='Varanasi';
// to print city array
print_r($city);

// define an associative array


$fruits['red'] = 'apple';
$fruits['yellow'] = 'banana';
$fruits['purple'] = 'plum';
$fruits['green'] = 'grape';
// to print fruits array
print_r($fruits);
?>

Processing Arrays with Loops


Example5.php
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
} ?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular
data in an array. PHP multidimensional array can be represented in the form of matrix
which is represented by row * column.

$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

PHP Multidimensional Array Example


Let's see a simple example of PHP multidimensional array to display following tabular
data. In this example, we are displaying 3 rows and 3 columns.

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)
);

for ($row = 0; $row < 3; $row++) {


for ($col = 0; $col < 3; $col++) {
echo $emp[$row][$col]." ";
}
echo "<br/>";
}
?>

Let’s use some common array function.

array_keys() and array_values() functions


These functions come in handy to get a list of all the keys and values within the array. The
following example illustrates this:
Example7.php
<?php
// define an array
$menu = array('breakfast' => 'Butter & bread', 'lunch' => 'Chelly Paneer', 'dinner' =>
'Onion Paratha');
$result = array_keys($menu);
print_r($result );
echo"<br>";
$result = array_values($menu); // returns the array
print_r($result );
?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

list() and extract() functions


You can convert array elements into regular PHP variables with
the list() and extract() functions. The list() function assigns array elements to variables and
the extract() function iterates through a hash, converting the key-value pairs into
corresponding variable-value pairs.

Using list() function


Example8.php

<?php
// define an array
$flavors = array('strawberry', 'grape', 'vanilla');
// extract values into variables
list ($flavor1, $flavor2, $flavor3) = $flavors;
// returns "strawberry"
echo $flavor1;
?>

Using extract () function


The extract() function imports variables into the current symbol table from an array.This
function basically creates variables from an associative array.

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

array_push(), array_pop(),array_shift() and array_unshift()


functions
You can add an element to the end of an existing array with the array_push() function,
and remove an element from the end with the interestingly named array_pop() function. If
you need to pop an element off the top of the array, you can use the array_shift()
function, while the array_unshift() function takes care of adding elements to the beginning
of the array.

The following example demonstrates all these functions:

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

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

The implode() function

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.

PHP Open File


PHP fopen() function is used to open file or URL and returns resource. The fopen()
function accepts two arguments: $filename and $mode. The $filename represents the file
to be opended and $mode represents the file mode for example read-only, read-write,
write-only etc.

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

Reading Data from a File

PHP Read File


PHP provides various functions to read data from file. There are different functions that
allow you to read all file data, read data line by line and read data character by character.
The available PHP file read functions are given below.
 fread()
 fgets()
 fgetc()

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

$contents = fread($fp, filesize($filename)); //read file

echo "<pre>$contents</pre>"; //printing data of file


fclose($fp);//close file
?>

PHP Read File - fgets()


The PHP fgets() function is used to read single line from the file.

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);
?>

PHP Read File - fgetc()


The PHP fgetc() function is used to read single character from the file. To get all data
using fgetc() function, use !feof() function inside the while loop.

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);
?>

PHP Write File


PHP fwrite() and fputs() functions are used to write data into file. To write data into file,
you need to use w, r+, w+, x, x+, c or c+ mode.

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

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);

echo "File written successfully";


?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

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 Append to File


You can append data into file by using a or a+ mode in fopen() function. Let's see a
simple example that appends data into data.txt file.
Let's see the data of file first.

PHP Append to File - fwrite()


The PHP fwrite() function is used to write and append data into file.
Eaxmple

<?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";
?>

PHP Delete File


In PHP, we can delete any file using unlink() function. The unlink() function accepts one
argument only: file name. It is similar to UNIX C unlink() function.
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.
Syntax:
bool unlink ( string $filename [, resource $context ] )

$filename represents the name of the file to be deleted.

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

PHP Global Variables


Several predefined variables in PHP are "superglobals", which means that they are always
accessible, regardless of scope - and you can access them from any function, class or file
without having to do anything special.

The PHP global variables are:


$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_COOKIE
$_SESSION

PHP $GLOBALS Variables


$GLOBALS is a PHP super global variable which is used to access global variables from
anywhere in the PHP script

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

PHP $_GET Variables


PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get".
$_GET can also collect data sent in the URL.
Assume we have an HTML page that contains a hyperlink with parameters:

Eaxmple14.php
Filename: form1.php filename:testform.php

<html> <?php

<body> echo "<pre>";

<form action="testform.php" method="get"> print_r($_GET);

name: <input type="text" name="fname"><br><br> echo "</pre>";

age: <input type="text" name="age"><br><br> ?>

<input type="submit" name="save">

</form>

</body>

</html>

Output:
National Institute of Electronics & Inf ormation Technology
Gorakhpur

PHP $_POST Variables

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

<body> echo "<pre>";

<form action="testform.php" method="post"> print_r($_POST);

name: <input type="text" name="fname"><br><br> echo "</pre>";

age: <input type="text" name="age"><br><br> ?>

<input type="submit" name="save">

</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 action="testform.php" method="post"> <?php

name: <input type="text" name="fname"><br><br> echo "<pre>";

age: <input type="text" name="age"><br><br> print_r($_REQUEST);

<input type="submit" name="save"> echo "</pre>";

</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:

FILENAME: FORM1.PHP FILENAME: TESTFORM.PHP

<html>

<body> <?php

<form action="testform.php" method="post"> echo "<pre>";

name: <input type="text" name="fname"><br><br> print_r($_SERVER);

age: <input type="text" name="age"><br><br> echo "</pre>";

<input type="submit" name="save"> echo $_SERVER['PHP_SELF'];

</form> ?>

</body>

</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

PHP $_FILE variable

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 action="" method="post" enctype="multipart/form-data">

photo:<input type="file" name="image"><br><br>

<input type="submit" name="save">

</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.

Three steps to set and get SESSION values:


 Session_start();
 $_SESSION[name]=value; // set session name and value
 echo $_SESSION[name]; // get session value

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";

echo "session variable is set.";

?>

View session
Filename:session_view.php

<?php

session_start();

print_r($_SESSION);

?>

<html>

<body>

<?php

echo "favorite color:".$_SESSION ["favcolor"];

?>

</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();

echo "session is 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.

In short, cookie can be created, sent and received at server end.

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)

View cookies value

$_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]))

echo "cookies is not set";

}else

echo $_COOKIE[$cookie_name];

?>

</body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

View cookie value another file


Filename: view-cookie.php

<?php

echo "cookie value:".$_COOKIE["user"];

?>

Delete cookie:

<?php

echo "cookie value:".$_COOKIE["user"];

setcookie("user"," ",time()-(86400*30),"/");

?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Let’s use some common String function.


Add a backslash in front of the character "W":

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";

printf("There are %u million bicycles in %s.",$number,$str);

?>

</body></html>

OUTPUT
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example 8:

<!DOCTYPE html><html><body>

<?php

$str = "Hello World!";

echo $str . "<br>";

echo rtrim($str,"World!"). "<br>";

echo ltrim($str,"Hello"). "<br>";

echo trim($str,"Hed!"). "<br>";

echo trim($str). "<br>";

?>

</body>

</html>

OUTPUT

Example 9:
National Institute of Electronics & Inf ormation Technology
Gorakhpur
<!DOCTYPE html><html><body>

<?php

echo $str="Hello world!";

echo "<br>". str_word_count($str);

echo "<br>". ucfirst($str);

echo "<br>". lcfirst($str);

echo "<br>". ucwords($str);

echo "<br>". strtolower($str);

echo "<br>". strtoupper($str);

echo "<br>". strlen($str);

echo "<br>". strrev($str);

echo "<br>". substr($str,6);

?>

</body></html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Example 10:

<!DOCTYPE html><html><body>

<?php

$str = "An example of a long word is: Supercalifragulistic";

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.

 RDBMS stands for Relational Database Management System.


 RDBMS is the basis for SQL, and for all modern database systems such as MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
 The data in RDBMS is stored in database objects called tables. A table is a
collection of related data entries and it consists of columns and rows.

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

Benefits of Relational Databases


The simple yet powerful relational model is used by organizations of all types and sizes
for a broad variety of information needs. Relational databases are used to track
inventories, process ecommerce transactions, manage huge amounts of mission-critical
customer information, and much more. A relational database can be considered for any
information need in which data points relate to each other and must be managed in a
secure, rules-based, consistent way.

Stored Procedures and Relational Databases


Data access involves many repetitive actions. For example, a simple query to get
information from a data table may need to be repeated hundreds or thousands of times
to produce the desired result. These data access functions require some type of code to
access the database. Application developers don’t want to write new code for these
functions in each new application. Luckily, relational databases allow stored procedures,
National Institute of Electronics & Inf ormation Technology
Gorakhpur
which are blocks of code that can be accessed with a simple application call.
For example, a single stored procedure can provide consistent record tagging for users of
multiple applications. Stored procedures can also help developers ensure that certain data
functions in the application are implemented in a specific way.

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

Tables Records and Fields


A relation is defined as a set of tuples that have the same attributes. A tuple usually
represents an object and information about that object. Objects are typically physical
objects or concepts. A relation is usually described as a table, which is organized into rows
and columns. All the data referenced by an attribute are in the same domain and conform
to the same constraints.

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.

ID Name AGE COURSE


1 Suraj 24 B.Tech
2 aryan 20 C.A
3 sita 21 BCA
4 geeta 22 MCA
5 Vimal 26 BSC
National Institute of Electronics & Inf ormation Technology
Gorakhpur

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.

What is row or record?


A row of a table is also called record. It contains the specific information of each individual
entry in the table. It is a horizontal entity in the table. For example: The above table
contains 5 records.
Let's see one record/row in the table.

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

Normal Form Description


1NF A relation is in 1NF if it contains an atomic value.

A relation will be in 2NF if it is in 1NF and all non-key attributes


2NF are fully functional dependent on the primary key.

A relation will be in 3NF if it is in 2NF and no transition


3NF dependency exists.

A relation will be in 4NF if it is in Boyce Codd normal form and has


4NF no multi-valued dependency.

A relation is in 5NF if it is in 4NF and not contains any join


5NF dependency and joining should be lossless.

Example: 1NF Relation EMPLOYEE is not in 1NF because of multi-valued attribute EMP_PHONE.

EMPLOYEE table:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE


7272826385,
14 John UP
9064738238
20 Harry 8574783832 Bihar
7390372389,
12 Sam Punjab
8589830302

The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE


14 John 7272826385 UP
14 John 9064738238 UP
20 Harry 8574783832 Bihar
12 Sam 7390372389 Punjab
12 Sam 8589830302 Punjab
National Institute of Electronics & Inf ormation Technology
Gorakhpur

SQL and SQL Queries


SQL is followed by a unique set of rules and guidelines called Syntax. All the SQL
statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER,
DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;).
The most important point to be noted here is that SQL is case insensitive, which means
SELECT and select have same meaning in SQL statements. Whereas, MySQL makes
difference in table names. So, if you are working with MySQL, then you need to give table
names as they exist in the database.

Various Syntax in SQL

.
SQL SELECT Statement

SELECT column1, column2....columnN


FROM table_name;
SQL DISTINCT Clause

SELECT DISTINCT column1, column2....columnN


FROM table_name;
SQL WHERE Clause

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION;
SQL AND/OR Clause

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
SQL IN Clause

SELECT column1, column2....columnN


FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SQL BETWEEN Clause
National Institute of Electronics & Inf ormation Technology
Gorakhpur
SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
SQL LIKE Clause

SELECT column1, column2....columnN


FROM table_name
WHERE column_name LIKE { PATTERN };
SQL ORDER BY Clause

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
SQL GROUP BY Clause

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

SQL CREATE TABLE Statement

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);

SQL DROP TABLE Statement

DROP TABLE table_name;

SQL CREATE INDEX Statement

CREATE UNIQUE INDEX index_name


ON table_name ( column1, column2,...columnN);

SQL DROP INDEX Statement

ALTER TABLE table_name


DROP INDEX index_name;
National Institute of Electronics & Inf ormation Technology
Gorakhpur

SQL DESC Statement

DESC table_name;

SQL TRUNCATE TABLE Statement

TRUNCATE TABLE table_name;

SQL ALTER TABLE Statement

ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};


SQL ALTER TABLE Statement (Rename)

ALTER TABLE table_name RENAME TO new_table_name;

SQL INSERT INTO Statement

INSERT INTO table_name( column1, column2....columnN)


VALUES ( value1, value2....valueN);

SQL UPDATE Statement

UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
National Institute of Electronics & Inf ormation Technology
Gorakhpur

SQL DELETE Statement

DELETE FROM table_name


WHERE {CONDITION};

SQL CREATE DATABASE Statement

CREATE DATABASE database_name;

SQL DROP DATABASE Statement

DROP DATABASE database_name;

SQL USE Statement

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

MySQL GUI interface using XAMP


phpMyAdmin
phpMyAdmin is a web-based tool to manage MySQL databases and tables, input records,
and execute queries. It is written entirely in PHP, is licensed under the GNU GPL, and is
currently available in 47(more) languages.
It showed you how a database structures data into tables, records, and fields;
how it identifies records with primary keys; and how it connects records in different tables
with each other through foreign keys.

To open :

http://localhost/phpmyadmin/
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Day-15:
Topic to covered
 Database Queries

SQL Commands

SQL commands are mainly categorized into five categories as:

1. DDL – Data Definition Language


2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Database Queries

Go to c->xampp->mysql->bin->type the cmd on navigation bar


type mysql –u root –p press enter
Ask for password then press enter again acommand prompt shows
Mariadb[(none)]>

C:\>cd xampp

C:\xampp>cd mysql

C:\xampp\mysql>cd bin

C:\xampp\mysql\bin>mysql -u root –p

Enter password:

Welcome to the MariaDB monitor. Commands end with ; or \g.


Your MariaDB connection id is 16
Server version: 10.4.32-MariaDB mariadb.org binary distribution
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> show databases;

+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| phpmyadmin |
| student |
| test |
+--------------------+

6 rows in set (0.001 sec)

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: Used to modify or change structures in the table.


MariaDB [student]> ALTER TABLE employee
-> ADD email varchar(55);
Query OK, 0 rows affected (0.181 sec)
Records: 0 Duplicates: 0 Warnings: 0

ALTER: Add multiple columns in the table


MariaDB [student]> ALTER TABLE employee ADD category varchar(100) not
null AFTER fname,ADD salary int(100) not null AFTER city;

Query OK, 0 rows affected (0.144 sec)


National Institute of Electronics & Inf ormation Technology
Gorakhpur

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: Column in table


MariaDB [student]> ALTER TABLE employee
-> DROP COLUMN address;

Query OK, 0 rows affected (0.187 sec)


Records: 0 Duplicates: 0 Warnings: 0

RENAME: column in Table


MariaDB [student]> ALTER TABLE employee CHANGE COLUMN lname title varchar(20) not null;

Query OK, 0 rows affected (0.836 sec)

Records: 0 Duplicates: 0 Warnings: 0


National Institute of Electronics & Inf ormation Technology
Gorakhpur

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

INSERT: Used to insert new rows into the table

MariaDB [student]> INSERT into employee


values(1,'sonoo','gen','gkp',40000,'[email protected]'),(2,'gita','obc','lko',50000,'[email protected]
m');
Query OK, 2 rows affected (0.347 sec)
Records: 2 Duplicates: 0 Warnings: 0
Show table data
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Delete all rows : DELETE from employee;

Delete particular row : DELETE FROM Employees WHERE id=1;

UPDATE: Used to update existing records in a table.


UPDATE employee SET col1 = new_col WHERE condition;

MariaDB [student]> UPDATE employee SET category='gen' WHERE city='lko';


Query OK, 1 row affected (0.151 sec)
Rows matched: 1 Changed: 1 Warnings: 0
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Assignment

Create following Emp Ddatabase table:

 employee (emp_id, emp_name, emp_fname, emp_dob, emp_city, emp_mobile,


emp_gender, emp_salary, dept_id)
 salary (emp_id, salary_month, salary_year, absent, leave, total_salary)
 department (dept_id, dept_name )
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Day-16:
Topic to covered
 Database Connection methods

Database Connection methods


PHP Connect to MySQL
PHP 5 and later can work with a MySQL database using:
1. MySQLi extension (the "i" stands for improved)
2. PDO (PHP Data Objects)

MySQLi and PDO advantages:


 PDO will work on 12 different database systems, where as MySQLi will only work
with MySQL databases.
 So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries.
With MySQLi, you will need to rewrite the entire code - queries included.
 Both are object-oriented, but MySQLi also offers a procedural API.
 Both support Prepared Statements. Prepared Statements protect from SQL
injection, and are very important for web application security.

MySQLi Methods in PHP

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

Open a Connection Using MySQLi

Example1.php program for checking connection of


server(localhost/xampp)

<?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";

?>

Output : Connection is successfull


National Institute of Electronics & Inf ormation Technology
Gorakhpur

Create a MySQL Database Using MySQLi

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

Create a MySQL Table Using MySQLi

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

Insert Data Into MySQL Using MySQLi

Example4.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 = "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

Select Data From MySQLi

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

Delete Data From a MySQL Table Using MySQLi

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

Update Data in MySQL Table Using MySQLi

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

Limit Data Selections From a MySQL Database

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:

$sql = "SELECT * FROM Orders LIMIT 30";


When the SQL query above is run, it will return the first 30 records.
What if we want to select records 16 - 25 (inclusive)?
Mysql also provides a way to handle this: by using OFFSET.

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.

Databases supported by PDO


1. MySQL
2. PostgreSQL
3. Oracle
4. Firebird
5. MS SQL Server
6. Sybase
7. Informix
8. IBM
9. FreeTDS
10. SQLite
11. Cubrid
12. 4D
National Institute of Electronics & Inf ormation Technology
Gorakhpur
Comparison between PDO and MySQLi

Features PDO MySQLi

DB Support 12 different drivers MySQL only

Connection Easy Easy

API OOP OOP + Procedure

Performance Fast Fast

Named Parameter Yes No

Object mapping Yes Yes

Stored Procedure Yes Yes

Client-Side Prepared Yes No


Statements

Security More secure than Secure but not more


MySQLi. than PDO.

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. ?>

Output: Successfully connected with myDB database


National Institute of Electronics & Inf ormation Technology
Gorakhpur

Handling Connection Error


<?php
$dbHost="localhost";
$dbName="myDB";
$dbUser="rroot";
$dbPassword="";
try{
$dbConn= new PDO("mysql:host=$dbHost;dbname=$dbName",$dbUser,$dbPassword);

//Set the PDO error mode to exception.


10. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
11. Echo "Successfully connected with myDB database";
12. } catch(Exception $e){
13. Echo "Connection failed" . $e->getMessage();
14. }
15. ?>

Output: Connection failedSQLSTATE[HY000] [1045] Access denied for user


'rroot'@'localhost' (using password: NO)
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Interacting PHP with MySQL database


Select Data With MySQLi(Object-oriented)

Open a Connection Using MySQLi(object-oriented)


<?php

$servername="localhost";

$username= "root";

$password="";

$conn=new mysqli($servername,$username,$password);

if($conn->connect_error)

die("connection failed:".$conn->connect_error);

echo "connected successfully";

$conn->close();

?>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Select Data From MySQLi(object oriented)

<?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 = "SELECT id, firstname, lastname FROM user";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

// output data of each row

while($row = $result->fetch_assoc()) {

echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";

} else {

echo "0 results";

$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 {

border: 1px solid black;

</style>

</head>

<body>

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "student";

// Create connection

$conn = new mysqli($servername, $username, $password,


$dbname);

// Check connection
National Institute of Electronics & Inf ormation Technology
Gorakhpur

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

$sql = "SELECT id, name, code FROM emp";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

echo "<table><tr><th>ID</th><th>Name</th><th>code</th></tr>";

// output data of each row

while($row = $result->fetch_assoc()) {

echo "<tr><td>" . $row["id"]. "</td><td>" . $row["name"]. "


</td><td>" . $row["code"]. "</td></tr>";

echo "</table>";

} else {

echo "0 results";

$conn->close();

?>

</body>

</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Interacting PHP with Excel file database

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.

//document.getElementById('result').innerText = JSON.stringify(data, null,


2)

// Applying `innerHTML` hangs the browser when there're a lot of


rows/columns.
// For example, for a file having 2000 rows and 20 columns on a modern
National Institute of Electronics & Inf ormation Technology
Gorakhpur
// mid-tier CPU it parses the file (using a "schema") for 3
seconds
// (blocking) with 100% single CPU core usage.
// Then applying `innerHTML` hangs the browser.
r=0;
c=0; document.getElementById('result-table').innerHTML =
'<form name="form1" action="#" method="post" ><table>' +
'<tbody>' +
data.map(function (row) {
r++;
return '<tr>' +
row.map(function (cell) {
c++;
return '<td><input type=text readonly name="c'+c+'r'+r+'" value="'
+
(cell === null ? '' : cell) +
'" ></td>'
}).join('') +
'</tr>'
}).join('') +
'</tbody>' +
'</table><input type="submit" ></form>'
}, function (error) {
console.error(error)
alert("Error while parsing Excel file. See console output for the error stack
trace.")
})
})
</script>
</body>
</html>
National Institute of Electronics & Inf ormation Technology
Gorakhpur

Interacting PHP with text file database


Reading Data from a File
Example5.php

<?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;
?>

Writing Data to a File

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

You might also like