0% found this document useful (0 votes)
14 views36 pages

HTML5 Overview and Key Features

Uploaded by

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

HTML5 Overview and Key Features

Uploaded by

kal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

21PCS10 WEB TECHNOLOGY AND DESIGN

UNIT 1
HTML5 | Introduction

1.2 Heading
1.3 Linking
1.4 Images
1.5 Lists
1.6 Tables
1.7 internal
1.8 linking 1.9 Form
HTML5 is the fifth version of Hypertext Markup Language (HTML), a standard language used to
structure webpages. It defines how content on a webpage should be structured and displayed. Here are
some key points of HTML5 • Multimedia Support: Embeds audio and video without plugins.
• New Form Controls: Includes input types like date and email.
• Web Storage: Stores data offline for better performance.
• Semantic Elements: Uses tags like <header> and <footer> for better structure.
• Improved Performance: Faster and more efficient, especially on mobile.
Here is a simple HTML5 example <html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple HTML Page</title>

</head>
<body>

<header>
<h1>Hello, World!</h1>
</header>

<main>
<p>This is a simple HTML5 page.</p>
</main>

<footer>
<p>@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved</p>
</footer>

</body>
</html>
• It defines a simple HTML5 page with DOCTYPE, <html>, <head>, and <body> tags.
• Includes a character set (UTF-8) and viewport settings for mobile responsiveness.
• Contains a header, main content, and footer with basic text content.
Evolution of HTML
HTML has gone through several changes over the years to keep up with the growing needs of web
development. These changes have helped improve website design, functionality, and accessibility.
Here's an overview of how it has evolved.
Early Web Browser Development:
• In the early days of the web, major browser creators like Microsoft Internet Explorer and
Mosaic Netscape introduced browser-specific elements to improve the appearance of web pages
for their browsers.
• This led to the creation of distinct versions of websites tailored for Internet Explorer and
Netscape by the late 1990s.
HTML 3.2 (1996):
• The World Wide Web Consortium (W3C) recommended the creation of HTML 3.2 in 1996.
• This standard included commonly used HTML elements and introduced presentational
extensions, like the <center> and <font> elements, which were developed during the browser
rivalry between Internet Explorer and Netscape.
HTML 4.0 (1998) and HTML 4.01 (1999):
• HTML 4.0, released in 1998, and its update HTML 4.01 in 1999, focused on separating content
structure from presentation.
• These versions emphasized improving accessibility and moving presentation elements to the
newly introduced Cascading Style Sheets (CSS) standard.
New Added Elements in HTML 5
HTML5 introduced several new elements that help structure a webpage better and make it more
interactive. These elements not only improve the design but also make the code more readable and
accessible. Here are some key elements of HTML5:
• <article>: The <article> tag is used to represent an article. More specifically, the content within
the <article> tag is independent from the other content of the site (even though it can be related).
• <aside>: The <aside> tag is used to describe the main object of the web page in a shorter way like
a highlighter. It basically identifies the content that is related to the primary content of the web
page but does not constitute the main intent of the primary page. The <aside> tag contains mainly
author information, links, related content and so on.
• <figcaption>: The <figcaption> tag in HTML is used to set a caption to the figure element in a
document.
• <figure>: The <figure> tag in HTML is used to add self-contained content like illustrations,
diagrams, photos or codes listing in a document. It is related to main flow, but it can be used in
any position of a document and the figure goes with the flow of the document and if it is removed
it should not affect the flow of the document.
• <header>: It contains the section heading as well as other content, such as a navigation links, table
of contents, etc.
• <footer>: The <footer> tag in HTML is used to define a footer of HTML document. This section
contains the footer information (author information, copyright information, carriers etc.). The
footer tag is used within body tag. The <footer> tag is new in the HTML 5. The footer elements
require a start tag as well as an end tag.
• <main>: Delineates the main content of the body of a document or web app.
• <mark>: The <mark> tag in HTML is used to define the marked text. It is used to highlight the part
of the text in the paragraph.
• <nav>: The <nav> tag is used to declaring the navigational section in HTML documents. Websites
typically have sections dedicated to navigational links, which enables user to navigate the site.
These links can be placed inside a nav tag.
• <section>: It demarcates a thematic grouping of content.
• <details>: The <details> tag is used for the content/information which is initially hidden but could
be displayed if the user wishes to see it. This tag is used to create interactive widget which user
can open or close it. The content of details tag is visible when open the set attributes.
• <summary>: The <summary> tag in HTML is used to define a summary for the <details> element.
The <summary> element is used along with the <details> element and provides a summary
visible to the user. When the summary is clicked by the user, the content placed inside the
<details> element becomes visible which was previously hidden. The <summary> tag was added
in HTML 5. The <summary> tag requires both starting and ending tag.
• <time>: The <time> tag is used to display the human-readable data/time. It can also be used to
encode dates and times in a machine-readable form. The main advantage for users is that they can
offer to add birthday reminders or scheduled events in their calendars and search engines can
produce smarter search results.
• <bdi>: The <bdi> tag refers to the Bi-Directional Isolation. It differentiates a text from other text
that may be formatted in different direction. This tag is used when a user generated text with an
unknown direction.
• <wbr>: The <wbr> tag in HTML stands for word break opportunity and is used to define the
position within the text which is treated as a line break by the browser. It is mostly used when the
used word is too long and there are chances that the browser may break lines at the wrong place
for fitting the text.
• <datalist>: The <datalist> tag is used to provide autocomplete feature in the HTML files. It can be
used with input tag, so that users can easily fill the data in the forms using select the data.
• <keygen>: The <keygen> tag in HTML is used to specify a key-pair generator field in a form. The
purpose of <keygen> element is to provide a secure way to authenticate users. When a form is
submitted then two keys are generated, private key and public key. The private key stored locally,
and the public key is sent to the server. The public key is used to generate client certificate to
authenticate user in future.
• <output>: The <output> tag in HTML is used to represent the result of a calculation performed by
the client-side script such as JavaScript.
• <progress>: It is used to represent the progress of a task. It also defines how much work is done
and how much is left to download a task. It is not used to represent the disk space or relevant
query.
• <svg>: It is the Scalable Vector Graphics.
• <canvas>: The <canvas> tag in HTML is used to draw graphics on web page using JavaScript. It
can be used to draw paths, boxes, texts, gradient and adding images. By default, it does not
contain border and text.
• <audio>: It defines the music or audio content.
• <embed>: Defines containers for external applications (usually a video player).
• <source>: It defines the sources for <video> and <audio>.
• <track>: It defines the tracks for <video> and <audio>.
• <video>: It defines the video content.
HTML5
Features ofintroduces
HTML5 several new elements and attributes to improve web
development: • Semantic Elements:
o New tags like <article>, <aside>, <nav>, <header>, <footer>, and <section> provide

meaning and structure to the content, improving both accessibility and SEO.
• Multimedia Support:

o Native support for <audio> and <video> tags removes the need for third-party plugins
like Flash.
• Canvas API:
o Allows drawing graphics, animations, and games directly in the browser using
JavaScript.
• Geoloci ition API:

o Provides access to the user's geographical location (with permission), enabling location-
based services.
• Web St orage (localStorage and sessionStorage):

o Local storage (localStorage) and session storage (sessionStorage) provide client-side


data storage, improving performance and enabling offline functionality.
• Web W orkers:

o Allows background processing of JavaScript, improving performance by preventing


blocking of the main thread.
• Form E Enhancements:

o New input types (e.g., date, email, number) and form validation make forms easier and
more efficient to create.
• Drag ai id Drop API:

o Allows users to drag and drop elements within a web page or between applications,
enhancing interactivity.
• SVG In tegration:

o Improved support for Scalable Vector Graphics (SVG), allowing for resolution-
independent vector graphics to be embedded directly into HTML.
• WebSo cket API:
o Enables real-time, bidirectional communication bet.
Deprecated 1 Elements in HTML5
HTML5 > removed several outdated elements, replacing them with newer, more flexible solutions:
has

Removed ] Elements Use Instead Elements

<acrony
> <abbr>
m

<applet> <object>

<basefont> CSS

<big> CSS

<center> CSS
Removed Elements Use Instead Elements

<dir> <ul>

<font> CSS

<frame> None

<frameset> None

<noframes> None

<isindex> None

<strike> CSS, <s> or <del>

<tt> CSS

HTML5 Advantages
• Multimedia Support: Native audio and video tags for easier media embedding.
• Better Performance: Faster loading times with fewer dependencies.
• Cross-Platform: Works across all major browsers and mobile devices.
• Geolocation: Access users’ location for location-based features.
• Offline Capability: Works offline with Web Storage and AppCache.
• Simplified Code: New semantic tags for cleaner, more readable code.
• Mobile-Friendly: Optimized for a smoother mobile experience.
HTML5 Disadvantages
• Browser Inconsistencies: Older browsers may not fully support HTML5 features.
• Mobile Compatibility: Some older mobile devices may struggle with certain HTML5 features.
• Security Risks: New features like Web Storage can potentially expose user data if not handled
properly.
• Complexity: Advanced features like WebSockets and APIs can be challenging for beginners.
• Lack of Support in Older Internet Explorer Versions: Some older versions of IE (like IE 8 and
below) do not support HTML5 at all.
More Example of HTML5
Adding a Video Using the <video> Tag
<html>
<body>

<h1>HTML5 Video Example</h1>


<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
</html>
In this example,
• The <video> tag is used to embed a video in the HTML page.
• The controls attribute adds play, pause, and volume control buttons.
• The <source> tag specifies the video file and format. If the video is not supported, the text
inside the <video> tag will be displayed.
Using the <canvas> Element for Drawing

<html>

<body>
<h1>HTML5 Canvas Example</h1>
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
var canvas = [Link]("myCanvas"); var ctx =
[Link]("2d"); [Link] = "blue"; [Link](50, 50, 100, 100);
</script>
</body>
</html>
In this example,
• The <canvas> tag is used to create an area for drawing graphics using JavaScript.
• The getContext(“2d”) method is used to set up a 2D drawing context on the canvas.
• The fillRect method draws a blue rectangle within the canvas.
Using the <progress> Element to Show Task Progress

<html>
<body>

<h1>HTML5 Progress Bar Example</h1>


<progress value="70" max-'100"></progress>
</body>
</html>
• The <progress> tag is used to display a progress bar on the webpage.
• The value attribute sets the current progress, and the max attribute defines the maximum value.
Best Practices of Using HTML5
• Use Semantic Tags: Improve SEO and accessibility by using tags like <header>, <footer>,
<article>, and <section>.
• Ensure Cross-Browser Compatibility: Test your code across multiple browsers, especially older
versions.
• Use <meta charset=”UTF-8''>: Always specify the character encoding at the start to avoid
encoding issues.
• Mobile Responsiveness: Use the <meta name=”viewport” content=”width=device-width,
initial-scale=1.0"> tag for mobile-friendly designs.
Browser Support for HTML5
• Apple Safari, Google Chrome, Mozilla Firefox, and Opera (latest versions) provide extensive
support for HTML5 features.
• Internet Explorer 9.0 supports some HTML5 functionalities, although it is considered outdated.
• Mobile browsers on iPhones,iPads, and Android devices offer excellent HTML5 support.
• These mobile browsers ensure smooth access to modern web apps and features, providing a
smooth experience on smartphones and tablets.
UNIT 2

CSS 3

2.1 Inline Style sheet

2.2 Embedded Style Sheet

2.3 External Style Sheet

2.4 Positioning Elements:

2.5 Absolute Positioning

2.6 z-index

2.7 Relative Positioning

2.8 span, Backgrounds, Box Model

2.9 Text Flow

2.10 Text Shadows, Box Shadows

2.11 Animations

2.12 Transitions and Transformations

HTML Styles - CSS

CSS stands for Cascading Style Sheets.

CSS saves a lot of work. It can control the layout of multiple web pages all at
once.

CSS = Styles and Colors

M a n i p u l a t e T e x t Colors, Boxes
Boxes
What is CSS?

Cascading Style Sheets (CSS) is used to format the layout of a webpage.

With CSS, you can control the color, font, the size of text, the spacing between elements, how
elements are positioned and laid out, what background images or background colors are to be used,
different displays for different devices and screen sizes, and much more!

Tip: The word cascading means that a style applied to a parent element will also apply to all children
elements within the parent. So, if you set the color of the body text to "blue", all headings, paragraphs,
and other text elements within the body will also get the same color (unless you specify something
else)!

Using CSS

CSS can be added to HTML documents in 3 ways:

• Inline - by using the style attribute inside HTML elements


• Internal - by using a <style> element in the <head> section
• External - by using a <link> element to link to an external CSS file

The most common way to add CSS, is to keep the styles in external CSS files. However, in this
tutorial we will use inline and internal styles, because this is easier to demonstrate, and easier for you
to try it yourself.

Inline CSS

An inline CSS is used to apply a unique style to a single HTML element.

An inline CSS uses the style attribute of an HTML element.


The following example sets the text color of the <h1> element to blue, and the text color of the <p>
element to red:
Example
<h1 style="color:blue;">A Blue Heading</h1>

<p style="color:red;">A red paragraph.</p>

Internal CSS

An internal CSS is used to define a style for a single HTML page.

An internal CSS is defined in the <head> section of an HTML page, within a <style> element.
The following example sets the text color of ALL the <h1> elements (on that page) to blue, and the
text color of ALL the <p> elements to red. In addition, the page will be displayed with a
"powderblue" background color:
Example

<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;} h1 {color: blue;} p {color: red;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

External CSS

An external style sheet is used to define the style for many HTML pages.

To use an external style sheet, add a link to it in the <head> section of each HTML

page:
Example

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="[Link]">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

The external style sheet can be written in any text editor. The file must not contain any HTML code,
and must be saved with a .css extension.

Here is what the "[Link]" file looks like:

"[Link]": body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}

Tip: With an external style sheet, you can change the look of an entire web site, by changing one file!

CSS Colors, Fonts and Sizes

Here, we will demonstrate some commonly used CSS properties. You will learn more about them later.
The CSS color property defines the text color to be used.

The CSS font-family property defines the font to be used.

The CSS font-size property defines the text size to be used.

Example
Use of CSS color, font-family and font-size properties:

<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue; font-family: verdana; font-size: 300%;
}
p{

color: red; font-family: courier; font-size: 160%;


}

</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

CSS Border

The CSS border property defines a border around an HTML element.


Tip: You can define a border for nearly all HTML elements.

Example

Use of CSS border property: p {


border: 2px solid
} powderblue;

CSS Padding

The CSS padding property defines a padding (space) between the text and the

border. Example

Use of CSS border and padding properties: p {


border: 2px solid

powderblue;
padding: 30px;
}

CSS Margin

The CSS margin property defines a margin (space) outside the border.

Example

Use of CSS border and margin properties: p {


border: 2px solid
margin: 50px; powderblue;
}
Link to External CSS

External style sheets can be referenced with a full URL or with a path relative to the current web

page. Example
This example uses a full URL to link to a style sheet:

<link rel="stylesheet" href="[Link]

Example

This example links to a style sheet located in the html folder on the current web site:

<link rel="stylesheet" href="/html/[Link]">

Example

This example links to a style sheet located in the same folder as the current page:

<link rel="stylesheet" href="[Link]">


You can read more about file paths in the chapter HTML File Paths.

Chapter Summary

• Use the HTML style attribute for inline styling


• Use the HTML <style> element to define internal CSS
• Use the HTML <link> element to refer to an external CSS file
• Use the HTML <head> element to store <style> and <link> elements
• Use the CSS color property for text colors
• Use the CSS font-family property for text fonts
• Use the CSS font-size property for text sizes
• Use the CSS border property for borders
• Use the CSS padding property for space inside the border
• Use the CSS margin property for space outside the border
Tip: You can learn much more about CSS in our CSS Tutorial.
HTML Style Tags

Tag Description

<style> Defines style information for an HTML document

<link> Defines a link between a document and an external resource

For a complete list of all available HTML tags, visit our HTML Tag Reference

UNIT 3

3.1Prompt Dialogs

3.2 Control Statements

3.3 Functions-

3.4 Arrays

3.5 Objects

3.6 DOM

3.7 Event Handling

JavaScript Events
<html>

<script>

function myFun() {

[Link](

"gfg").innerHTML = "GeeksforGeeks";
}

</script>

<body>

<button onclick="myFun()">Click me</button>

<p id="gfg"></p>

</body>

</html>

JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by
various user interactions or by the browser itself.

<html>
<script>

function myFun() {
[Link](
"gfg").innerHTML = "GeeksforGeeks";
}
</script>

<body>
<button onclick="myFun()">Click
me</button> <p id="gfg"></p>
</body>
</html>
• The onclick attribute in the <button> calls the myFun() function when clicked.
• The myFun() function updates the <p> element with id="gfg" by setting its innerHTML to
"GeeksforGeeks".
• Initially, the <p> is empty, and its content changes dynamically on button click.
Event Types
JavaScript supports a variety of event types. Common categories include:
• Mouse Events: click, dblclick, mousemove, mouseover, mouseout
• Keyboard Events: keydown, keypress, keyup
• Form Events: submit, change, focus, blur
• Window Events: load, resize, scroll Common JavaScript Events

Event Attribute Description

onclick Triggered when an element is clicked.

onmouseover Fired when the mouse pointer moves over an element.

onmouseout Occurs when the mouse pointer leaves an element.

onkeydown Fired when a key is pressed down.

onkeyup Fired when a key is released.

onchanae Triggered when the value of an input element changes.

onload Occurs when a page has finished loading.

onsubmit Fired when a form is submitted.

onfocus Occurs when an element gets focus.

onblur Fired when an element loses focus.

//Mouse Event
[Link]("mousemove", (e) => { [Link]('Mouse moved to ($
{[Link]}, ${[Link]})');
});

// Keyboard Event
[Link]("keydown", (e) => { [Link]('Key pressed: ${[Link]}');
});

• The mousemove event tracks cursor movement.


• The keydown event captures key presses.
JavaScript Event Handlers
Event handlers can be used to handle and verify user input, user actions, and browser
actions:
• Things that should be done every time a page loads
• Things that should be done when the page is closed
• Action that should be performed when a user clicks a button
• Content that should be verified when a user inputs data
• And more ...
Many different methods can be used to let JavaScript work with events:
• HTML event attributes can execute JavaScript code directly
• HTML event attributes can call JavaScript functions
• You can assign your own event handler functions to HTML elements
• You can prevent events from being sent or being handled
• And more ...
Event Handling Methods
1. Inline HTML Handlers

2. DOM Property Handlers

let btn [Link]( myButton );

[Link] () => {

alert("Button clicked!");
};

3. addEventListener() (Preferred)

[Link]("click", () => {
alert("Button clicked using addEventListener!");
});
addEventListener() is the most versatile and recommended method as it supports multiple event
listeners and removal of listeners.
Event Propagation
JavaScript events propagate in two phases:
• Capturing Phase: Event travels from the root to the target element.
• Bubbling Phase: Event travels from the target element back to the root.
[Link]("div").addEventListener("click", () => {
[Link]("Div clicked");
}, true); // Capturing phase

[Link]("click", (e) => { [Link]("Button clicked"); [Link](); //Stops


propagation
});

• Setting true in addEventListener makes it capture events during the capturing phase.
• stopPropagation() halts further propagation.
Event Delegation
Event delegation allows you to handle events efficiently by attaching a single listener to a parent

[Link]("ul").addEventListener("click", (e) => { if ([Link] === "LI") {


[Link]('Clicked on item: ${[Link]}');
}
});

Events are delegated to list, reducing the need to add listeners to each list items.
Preventing Default Behavior
Certain elements have default actions (e.g., links navigating to URLs). Use preventDefault() to
override

[Link]("a").addEventListener("click", (e) =>


{ e .preventDefault();
[Link]("Link click prevented");
});

preventDefault() stops the link from navigating.


Practical Applications
1. Form Validation

<html>

<body>
<h2>Form Validation</h2>
<form id="example">
<input type="text" placeholder="Enter something" id="formInput" /> <button
type="submit">Submit</button>
</form>
<script>
[Link]("#example").addEventListener("submit", (e) => { let
input = [Link]("#formInput"); if (![Link])
{ [Link](); alert("Input cannot be empty");
}
});
</script>

</body>

</html>
2. Dynamic Content

<html>

<body>
<h2>Dynamic Content</h2>
<button id="button">Add Element</button>
<script>
[Link]("#button").addEventListener("click", () =>
{ let newDiv = [Link]("div"); [Link] =
"New Element Added"; [Link] = "10px 0";
[Link](newDiv);
});
</script>

<body>

<h2>Interactive Lists</h2>
<ul id="lists">
<li>Interactive Item 1</li>
<li>Interactive Item 2</li>
<li>Interactive Item 3</li>
</ul>
<script>
let ul = [Link]("#lists");

[Link]("click", (e) => { if


([Link] === "LI") {
[Link] = "yellow";
}
});
</script>
</body>

</html>
UNIT 4

4.1 PHP

4.2 Converting between data types

4.3 Arithmetic Operators

4.4 Arrays

4.5 Strings

4.6 Regular Expressions

4.7 Form Processing

4.8 Reading From Databases

4.9 Cookies
PHP provides various functionalities for web development, including handling data types, performing
operations, managing data structures, processing user input, interacting with databases, and managing
client-side data.
1. Converting Between Data Types (Type Juggling & Casting):

PHP is a loosely typed language, allowing for automatic type conversion (type juggling). Explicit
type casting can be done using (int), (float), (string), (array), (object), and (bool) to convert variables
specific types.
to

Code
<?php
$num_string "123";
$num_int = (int) $num_string; // Explicit casting to integer

$sum = $num_string + 5; // Type juggling: ”123” is converted to 123 for addition echo "Sum:
" . $sum; // Output: Sum: 128
?>

2. Arithmetic Operators:

PHP supports standard arithmetic


operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus), and **
(exponentiation).
Code
<?php
$a = 10;
$b = 3;
echo "Addition: " . ($a + $b) . "\n";
0/
echo "Modulus: " . ($a % $b) . "\n";
?>

3. Arrays:

Arrays store multiple values in a single variable. They can be indexed (numeric keys) or associative
(named keys).
Code
<?php

$colors = ["red", "green", "blue"]; // Indexed array


echo $colors[0] . "\n";

$person = ["name" => "Alice", "age" => 30]; // Associative array


echo $person["name"] . "\n";
?>

4. Strings:

Strings are sequences of characters. PHP offers various functions for string manipulation, including
concatenation (.), length (strlen()), substring extraction (substr()), and replacement (str_replace()).

Code
<?php
$greeting = "Hello";
$name = "World";
$full_greeting = $greeting . " " . $name;
echo $full_greeting . "\n";
?>
5. Regular Expressions:

Regular expressions (regex) are powerful tools for pattern matching and manipulation within strings.
PHP's PCRE functions (e.g., preg_match(), preg_replace()) are used for this purpose.

Code
<?php
$text = "The quick brown fox jumps over the lazy dog.";
if (preg_match("/fox/", $text)) {

echo "Found 'fox' in the text.\n";


}

?>

6. Form
Processing:

PHP is commonly used to process data submitted through HTML forms. Data is typically accessed
via the $_GET (for GET requests) or $_POST (for POST requests) superglobal arrays.

Code
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
echo "Welcome, " . htmlspecialchars($username) . "!\n";
}
?>

7. Reading From Databases:

PHP interacts with databases (e.g., MySQL, PostgreSQL) using extensions like MySQLi or PDO.
This involves connecting, executing queries, and fetching results.

Code
<?php
// Example using MySQLi
$conn = new mysqli("localhost", "user", "password", "database");
if ($conn->connect error) {

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


}

$result = $conn->query(" SELECT name FROM users");


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

echo $row["name"] "\n";


}

$conn->close();
?>

8. Cookies:

Cookies are small pieces of data stored on the client's browser to maintain state information. PHP's
setcookie() function sets cookies, and $_COOKIE superglobal array accesses them.
Code
<?php
setcookie("user_pref', "dark_mode", time() + (86400 * 30), // 30-day cookie
if (isset($_COOKIE["user_pref"])) {
echo "User preference: " . $_COOKIE["user_pref'] . "\n";
}
?>

PHP Data Types

Variables can store data of different types, and different data types can do different

things. PHP supports the following data types:

• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

Get the Data Type

You can get the data type of any object by using the var dump() function.

ExampleGet your own PHP Server

The var dump() function returns the data type and the value:

$x = 5;

var_dump($x);
PHP String

A string is a sequence of characters, like "Hello world!".


A string can be any text inside quotes. You can use single or double quotes:
Example

$x = "Hello world!";

$y = 'Hello world!';

var_dump($x); echo "<br>";

var_dump($y);

PHP Integer

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.

Rules for integers:


• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary
(base 2) notation
In the following example $x is an integer. The var dump() function returns the data type and value:

Example

$x=5985;

var_dump($x);

PHP Float

A float (floating point number) is a number with a decimal point or a number in exponential form.

In the following example $x is a float. The var dump() function returns the data type and value:

Example
$x = 10.365;
I var_dump($x);

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.

Example $x =

true;

var_dump($x)

;Booleans are often used in conditional testing.

You will learn more about conditional testing in the PHP If,,,Else chapter.

PHP Array

An array stores multiple values in one single variable.

In the following example $cars is an array. The var dump() function returns the data type and

value: Example

$cars =

array("Volvo","BMW","Toyota");

var_dump($cars);
You will learn a lot more about arrays in later chapters of this tutorial.

PHP Object

Classes and objects are the two main aspects of object-oriented programming.

A class is a template for objects, and an object is an instance of a class.


When the individual objects are created, they inherit all the properties and behaviors from the class,
but each object will have different values for the properties.

Let's assume we have a class named Car that can have properties like model, color, etc. We can
define variables like $model, $color, and so on, to hold the values of these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties
and behaviors from the class, but each object will have different values for the properties.

If you create a construct() function, PHP will automatically call this function when you create an
object from a class.

Example

class Car {

public $color;

public $model;

public function __construct($color, $model) {

$this->color = $color;

$this->model = $model;
}

public function message() {

return "My car is a " . $this->color . " " . $this->model . "!";

$myCar = new Car("red", "Volvo"); var_dump($myCar);


Do not worry if you do not understand the PHP Obj ect syntax, you will learn more about that in the
PHP Classes/Objects chapter.

PHP NULL Value


Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

Tip: If a variable is created without a value, it is automatically assigned a value of NULL.

Variables can also be emptied by setting the value to NULL:

Example

$x = "Hello world!";

$x = null; var_dump($x);

Change Data Type

If you assign an integer value to a variable, the type will automatically be an integer.

If you assign a string to the same variable, the type will change to a string:

Example
$x = 5;

var_dump($x);

$x = "Hello"; var_dump($x);
If you want to change the data type of an existing variable, but not by changing the value, you can use
casting.
Casting allows you to change data type on variables:

Example
$x = 5;

$x = (string) $x; var_dump($x);


You will learn more about casting in the PHP Casting Chapter.

PHP Resource

The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP.
A common example of using the resource data type is a database call.

We will not talk about the resource type here, since it is an advanced topic.

UNIT 5

5.1 XML Basics

5.2 Structuring Data

5.3 XML Namespaces

5.4 DTD

5.5 XSLT transformation

5.6 Creating AJAX Applications using XML

5.7 Http Request Object and JSON

transformation, and asynchronous communication.


XML Basics:

• Structuring Data:

using custom tags, making it human-readable and machine-understandable. It focuses on what the data is,
not how it's displayed.
XML Namespaces:

sources. They use a URI to uniquely identify a collection of element and attribute names.

• DTD (Document Type Definition):

attributes, and their relationships. It ensures the structural validity of an XML file.
XSLT Transformation:

• XSLT (Extensible Stylesheet Language Transformations): XSLT is used to transform XML documents

i
into other formats, such as HTML, plain text, or another XML structure. It uses XPath to navigate and
select nodes within the XML document for transformation.
Creating AJAX Applications using XML Http Request Object and JSON:
• AJAX (Asynchronous JavaScript and XML):
AJAX is a web development technique that allows web pages to update content asynchronously,

i
without reloading the entire page. This enhances user experience by making web applications more
responsive.
• XMLHttpRequest Object:
This is the core of AJAX. It's a JavaScript object used to send asynchronous HTTP requests to a web

server and receive responses. Key methods include open() to initialize the request and send() to transmit
it.

• JSON (JavaScript Object Notation):

exchange due to its lightweight nature and direct compatibility with JavaScript. When using
XMLHttpRequest, the server can send data in JSON format, which can then be easily parsed and used by
JavaScript to update the webpage dynamically.

JAX - The XMLHttpRequest Object

The keystone of AJAX is the XMLHttpRequest object.

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.


The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This
means that it is possible to update parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, Edge (and IE7+), Safari, Opera) have a built-in
XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Example

var xhttp = new XMLHttpRequest();


The "ajax_info.txt" file used in the example above, is a simple text file and looks like this:

<h1 >AJAX</h1 >


<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p> <p>AJAX stands for
Asynchronous JavaScript And XML.</p>

Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same

server.

The examples on W3Schools all open XML files located on the W3Schools domain.
If you want to use the example above on one of your own web pages, the XML files you load must be
located on your own server.
XMLHttpRequest Object Methods

Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object


abort() Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

open(method, url,async,user,psw) Specifies the request

method: the request type GET or POST url:


the file location async: true (asynchronous)
or false (synchronous)
user: optional user name psw: optional
password

send()
Sends the request to the server Used for GET
requests

send(string)
Sends the request to the server. Used for
POST requests

setRequestHeader()
Adds a label/value pair to the header to be
sent
Property Description

onreadystatechange
Defines a function to be called when the readyState
property changes

readyState
Holds the status 0: of the XMLHttpRequest.
request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

responseText Returns the response data as a string

responseXML Returns the response data as XML data

status Returns the status-number of a request


200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")

XMLHttpRequest Object Properties

You might also like