Database and Web Development Module
Database and Web Development Module
APRIL 2024.
Table of Contents
Introduction .................................................................................................................................3
Sub theme 1: Fundamentals of Database .......................................................................................6
Sub theme 2: Internet and web design......................................................................................... 86
Sub theme 3: Web Programming ............................................................................................... 241
Sub theme 4: Multimedia System and Development .................................................................. 290
Introduction
Welcome to the comprehensive module designed to guide students through the key subjects
essential for their exit exam: Fundamentals of Database, Internet and Web Design, Web
Programming, and Multimedia System and Development. This module is carefully structured to
provide students with a deep understanding of these critical areas, ensuring they are well-equipped
to tackle the challenges of the digital world with confidence.
Throughout this module, students will embark on a journey of exploration and mastery, delving
into the intricacies of database management, web design principles, programming techniques, and
multimedia development. From laying the foundation with database fundamentals to mastering the
art of creating dynamic web applications and captivating multimedia experiences, this module
offers a holistic approach to learning that prepares students for success in their exit exam and
beyond. Join us as we dive into the fascinating realms of technology and innovation, empowering
students to unleash their potential and thrive in today's digital landscape.
Understand
multimedia editing
Multimedia
Explain multimedia, applications, elements
System and and production
3 2
techniques to and design principles
Development create
professional-
quality multimedia
content
Prepared By:
Tinsae D.
Approved By:
ICT Department
Sub theme 1: Fundamentals of Database
Welcome to the foundational guide to relational databases, tailored specifically for students
seeking to grasp the fundamental principles of data management. In today's digital landscape,
relational databases serve as the bedrock of countless applications, offering a structured approach
to organizing and retrieving data. This comprehensive overview will illuminate the core concepts
of relational database modules, empowering students to navigate the intricacies of this essential
technology with confidence.
At its essence, a relational database module provides a structured framework for storing and
managing data in tables with predefined relationships. Whether you're delving into the world of
software development, data analytics, or business intelligence, understanding relational databases
is indispensable. Throughout this guide, we'll unravel the key components and functionalities of
relational databases, from data modeling and normalization techniques to the principles of
querying using SQL (Structured Query Language).
Through this journey, students will gain proficiency in designing, implementing, and optimizing
relational database systems. We'll explore the principles of the relational model, emphasizing the
importance of maintaining data integrity and consistency through well-defined relationships
between tables. Additionally, we'll delve into practical aspects such as creating and manipulating
tables, writing efficient SQL queries, and optimizing database performance. By mastering these
foundational concepts, students will be well-equipped to leverage the power of relational databases
in various domains, laying a solid groundwork for their future endeavors.
1.1.What is database?
A database is a structured collection of interrelated data organized in a manner that allows efficient
storage, retrieval, and manipulation of information. It serves as a central repository for storing and
managing data, providing users with a systematic way to access and interact with the stored
information. In essence, a database acts as an electronic filing system, where data is stored in
tables, each consisting of rows and columns.
The primary purpose of a database is to facilitate data management and enable users to perform
various operations on the stored data, such as querying, updating, and deleting records. By
structuring data into a database, organizations can ensure data integrity, consistency, and security,
thus reducing redundancy and minimizing data inconsistency issues. Additionally, databases
provide mechanisms for enforcing data constraints and relationships, enabling data validation and
maintaining data accuracy.
Databases play a crucial role in modern computing, powering a wide range of applications across
various industries, including finance, healthcare, education, and e-commerce. They serve as the
backbone of information systems, supporting mission-critical operations and enabling
organizations to make informed decisions based on accurate and timely data. With the advent of
technologies like relational databases, NoSQL databases, and cloud-based database services, the
capabilities and scalability of databases continue to evolve, catering to the growing demands of
data-driven applications.
In general, a Database is - a collection of related data (General definitions). A database has the
following implicit properties:
• It represents some aspects of the real world, sometimes called the mini world or the
Universe of Discourse (UoD)
• It is a logically coherent collection of data with some inherent meaning
• It is designed, built, and populated with data for a specific purpose A database can be of
any size and of varying complexity e.g. - Address book 8 A database may be generated and
maintained manually or it may be computerized (our concern in this course is the
computerized one)
Note: even though there are a lot of categories of DBMS our focus in this course is
on Relational DBMS
1.3.Database System
A database system is a software application that enables the storage, retrieval, management, and
manipulation of structured data. It consists of two main components: the database itself, which
stores the data, and the Database Management System (DBMS), which provides the interface for
users to interact with the database. The database system facilitates efficient data storage and
retrieval by organizing data into tables, each consisting of rows and columns. It supports various
data types, such as text, numbers, dates, and binary data, allowing for the representation of diverse
types of information.
The DBMS serves as the intermediary between users and the database, offering tools and utilities
for defining the database schema, querying and manipulating data, enforcing data integrity
constraints, and managing transactions. It provides users with a structured way to access and
manage data, ensuring data consistency, security, and reliability. Moreover, database systems
support concurrent access by multiple users, enabling collaborative data sharing and processing.
With the evolution of technology, modern database systems offer advanced features such as
scalability, high availability, and support for distributed computing, catering to the diverse needs
of organizations across different industries.
Here are some examples of database systems
Library Management System
• Manages library resources such as books, journals, and multimedia materials
• Tracks borrowing and returning of items by patrons
Components of a DBMS
A DBMS is partitioned into several software components (or modules), each of which is assigned
a specific operation. The following are the major software components of a DBMS
• Query processor - transforms queries into a series of low-level instructions directed to the
database manager
• Database manager (DM) Accepts queries and examines to determine what conceptual
records are required to satisfy the request. The DM then places a call to the file manager to
perform the request.
In contrast, a database system employs a centralized approach to data management, where data is
stored in a structured format within a database, and data manipulation is performed through a
Database Management System (DBMS). Databases organize data into tables, each consisting of
rows and columns, and support features such as data indexing, transaction management, and query
optimization. By providing a structured framework for data storage and retrieval, database systems
offer advantages such as improved data organization, integrity, and accessibility. Additionally,
DBMSs offer robust security mechanisms, such as authentication, authorization, and encryption,
to protect sensitive data and ensure regulatory compliance. Overall, while file-based systems are
suitable for small-scale applications with limited data requirements, database systems are more
scalable, secure, and efficient for managing large volumes of structured data in complex
environments.
Advantages of a database system
Some of the advantages of using a database system as compared to a file-based system are:
• Data Centralization: A database system centralizes data storage, providing a single
repository for storing and managing data. This eliminates data redundancy and
inconsistency that can occur in file-based systems, where data may be duplicated across
multiple files or documents.
• Data Integrity: Database systems enforce data integrity constraints, such as primary key,
foreign key, and data validation rules, to ensure the accuracy and reliability of stored data.
Overall, while file-based systems may be suitable for small-scale applications with limited data
requirements, they pose significant limitations in terms of data management, sharing, integrity,
and scalability compared to modern database systems.
1. What is the definition of a database system and why is it essential in modern information
management?
2. How do relational databases differ from other types of data storage systems, and what
advantages do they offer?
3. What are the key components of a database schema, and how do they contribute to data
organization and retrieval?
4. Explain the concept of data normalization and its significance in database design and
management.
5. How does SQL (Structured Query Language) facilitate data manipulation and retrieval in
relational database systems?
6. Discuss the importance of maintaining data integrity and consistency in database systems,
and how it is achieved.
7. What are the primary functions of a database management system (DBMS) in handling
data operations and queries?
8. How does the relational model establish relationships between tables and ensure efficient
data retrieval?
9. Describe the process of creating and manipulating tables in a relational database, including
defining primary and foreign keys.
10. In what ways can understanding the principles of database systems benefit individuals
pursuing careers in software development, data analytics, and business intelligence?
A data model is a conceptual representation of the structure and relationships of data within a
database system. It defines the organization and format of data elements, as well as the rules and
constraints that govern their manipulation and storage. Data models serve as blueprints for
designing databases and provide a common language for communication between database
designers, developers, and users.
There are several types of data models, each with its own approach to representing data. The most
commonly used data models include the Entity relationship model, relational model, hierarchical
model, network model, and object-oriented model. The relational model, pioneered by E.F. Codd
in the 1970s, organizes data into tables with rows and columns, representing entities and their
attributes. Relationships between entities are established through keys, enabling efficient querying
and manipulation of data using structured query language (SQL).
In addition to traditional data models, newer models have emerged to address specific data
management challenges. For example, the object-oriented data model extends the relational model
to support complex data structures and inheritance hierarchies, making it suitable for object-
oriented programming paradigms. Similarly, the document-oriented model, popularized by
NoSQL databases like MongoDB, stores data in flexible document formats such as JSON or XML,
enabling schema-less data storage and dynamic schema evolution. Overall, data models play a
crucial role in database design and development, providing a foundation for building robust and
efficient database systems to meet the evolving needs of modern applications.
Note: DBMS are developed based on data model, for example RDBMs such as
Microsoft SQL Server, MySQL and the like are software developed using Relational
model.
Here are some lists for data models with and their descriptions:
1. Relational Model: Organizes data into tables with rows and columns, establishing
relationships between entities using keys. It is based on the principles of mathematical set
theory and is widely used in relational database management systems (RDBMS) like
MySQL, PostgreSQL, Oracle Database, and Microsoft SQL Server.
Once the data model is defined, database developers embark on the implementation phase, where
they translate the logical data model into a physical database schema and build the database system
using a Database Management System (DBMS). During database development, developers focus
on tasks such as creating tables, defining data types, establishing relationships, and optimizing
database performance. They also write database queries, stored procedures, triggers, and other
1. Requirements Analysis:
• Understand the requirements of the database system, including data storage needs,
functionality requirements, user access requirements, and performance
expectations.
• Gather requirements through discussions with stakeholders, interviews, surveys,
and documentation review.
2. Conceptual Design:
• Develop a conceptual data model that represents the high-level structure and
relationships of the data.
• Identify entities, attributes, relationships, and constraints using techniques such as
Entity-Relationship Diagrams (ERDs).
3. Logical Design:
• Translate the conceptual data model into a logical data model that can be
implemented in a database management system (DBMS).
• Normalize the data model to reduce redundancy and improve data integrity.
• Define tables, columns, primary keys, foreign keys, and other database objects
based on the logical data model.
4. Physical Design:
• Design the physical database schema and storage structures based on the logical
data model.
• Choose appropriate data types, indexing strategies, partitioning schemes, and
optimization techniques to enhance performance and scalability.
• Consider factors such as data volume, access patterns, and system resources when
designing the physical database layout.
5. Implementation:
• Create the database schema and build the database objects using a DBMS.
• Write database scripts, queries, stored procedures, triggers, and other database
artifacts to implement the required functionality.
• Populate the database with initial data sets and perform data validation and
verification.
Problem
Requirement
Analysis
Implementation
(Logical) Design
Application Program
DBMS Implementation
Design
Dependent (Logical) Schema
STUDENT
Attributes
Attributes are the properties or characteristics of entities that describe them further. They
represent the different pieces of information that are stored about each entity. Attributes are
depicted as ovals connected to their respective entities in an ERD. For example, attributes of the
Student entity could include StudentID, Name, sex, date of birth, and GPA.
StudentID Sex
STUDENT
sex
2. Composite Attribute: An attribute that can be divided into smaller parts, each representing
a subpart of the whole attribute.
• Example:
• Address (composed of Street, City, …..)
• E-Diagram Representation
• Oval Branched Street
Address
City
3. Derived Attribute: An attribute whose value can be derived or calculated from other
attributes.
• Example:
• Age (derived from Date of Birth)
• Total Salary (derived from Salary and Bonus)
Age
4. Multi-valued Attribute: An attribute that can have multiple values for a single entity
instance.
• Example:
• Skills (multiple skills possessed by an employee)
• Phone Numbers (multiple phone numbers for a contact)
• E-Diagram Representation
• Double oval
Phone
Number
• E-Diagram Representation
• Underlined oval
ISBN
6. Foreign Key: An attribute that refers to the primary key of another entity, establishing a
relationship between the two entities.
• Example:
• CourseID (foreign key in the Enrollments table referencing the Course
table)
• DepartmentID (foreign key in the Employee table referencing the
Department table)
• E-R Diagram Representation
• Dash Underlined oval
ISBN
M enrolls M
STUDENT Course
in
Cardinality constraint
In the context of the Entity-Relationship (ER) model, cardinality constraints specify the number
of instances of one entity that can be associated with another entity in a relationship. They define
the nature and scope of relationships between entities, providing valuable insights into how entities
interact with each other within the database.
For a binary relationship there are four types of carinality constraints
i. one-to-one (1:1)
ii. one-to-many (1:N)
iii. many-to-one (N:1)
iv. many-to- many (N: N)
A one-to-one (1:1) cardinality constraint indicates that each instance of one entity is associated
with exactly one instance of another entity, and vice versa. This type of relationship is relatively
rare in practice but is useful in certain scenarios where a strict one-to-one correspondence exists
between entities.
A one-to-many (1:N) cardinality constraint indicates that each instance of one entity can be
associated with multiple instances of another entity, but each instance of the other entity is
associated with at most one instance of the first entity. This is the most common type of
relationship in database modeling, where one entity acts as the parent and the other as the child.
A many-to-many (N: N) relationship, each instance of one entity can be associated with zero or
more instances of another entity, and vice versa. This type of relationship requires the use of an
associative entity or junction table to represent the relationship.
Note: the expected output of Entity-Relationship model is Entity-Relationship diagram
• Tables − In relational data model, relations are saved in the format of Tables. This format
stores the relation among entities. A table has rows and columns, where rows represents
records and columns represent the attributes.
• Tuple − A single row of a table, which contains a single record for that relation is called a
tuple.
• Relation instance − A finite set of tuples in the relational database system represents
relation instance. Relation instances do not have duplicate tuples.
• Relation schema − A relation schema describes the relation name (table name), attributes,
and their names.
• Relation key − Each row has one or more attributes, known as relation key, which can
identify the row in the relation (table) uniquely.
• Attribute domain − Every attribute has some pre-defined value scope, known as attribute
domain.
Constraints
Every relation has some conditions that must hold for it to be a valid relation. These conditions
are called Relational Integrity Constraints. There are three main integrity constraints −
• Key constraints
• Domain constraints
• Referential integrity constraints
i. Key Constraints
There must be at least one minimal subset of attributes in the relation, which can identify a tuple
uniquely. This minimal subset of attributes is called key for that relation. If there are more than
one such minimal subsets, these are called candidate keys.
• in a relation with a key attribute, no two tuples can have identical values for key attributes.
• a key attribute can not have NULL values.
Attributes have specific values in real-world scenario. For example, age can only be a positive
integer. The same constraints have been tried to employ on the attributes of a relation. Every
attribute is bound to have a specific range of values. For example, age cannot be less than zero and
telephone numbers cannot contain a digit outside 0-9.
Referential integrity constraints work on the concept of Foreign Keys. A foreign key is a key
attribute of a relation that can be referred in other relation.
Referential integrity constraint states that if a relation refers to a key attribute of a different or
same relation, then that key element must exist.
The Entity-Relationship (ER) model and the Relational model are two fundamental approaches to
database design, each with its unique characteristics and focus. The ER model, a conceptual data
model, emphasizes the high-level representation of data structures and relationships. In ER
diagrams, entities are depicted as rectangles representing real-world objects or concepts, while
relationships are illustrated as lines connecting entities, showcasing associations between them.
The ER model allows for the specification of constraints such as cardinality (one-to-one, one-to-
many, many-to-many) and participation, enabling the enforcement of data integrity. However, the
ER model does not address data storage or manipulation details but instead provides a blueprint
for database design.
In general ER Model, when conceptualized into diagrams, gives a good overview of entity-
relationship, which is easier to understand. ER diagrams can be mapped to relational
schema(relational model) that could make it easier for identifies each component.
Transitioning from the big ideas of how things relate in an E-R diagram to the nitty-gritty details
of how they're organized in a database, converting an E-R diagram into relations is like building a
road from concept to reality. It's where we take the abstract notions of what entities, relationships,
and attributes mean and turn them into concrete tables, keys, and rules. This conversion process is
crucial because it sets the stage for how our data will be stored and retrieved efficiently. It's like
turning a sketch of a house into a blueprint that builders can follow step by step.
Converting an E-R diagram to relations is all about moving from a big picture view to a more
focused and practical way of designing databases. It's like breaking down a complicated puzzle
into smaller, more manageable pieces. We take each entity, attribute, and relationship and organize
them into separate tables, with keys and rules to guide how they fit together. This step-by-step
process helps us create a blueprint for our database that reflects how everything connects and
makes it easier to work with the information we need.
The following are general steps to convert E-R diagram (conceptual design of a database) to
Relational model (logical design of a database):
1. Identify Entities (Entity Types): In the relational model, entities correspond to tables. Each
entity type in the E-R diagram becomes a table in the relational schema.
2. Define Attributes (Attributes): Attributes in the E-R diagram translate directly to columns
in the relational tables. Each attribute represents a specific piece of data stored in the table.
3. Determine Keys (Primary Key): The primary key uniquely identifies each record in a table.
In the relational model, the primary key constraint is applied to one or more columns to
ensure uniqueness.
4. Recognize Relationships (Relationships): Relationships between entities are represented in
the relational model by foreign keys. These foreign keys establish the connections between
tables, reflecting the associations between related entities.
5. Translate Relationships into Tables (Relationship Sets): Each relationship set in the E-R
diagram becomes a separate table if and only if the cardinality ratio is many to many. The
table includes foreign key columns referencing the primary keys of the related entities.
Or Resolve Many-to-Many Relationships (Association Tables): Many-to-many
relationships are resolved by creating an association table in the relational schema. This
table typically contains foreign keys referencing the primary keys of the related entities.
6. Check Cardinality and Optionality (Referential Integrity Constraints): The cardinality and
optionality of relationships are reflected in the foreign key constraints applied to the related
tables. These constraints enforce referential integrity and ensure that each foreign key value
corresponds to a valid primary key value.
2.6. Normalization
Normalization is a crucial process in relational database design aimed at reducing data redundancy
and dependency, thereby enhancing data integrity and efficiency. It involves organizing the
database schema into a series of progressively normalized forms, each building upon the previous
one. The goal is to eliminate or minimize data anomalies, such as insertion, update, and deletion
anomalies, which can occur when data is redundantly stored or when dependencies between
attributes are not properly managed. By breaking down larger tables into smaller, more
manageable ones and establishing well-defined relationships between them, normalization ensures
that each table serves a single purpose and contains only relevant information. This systematic
approach to database design not only improves data organization and consistency but also
facilitates easier maintenance and scalability as the database evolves over time.
Normalization typically proceeds through a series of normal forms, with each normal form
addressing specific types of data redundancy and dependency. The most commonly discussed
normal forms include First Normal Form (1NF), Second Normal Form (2NF), Third Normal Form
(3NF), and beyond. Achieving higher normal forms involves further decomposition and
refinement of the database schema to ensure that each table satisfies certain criteria, such as
atomicity of attributes, removal of partial dependencies, and elimination of transitive
dependencies. While normalization helps optimize database structure for efficient data storage and
manipulation, it's important to strike a balance between normalization and performance
considerations. Over-normalization can lead to increased join operations and complexity,
potentially impacting query performance, so it's essential to carefully evaluate the trade-offs and
design a schema that meets the specific requirements of the application while maintaining data
integrity.
1NF
First Normal Form (1NF) is the foundational level of normalization in relational database design,
aiming to ensure that each attribute within a table contains only atomic values, meaning they
For example, let's consider a table that stores information about students and their courses. In its
initial state, it might look something like this:
In this table, the "Course ID" and "Course Name" columns contain multiple values separated by
commas, indicating that multiple courses are associated with each student. This violates the
principles of 1NF because these columns are not atomic; instead, they contain sets of values.
To bring this table into 1NF, we need to separate the repeating groups of attributes into individual
rows. After normalization, the table might look like this:
Now, each row in the table represents a single combination of student and course, with each
attribute holding atomic values. This restructuring adheres to the requirements of 1NF, ensuring
that the table is free from repeating groups and each column contains only indivisible data
elements.
2NF
Second Normal Form (2NF) builds upon First Normal Form (1NF) by addressing the issue of
partial dependencies within a table. In essence, 2NF ensures that each non-prime attribute in a
table is fully functionally dependent on the entire primary key, rather than just a part of it. This
means that every attribute in the table should be directly related to the primary key, not just to a
subset of it.
In this table, {Employee ID, Project ID} is the composite primary key, as each employee can be
assigned to multiple projects and each project can have multiple employees. However, we can see
that the "Department" attribute is functionally dependent only on the "Employee ID", not on the
entire primary key. This violates the principles of 2NF because "Department" is not fully
dependent on the primary key.
To bring this table into 2NF, we need to split it into two separate tables: one for employee
information and another for project information. Each table will have its own primary key, and the
relationship between employees and projects will be represented through a foreign key.
Employee Table:
Project Table:
Assignment Table:
Employee ID Project ID
1 101
2 102
Now, the "Department" attribute is fully dependent on the primary key of the Employee table, and
the table structure adheres to the principles of 2NF. Each attribute is functionally dependent on the
entire primary key of its respective table, eliminating partial dependencies.
Third Normal Form (3NF) is the next level of normalization in relational database design, aiming
to eliminate transitive dependencies within a table. A transitive dependency occurs when a non-
prime attribute is functionally dependent on another non-prime attribute, rather than directly on
the primary key.
Consider a table that stores information about courses and instructors, with the following structure:
In this table, {Course Code} is the primary key. We can observe that the "Instructor Office"
attribute is functionally dependent on the "Instructor Name", rather than directly on the primary
key. Additionally, "Instructor Name" is not part of the primary key, which indicates a transitive
dependency.
To bring this table into 3NF, we need to split it into multiple tables to eliminate the transitive
dependency. We'll have separate tables for courses and instructors, with their own primary keys,
and then create a relationship between them using foreign keys.
Course Table:
Now, each table represents a single entity, and there are no transitive dependencies within any
table. The structure adheres to the principles of 3NF, ensuring that each attribute is functionally
dependent only on the primary key of its respective table, and there are no redundant or non-atomic
values.
1. What is a data model, and why is it crucial in the context of a database system?
2. How does a data model serve as a blueprint for designing databases, and what role does it
play in communication among stakeholders?
3. What are the key elements included in a data model, and how do they define the structure
and relationships of data?
4. Explain the significance of rules and constraints in a data model and how they govern data
manipulation and storage.
5. How do data models facilitate the organization and format of data elements within a
database system?
6. Discuss the importance of data models in providing a common language for collaboration
between database designers, developers, and users.
7. How do different types of data models, such as the relational model and object-oriented
model, address specific data management challenges and support various programming
paradigms?
8. What is Normalization?
3.1. Introduction
SQL, or Structured Query Language, is a programming language designed for managing and
manipulating relational databases. It's a standard language for interacting with databases, enabling
users to perform tasks like querying data, updating data, inserting new data, and deleting data. SQL
is widely used in various industries and applications where structured data storage and retrieval
are essential, such as web development, business analytics, and data science.
• Querying data
• Inserting, updating, and deleting rows in a table
• Creating, replacing, altering, and dropping objects
• Controlling access to the database and its objects
• Guaranteeing database consistency and integrity
Data definition language (DDL) refers to the set of SQL commands that can create and
The create command allow the creation of the database objects and table.
• The syntax for creating a table is this:
For example:
Please take note that the semi-colon is required at the end of the statement. It tells the system to
process everything before it. If you leave it out, you may have strange results, or even receive
errors.
When creating a table, the data types most often used include strings (VARCHAR or CHAR);
numbers (NUMBER or INTEGER); and dates (DATE). Each system varies in how to specify the
data type.
Creating Database
Example
The after Database tables can be added with the CREATE TABLE statement.
column_name1
data_type,
column_name2
data_type,
column_name3
data_type,
....
)
The P_Id column is of type int and will hold a number. The LastName, FirstName, Address, and
City columns are of type varchar with a maximum length of 255 characters.
The empty "Persons" table will now look like this:
The empty table can be filled with data with the INSERT INTO statement.
• Constraints are used to limit the type of data that can go into a table.
• Constraints can be specified when a table is created (with the CREATE TABLE statement)
or after the table is created (with the ALTER TABLE statement). We will focus on the
following constraints:
o NOT NULL
o UNIQUE
o PRIMARY KEY
o FOREIGN KEY
o CHECK
i. SQL PRIMARY KEY Constraint
• The PRIMARY KEY constraint uniquely identifies each record in a database table.
• Primary keys must contain unique values.
• A primary key column cannot contain NULL values.
• Each table should have a primary key, and each table can have only one primary key.
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table
is created:
FirstName varchar(255),
Address varchar(255),
City varchar(255)
Example : the following code is allowing naming of a PRIMARY KEY constraint for
multiple columns
FirstName varchar(255),
Address varchar(255),City
varchar(255),
To create a PRIMARY KEY constraint on the "P_Id" column when the table is already
created, use the following SQL:
Then use the DDL command ALTER TABLE to add the constraint. Think of a constraint as a rule-
enforcer: it limits what type of data is allowed in the data, to identify a primary or foreign key, or to
ensure that there are no duplicates in a given field.
This table example adds the constraint of a primary key that's unique (no repeating valuesare allowed)
to the Artist table. Remember that primary keys will always enforce a uniquevalue.
We have used the DDL ALTER statement to join the tables Artist and Album on theartistID
field from the Artist table, saved into the Album table as albumArtistID.
The constraints are 'artist_fk' (foreign key) and 'artist_pk' (the primary key on the Artisttable).
The ALTER TABLE statement is used to add, delete or modify columns in an existing table.
column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data
type specifies what type of data the column can hold.
Table: The effect of alter command to add DateOfBirth column on person table
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-
digit or four-digit format.
If you need to remove a constraint, use the DROP command in combination with the ALTER
statement like this:
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
The effect of alter command to remove DateOfBirth column from Person Table
The SQL data manipulation language (DML) is used to query and modify database data. In this
chapter, we will describe how to use the SELECT, INSERT, UPDATE, and DELETE SQL DML
command statements, defined below
SELECT column_name(s)
FROM table_name
Hansen Ola
Svendson Tove
Pettersen Kari
SELECT * Example
Now we want to select all the columns from the "Persons" table.
Navigation in a Result-set
Most database software systems allow navigation in the result-set with programming functions,
like: Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SELECT column_name(s)
FROM table_name
Now we want to select only the persons living in the city "Sandnes" from the table above.
WHERE City='Sandnes'
SQL uses single quotes around text values (most database systems will also accept double quotes).
Although, numeric values should not be enclosed in quotes.
= Equal
IN If you know the exact value you want to return for at least one of the columns
• AND & OR operators are used to filter records based on more than one condition.
• AND operator displays a record if both the first and the second condition is true.
• OR operator displays a record if either the first or the second condition is
true.
Now we want to select only the persons with the first name equal to "Tove" AND the last name
equal to "Svendson":
WHERE FirstName='Tove'
AND LastName='Svendson'
OR Operator Example
Now we want to select only the persons with the first name equal to "Tove" OR the first name
equal to "Ola":
WHERE FirstName='Tove'
OR FirstName='Ola'
You can also combine AND and OR (use parenthesis to form complex expressions).
Now we want to select only the persons with the last name equal to "Svendson" AND the first
name equal to "Tove" OR to "Ola":
LastName='Svendson'
SELECT column_name(s)
ORDER BY Example
Now we want to select all the persons from the table above, however, we want to sort the persons
by their last name.
We use the following SELECT statement:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
SQL UPDATE Example
The "Persons" table:
5 Tjessem Jakob
Now we want to update the person "Tjessem, Jakob" in the "Persons" table.
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.
Note: Be very careful when deleting records. You cannot undo this statement!
The second form specifies both the column names and the values to be inserted:
5 Tjessem Jakob
1. GRANT COMMAND
Syntax:
In the above example, user 'ABC' has been permitted to view and modify the records in the
'employee' table.
Syntax:
REVOKE UPDATE
ON employee FROM ABC;
GRANT REVOKE
GRANT command allows a user to perform REVOKE command disallows a user to perform
certain activities on the database. certain activities.
It grants access privileges for database objects to It revokes access privileges for database objects
other users. previously granted to other users.
Example: Example:
GRANT privilege_name REVOKE privilege_name
ON object_name ON object_name
TO FROM
{ {
user_name|PUBLIC|role_name user_name|PUBLIC|role_name
} }
[WITH GRANT OPTION];
Unit summary questions
1. What is SQL, and why is it considered a standard language for managing relational
databases?
2. How does SQL enable users to interact with databases, and what tasks can be performed
using SQL statements?
3. What industries and applications commonly utilize SQL for structured data storage and
retrieval?
4. What are the key commands of SQL that make it efficient, easy to learn, and functionally
complete?
5. What is the difference between DDL and DML
6. Discuss the DDL commands in detail
7. Discuss the DML commands in detail
8. What data controlling languages of SQL?
9. Explain the purpose and usage of the SELECT statement in SQL. Provide an example
query.
10. How do you handle NULL values in SQL queries? Provide examples of functions or
operators used for this purpose.
11. Describe the different types of joins in SQL (e.g., INNER JOIN, LEFT JOIN, RIGHT
JOIN, FULL JOIN). When would you use each type?
12. What is normalization in the context of relational databases, and why is it important?
Provide an example of a normalized database schema.
13. Explain the concept of transactions in SQL. What are ACID properties, and why are they
essential for ensuring data integrity?
14. What are indexes in SQL databases, and how do they improve query performance? Discuss
the types of indexes commonly used.
15. How do you optimize SQL queries for better performance? Mention techniques like query
optimization, indexing, and avoiding unnecessary operations.
16. Describe the process of backing up and restoring databases in SQL Server or another
relational database management system (RDBMS) of your choice.
17. What are stored procedures and triggers in SQL, and how do they differ from regular SQL
queries? Provide examples illustrating their usage.
Unit 4: Relational Algebra
Introduction to Relational Algebra
Relational Algebra serves as the foundational backbone of modern database systems, providing a
mathematical framework for querying and manipulating data stored in relational databases.
Developed by Edgar F. Codd in the early 1970s, relational algebra forms the theoretical basis upon
which the practical operations of database management systems (DBMS) are built. At its core,
relational algebra defines a set of operations for performing common tasks such as selection,
projection, join, and union on relations, which are analogous to tables in a relational database.
These operations enable users to formulate queries to extract, filter, and combine data to derive
meaningful insights and fulfill various information retrieval needs.
The principles of relational algebra are rooted in set theory and predicate logic, offering a rigorous
and formalized approach to database querying. By treating relations as sets of tuples and operations
as functions that manipulate these sets, relational algebra abstracts away the complexities of
database management, allowing users to focus on the logical structure and content of the data
rather than the underlying implementation details. This abstraction layer is instrumental in
achieving data independence, wherein changes to the database schema or physical storage do not
affect the logical view of the data, promoting flexibility and scalability in database design and
maintenance.
One of the key strengths of relational algebra lies in its simplicity and expressive power. Through
a small set of fundamental operations, users can construct complex queries to retrieve precisely
the information they require from large and diverse datasets. These operations include selection
(σ), which filters rows based on specified criteria; projection (π), which selects specific columns
from a relation; join (⨝), which combines tuples from two or more relations based on common
attributes; and union (∪), which merges the tuples from two relations with the same schema. By
composing these operations in various sequences and combinations, users can formulate
sophisticated queries to meet a wide range of data analysis and retrieval needs.
Generaly, relational algebra serves as the cornerstone of modern database systems, providing a
formalized and efficient means of querying and manipulating relational data. By leveraging
principles from set theory and predicate logic, relational algebra offers a powerful and expressive
framework for constructing queries and performing operations on relations. Its simplicity,
flexibility, and data independence make it an essential tool for database developers, administrators,
and users alike, enabling them to interact with and extract valuable insights from vast and complex
datasets efficiently and intuitively. Relational algebra is a procedural query language. It gives a
step by step process to obtain the result of the query. It uses operators to perform queries.
Types of Relational operation
1. Select Operation:
1. Notation: σ p(r)
Where:
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
2. Project Operation:
o This operation shows the list of those attributes that we wish to appear in the result. Rest
of the attributes are eliminated from the table.
o It is denoted by ∏.
Where
Input:
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
3. Union Operation:
o Suppose there are two tuples R and S. The union operation contains all the tuples that are
either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.
1. Notation: R ∪ S
Example:
DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
Input:
Output:
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
4. Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation contains all tuples that
are in both R & S.
o It is denoted by intersection ∩.
1. Notation: R ∩ S
Input:
Output:
CUSTOMER_NAME
Smith
Jones
5. Set Difference:
o Suppose there are two tuples R and S. The set intersection operation contains all tuples that
are in R but not in S.
o It is denoted by intersection minus (-).
1. Notation: R - S
Input:
Output:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
6. Cartesian product
o The Cartesian product is used to combine each row in one table with each row in the other
table. It is also known as a cross product.
o It is denoted by X.
1. Notation: E X D
Example:
EMPLOYEE
1 Smith A
2 Harry C
3 John B
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
1. EMPLOYEE X DEPARTMENT
Output:
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
7. Rename Operation:
The rename operation is used to rename the output relation. It is denoted by rho (ρ).
Example: We can use the rename operator to rename STUDENT relation to STUDENT1.
1. ρ(STUDENT1, STUDENT)
Join Operations:
A Join operation combines related tuples from different relations, if and only if a given join
condition is satisfied. It is denoted by ⋈.
Example:
EMPLOYEE
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
SALARY
EMP_CODE SALARY
101 50000
102 30000
103 25000
Result:
1. Natural Join:
o A natural join is the set of tuples of all combinations in R and S that are equal on their
common attribute names.
o It is denoted by ⋈.
Example: Let's use the above EMPLOYEE table and SALARY table:
Input:
Output:
EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal with missing
information.
Example:
EMPLOYEE
FACT_WORKERS
EMP_NAME BRANCH SALARY
Input:
1. (EMPLOYEE ⋈ FACT_WORKERS)
Output:
o Left outer join contains the set of tuples of all combinations in R and S that are equal on
their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.
Input:
1. EMPLOYEE ⟕ FACT_WORKERS
EMP_NAME STREET CITY BRANCH SALARY
o Right outer join contains the set of tuples of all combinations in R and S that are equal on
their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.
Input:
1. EMPLOYEE ⟖ FACT_WORKERS
Output:
o Full outer join is like a left or right join except that it contains all rows from both tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples in S that have no
matching tuples in R in their common attribute name.
o It is denoted by ⟗.
Input:
1. EMPLOYEE ⟗ FACT_WORKERS
Output:
3. Equi join:
It is also known as an inner join. It is the most common join. It is based on matched data as per the
equality condition. The equi join uses the comparison operator(=).
Example:
CUSTOMER RELATION
CLASS_ID NAME
1 John
2 Harry
3 Jackson
PRODUCT
PRODUCT_ID CITY
1 Delhi
2 Mumbai
3 Noida
Input:
1. CUSTOMER ⋈ PRODUCT
Output:
1 John 1 Delhi
2 Harry 2 Mumbai
3 Harry 3 Noida
Unit Summary
11. What is relational algebra, and what is its significance in the context of relational database
management systems?
12. Explain the fundamental operations of relational algebra: selection, projection, and
Cartesian product. Provide examples of each operation.
13. Define the join operation in relational algebra. Discuss different types of joins and provide
examples.
14. How does the natural join differ from other types of joins in relational algebra? Provide an
example illustrating its usage.
15. Describe the difference between the theta join and the equijoin in relational algebra. When
would you use each type?
16. Explain the concept of set operations (union, intersection, and difference) in relational
algebra. How are they applied to relations?
17. Discuss the division operation in relational algebra. Provide an example demonstrating its
use.
18. What is the purpose of the renaming operation in relational algebra? How does it affect the
result of a query?
19. Define the intersection compatibility condition in the context of relational algebra. Why is
it important for performing set operations?
20. Explain the concept of relational completeness in relational algebra. What are the minimum
set of operations required for a relational algebra to be relationally complete?
21. Describe the concept of closure in relational algebra. How is closure related to the
completeness of relational algebra operations?
22. Discuss the concept of domain relational calculus and tuple relational calculus. How do
they differ from each other and from relational algebra?
23. How can you express complex queries using relational algebra operations? Provide an
example of a query and its equivalent representation in relational algebra.
24. Describe the process of optimizing queries using relational algebraic transformations.
Provide examples of common transformations used for query optimization.
25. Discuss the limitations of relational algebra in expressing certain types of queries or
operations. How can these limitations be overcome in practice?
Sub theme 2: Internet and web design
Introduction
Welcome to the comprehensive web design and development teaching module designed to equip you
with the essential knowledge and skills needed to ace your exit exam. This module serves as your
roadmap for revising the fundamentals of the internet and the web, as well as mastering the core
languages and technologies of web development: HTML, CSS, JavaScript, and their related concepts.
Whether you're gearing up for your exam or simply looking to solidify your understanding of these
crucial topics, this module is your go-to resource for success.
Our journey begins with a thorough review of the internet and the web, providing you with a clear
understanding of how data is transmitted and accessed across the vast network of interconnected
devices. From the underlying protocols that govern communication to the role of web servers and
browsers, you will gain insight into the infrastructure that powers the digital landscape we navigate
every day.
Next, we delve into the foundational language of web development: HTML (Hypertext Markup
Language). Through interactive lessons and practical exercises, you will refresh your knowledge of
HTML syntax, tags, and elements, mastering the art of creating well-structured web documents that
lay the groundwork for engaging online experiences.
Building upon your HTML expertise, we then explore the realm of CSS (Cascading Style Sheets), the
language responsible for styling and enhancing the visual presentation of web pages. You will revisit
CSS selectors, properties, and values, honing your skills in creating aesthetically pleasing layouts and
designs that captivate users and convey your message effectively.
No web development curriculum would be complete without a deep dive into JavaScript, the dynamic
scripting language that powers interactivity and functionality on the web. From basic scripting
concepts to advanced DOM manipulation techniques, you will sharpen your JavaScript skills and learn
how to create dynamic, responsive web experiences that delight users and elevate your projects to the
next level.
Fundamentals of Internet:
• Understand the foundational concepts of the internet, including its infrastructure, protocols,
and the role of web browsers and servers.
• Explain the process of data transmission over the internet and how information is accessed and
exchanged across networks.
HTML:
• Create well-structured web documents using HTML, incorporating essential tags and elements
to define the structure and content of web pages.
• Apply HTML best practices to ensure document validity, accessibility, and compatibility
across different browsers and devices.
CSS:
• Utilize CSS to style and enhance the visual presentation of web pages, including the use of
selectors, properties, and values to control layout, typography, and color.
• Implement CSS techniques such as flexbox and grid to create responsive and adaptive layouts
that adjust seamlessly to various screen sizes and devices.
JavaScript:
1. Introduction
The Internet is a global network of interconnected computers and devices that allows for the sharing
and exchange of information. It provides a communication infrastructure that enables usersto connect
with each other and access various services and resources. The internet is not only one network. It
consists of thousands of connected networks of varying sizes. Networks connect computers and
allow them to share files and information. It is like a road in front of your house leading to the
nearest town, then to the national highway and through highways to several other places and cities
in the country. Like the highways, electrical lines, water supply lines or railway network, Internet
connects countries and regions of the earth to one another through networked computers and
communication lines.
The internet is a loose collection of academic, government, business and individual networks linked
around the world via many communication channels. The word is coined from the phrase
‘interconnected networks.
No one person or organization runs the internet. Instead, the Internet Society (ISOC), a private not
for profit group, makes recommendations guiding its growth. Many organizations connect their
networks into the internet to make this worldwide network possible. The Internet Society decides
the protocols or rules that make the internet work, such as the Transmission Control Protocol (TCP)
and Internet Protocol (IP).
The World Wide Web, often referred to as the Web, is a system of interconnected hypertext
documents and resources accessible via the Internet. It provides a graphical interface for navigating
and accessing information, allowing users to browse websites and interact with web-based
applications. It has revolutionized the way we access and share information, connect with others,
and engage in various online activities. The terms Internet and World Wide Web are used
interchangeably in nonprofessional terms they are not the same. It is common practice to say "going
on the Internet" whenever we open any web page on a browser. However, the World WideWeb or
the Web is one of the most popular Internet services available. The Web is a collection of
interconnected documents (web pages) and other web resources, linked by hyperlinks and URLs. It
uses HTTP as an underlying protocol for information transfer, which is one of the several other
protocols available in networking theory
The internet serves as the expansive network connecting millions of computers and devices
worldwide, facilitating the exchange of data and communication through a complex system of
hardware, software, and protocols. It forms the backbone for various online services and
technologies, including email, file sharing, instant messaging, and more, extending far beyond the
Tinsae D@2024 Internet and web design
boundaries of the World Wide Web.
On the other hand, the World Wide Web (WWW) is a subset of the internet, consisting of
interconnected documents and resources accessed through web browsers. Created by Tim Berners-
Lee in 1989, the web allows users to navigate between web pages via hyperlinks, accessing a
diverse range of content such as websites, web applications, multimedia, and online services. While
the internet provides the infrastructure, the World Wide Web represents the interconnected
ecosystem of information and resources that has become integral to our digital lives.
The Web works as per the internet's basic client-server format as shown in the following image.
The servers storeand transfer web pages or information to user's computers on the network when
requested by the users. A web server is a software program which serves the web pages requested
by web users using a browser. The computer of a user who requests documents from a server is
known as a client. Browser, which is installed on the user' computer, allows users to view the
retrieved documents.
i.Security
HTTPS: HTTPS incorporates SSL (Secure Sockets Layer) or TLS (Transport Layer Security)
protocols to establish an encrypted connection between the client and server. This encryption
ensures that data transmitted over HTTPS is encrypted, making it significantly more secure. It
protects against eavesdropping, tampering, and interception of sensitive information.
ii.Encryption
HTTP: Data transmitted over HTTP is not encrypted. It is sent as plain text, which means anyone
with access to the network can potentially intercept and view the data.
HTTPS: HTTPS encrypts the data being transmitted between the client and server. The encryption
process ensures that the data is converted into a secure format that can only be decrypted by the
intended recipient (the server). This protects the confidentiality and integrity of the data.
iii.Data Integrity
HTTP: Since data transmitted over HTTP is not encrypted, it is susceptible to modification during
transit. Attackers can intercept the data and alter its contents without detection.
HTTPS: HTTPS ensures data integrity by using cryptographic mechanisms. It verifies that the data
received by the client is the same as the data sent by the server. If any modification or tampering
occurs during transit, the integrity check will fail, and the connection will be terminated.
HTTPS: HTTPS employs digital certificates issued by trusted Certificate Authorities (CAs) to
authenticate the identity of the server. This ensures that the client is communicating with the intended
and legitimate server, reducing the risk of phishing attacks and unauthorized access.
v.URL Scheme
HTTP: URLs for HTTP resources start with "http://" in the address bar of web browsers.
HTTPS: URLs for HTTPS resources start with "https://" in the address bar. The presence of "https://"
indicates that the connection is secure, and the data transmitted between the client and server is
encrypted.
In summary, while HTTP is a standard protocol for web communication, it lacks security measures
such as encryption and authentication. In contrast, HTTPS provides secure communication by
encrypting data, verifying server authenticity, and ensuring data integrity. HTTPS is essential for
protecting sensitive information, maintaining user privacy, and establishing trust in online
interactions.
The Domain Name System (DNS) is a hierarchical naming system that translates domain names into
IP addresses. The Domain Name System (DNS) operates in a hierarchical structure, which plays a
vital role in translating human-readable domain names into IP addresses that computers
Hence, the DNS hierarchy is comprised of the following five levels: Root Level Domain, Top Level
Domains (TLD), Second Level Domains (SLD), Subdomains and Hosts.
1.8.Web browser
A web browser is a software application that allows users to access and navigate the World Wide
Web (WWW). It enables the retrieval and display of web pages, files, images, videos, and other
online content. Web browsers act as a user interface for accessing and interacting with the vast
amount of information available on the internet. Web browsers play a crucial role in enabling usersto
access and interact with the vast array of information and services available on the internet.
Understanding their features and settings empowers users to customize their browsing experienceand
maximize productivity while ensuring security and privacy.
• Google Chrome: Developed by Google, known for its speed, security, and extensive
features.
• Mozilla Firefox: An open-source browser known for its privacy features,
customization options, and developer tools.
• Safari: Developed by Apple, Safari is the default browser for Apple devices, offeringa
seamless integration with the macOS and iOS ecosystems.
• Microsoft Edge: Microsoft's web browser, built on Chromium, offering fast
performance, compatibility, and integration with Windows systems.
• Opera: A feature-rich browser known for its speed, built-in VPN, ad blocker, and
unique features like sidebar extensions.
1. What is the fundamental difference between the Internet and the World Wide Web?
2. How does a web browser work, and what are the key components involved in rendering a
webpage?
3. Describe the role of HTTP and HTTPS protocols in web communication. How do they differ?
4. What is DNS (Domain Name System), and how does it facilitate internet browsing?
5. What are cookies in the context of web browsing, and how are they used by websites?
6. Explain the significance of TCP/IP in internet communication. How does it ensure data
transmission reliability?
7. Describe the difference between client-side scripting and server-side scripting. Provide examples
of each.
8. How do search engines like Google index and rank web pages?
9. What are some common security threats associated with browsing the internet, and what
measures can users take to protect themselves from these threats?
10. Can you explain the concept of IPv6 and its significance in the context of internet addressing?
HyperText Markup Language, commonly referred to as HTML, is the standard markup languageused
to create web pages. Web browsers can read HTML files and render them into visibleor
audible web pages. HTML describes the structure of a website semantically along with cues for
presentation, making it a markup language, rather than a programming language. HTML, an acronym
for Hyper Text Markup Language, specifies how the structure of a webpage will be withthe help of
various markups. It is a structured markup language that is used to create Web pages. Markup
languages like HTML bundle together codes which are elements that are used to representthe structure
and format of a document. A user agent, usually a Web browser which renders (delivers) the
document, interprets the meaning of these codes to decipher (making it into simplerhuman readable
text) how to structure or display a document. The HTML elements are made up of alphanumeric
tokens surrounded by angle brackets, for example, <B>, <HTML>, <IMG> and <HR> .
Almost all elements possess a pair of tags i.e. a start tag and an end tag. The start tag is a mnemonic
symbol for the element enclosed in ‘<’ ’>’, also known as angle brackets, for instance, the symbol
associated with bolding text is B and the start tag for this purpose is <B>. An end tag is the same as
that for a start tag, but with an exception that there exists a forward slash preceding the text symbol
of start tag: </B>. The instruction applied by an element modifies whatever content is present
between the starting and ending tags:
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
Output:
HTML (Hypertext Markup Language) has been the cornerstone of web development since its inception in the
early 1990s. As the primary language for creating web pages and applications, HTML has undergone several
revisions and updates to meet the evolving needs of developers and users alike. Each version of HTML has
brought new features, capabilities, and standards, shaping the way we interact with the web.
HTML 1.0, introduced in 1993 by Tim Berners-Lee, marked the first standardized version of HTML. It
provided a basic set of markup tags for structuring and formatting hypertext documents, laying the groundwork
for the World Wide Web as we know it today.
HTML 2.0:
HTML 2.0, released in 1995, expanded upon the foundation established by HTML 1.0. It introduced support
for forms, allowing users to interact with web pages through text fields, checkboxes, and buttons, paving the
way for more dynamic and interactive web experiences.
HTML 3.2:
HTML 3.2, introduced in 1997, further extended the capabilities of HTML, introducing support for tables,
frames, and multimedia elements such as images, audio, and video. These new features enabled developers to
create more complex layouts and incorporate multimedia content into their web pages.
HTML 4.01:
HTML 4.01, released in 1999, represented a major update to the HTML specification. It introduced stricter
rules and improved support for scripting and styling, standardizing the Document Object Model (DOM) and
introducing support for cascading style sheets (CSS), allowing for more precise control over document layout
and presentation.
HTML5:
HTML5, introduced in 2014, represents the latest evolution of the HTML specification. It introduces new
semantic elements, APIs, and multimedia capabilities, providing native support for audio and video playback,
offline storage, geolocation, canvas drawing, and responsive design. HTML5 is well-suited for building
modern web applications and multimedia-rich websites, reflecting the ever-changing landscape of web
development and the increasing demands of users and developers alike.
While getting started with HTML, you will likely encounter new—and often strange— terms. Over time
Tinsae D@2024 Internet and web design
you will become more and more familiar with all of them, but the three common HTMLterms you should
begin with are elements, tags, and attributes.
2.2.1. Elements
Before we start adding tags to our document, let’s look at the anatomy of an HTML element (its syntax)
and firm up some important terminology. HTML elements are the building blocks of webpages. They define
the structure and content of a webpage by encapsulating different parts of the page within specific tags.
Each HTML element consists of an opening tag, content, and a closingtag. The opening tag denotes the start
of an element, the closing tag marks its end, and the contentlies between the tags. Elements can be nested
within each other, creating a hierarchical structure that represents the relationship between different parts
of the webpage.
Here's an example of an HTML element: Thus, an element will look like the following:
2.2.2. Tags
An HTML tag is a component of HTML markup that is used to define elements within an HTMLdocument.
HTML tags are enclosed within angle brackets ("<" and ">") and consist of the tag name. They provide
instructions to web browsers on how to interpret and render the content withinthe tags. Here's an example of
an HTML tag:
In HTML, the capitalization of element names is not important. So <img>, <Img>, and <IMG> are all the
same as far as the browser is concerned. However, in XHTML (the stricter version of HTML) all element
names must be all lowercase in order to be valid. Many web developers havecome to like the orderliness of
the stricter XHTML markup rules and stick with all lowercase.
2.2.3. Attributes
HTML elements can also have attributes that provide additional information or modify their behavior.
Attributes are properties used to provide additional information about an element. The most common
attributes include the id attribute, which identifies an element; the class attribute, which classifies an
element; the src attribute, which specifies a source for embeddable content; and the href attribute, which
provides a hyperlink reference to a linked resource.
Attributes are defined within the opening tag, after an element’s name. Generally attributes includea name
and a value. The format for these attributes consists of the attribute name followed by an equals sign and
then a quoted attribute value.
The syntax for an attribute is as follows:
attributename="value"
Attributes go after the element name, separated by a space. In non-empty elements, attributes goin the
opening tag only:
<element attributename="value">
<element attributename="value">Content</element>
You can also put more than one attribute in an element in any order. Just keep them separatedwith
spaces:
• Class
• Title
• Style
The Id Attribute:
This is the most widely used attribute. The id attribute is used to give a unique id to an HTMLelement.
Each element in HTML with an id attribute has its own unique identity, just as each of us has our own
unique identity. Multiple elements can’t share the same id.
In the above example, it is easy to distinguish the two paragraphs with the name- id attributehaving two
different values i.e. html and python.
The class Attribute:
The class attribute is used to specify a class to an HTML element. It is not unique like the id attribute.
Multiple elements can share the same class. It is used to associate an element with astylesheet, JS.
The title Attribute:
The id attribute is used to give a title to an HTML element. When the HTML element isloading, a tooltip
of the cursor comes and shows the written title.
For example:
1. Block-Level Elements:
Block-level elements are HTML elements that create a block-level box. These elements typicallystart on a
new line and occupy the full width available within their parent container. Some common examples of
block-level elements include <div>, <p>, <h1> to <h6>, <ul>, <li>, and
<section>.
• Start on a new line: Block-level elements create a line break before and after themselves,visually
separating them from other content.
• Occupy the full width: By default, block-level elements extend horizontally to fill theentire
width of their parent container.
• Do not start on a new line: Inline-level elements do not force a line break and are renderedwithin
the same line as surrounding text or other inline elements.
• Occupy only necessary space: Inline-level elements take up only as much space asrequired
by their content, without extending to the full width of the parent container.
• Do not support width and height properties: Inline-level elements do not accept explicitwidth or
height values. Their dimensions are determined by their content.
• Inline-level elements cannot contain block-level elements but can contain other inline-level
elements.
Common use cases for inline-level elements:
• Styling specific portions of text: <span>, <strong>, <em>, and similar inline elements arecommonly
used for applying styling, such as color, font weight, or emphasis, to specific portions of text.
In conclusion, block-level elements create block-level boxes, start on new lines, and occupy thefull width
of their parent containers. They are suitable for grouping content and creating structural sections. On the
other hand, inline-level elements do not create line breaks, occupy only necessary space, and are typically
used for applying styling or inserting specific elements within text. By leveraging the characteristics and
appropriate use of these elements, you can create well-structured and visually appealing web pages.
Now that you know what HTML elements, tags, and attributes are, let’s take a look at putting together our
first web page. If anything looks new here, no worries—we’ll decipher it as we go.
Figure 2-4 shows the recommended minimal skeleton of an HTML5 document. I say “recommended”
because the only element that is required in HTML is the title. But I feel it is better, particularly for
beginners, to explicitly organize documents with the proper structural markup. And if you are writing in the
stricter XHTML, all of the following elements except metamust be included in order to be valid. Let’s take
a look at what’s going on in Figure 2-4.
1. I don’t want to confuse things, but the first line in the example isn’t an element at all; it is a document
type declaration (also called DOCTYPE declaration) that identifies this document as an HTML5
document. I have a lot more to say about DOCTYPE declarations in Chapter 10,but for this discussion,
suffice it to say that including it lets modern browsers know they shouldinterpret the document as
written according to the HTML5 specification.
2. The entire document is contained within an html element. The html element is called the root element
because it contains all the elements in the document, and it may not be contained
3. Within the html element, the document is divided into a head and a body. The head element contains
descriptive information about the document itself, such as its title, the style sheet(s) ituses, scripts, and
other types of “meta” information.
4. The meta elements within the head element provide information about the document itself. A meta
element can be used to provide all sorts of information, but in this case, it specifies the character
encoding (the standardized collection of letters, numbers, and symbols) used in the document. I don’t
want to go into too much detail on this right now, but know that there are many good reasons for
specifying the charset in every document, so I have included it as part of the minimal document
structure.
5. Also in the head is the mandatory title element. According to the HTML specification, every document
must contain a descriptive title.
6. Finally, the body element contains everything that we want to show up in the browser window.
Meta tags are HTML elements placed within the head section of a web page. They serve as metadata,
providing information about the page to various entities, including search engines and social media
platforms. While users typically do not see meta tags directly, they play a significantrole behind the scenes
in shaping how your website is displayed and understood by different systems. One of the primary benefits
of meta tags are
One of the primary benefits of meta tags is their impact on search engine optimization. Search engines use
meta tags to understand the content and relevance of a web page, which influences itsranking in search
results. Some key meta tags for SEO include:
• <title> tag: Defines the title of the web page. It appears in search engine results and browsertabs as
the clickable headline.
• <meta name="description" content="..."> tag: Provides a concise description of the page's
content. It appears in search engine results below the title, influencing users to clickon the link.
• <meta name="keywords" content="..."> tag: Specifies relevant keywords related to the page's
content, helping search engines understand the page's relevance to specific search queries.
• <meta name="robots" content="..."> tag: Instructs search engine crawlers on how to interact with
and index the page. It can specify whether to index the page, follow links, orset page restrictions.
Meta tags also play a crucial role in how your website is shared and displayed on social media platforms.
When someone shares a web page on platforms like Facebook or Twitter, meta tags provide the necessary
information to populate the post with relevant content. Some key meta tagsfor social media sharing include:
• <meta property="og:title" content="..."> tag: Specifies the title of the page when sharedon social
media platforms.
• <meta property="og:description" content="..."> tag: Provides a description of the page'scontent
when shared on social media.
• <meta property="og:image" content="..."> tag: Specifies an image to be displayedalongside the
shared link on social media platforms.
By including these meta tags, you can control how your website appears when shared on socialmedia,
ensuring a consistent and appealing representation that attracts users' attention.
Meta tags also contribute to improving the accessibility of your website. They provide additional
information to assistive technologies like screen readers, enabling them to accurately interpret andpresent
the content to users with disabilities. For example:
Example
<!DOCTYPE html>
<html>
<head>
<title>Heading Example</title>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>
A paragraph always starts on a new line, and is usually a block of text. The HTML <p> element defines a
paragraph. A paragraph always starts on a new line, and browsers automatically add some white space (a
margin) before and after a paragraph. Paragraphs are widely used for varioustypes of textual content, such
as articles, descriptions, and explanations. You can add attributes tothe <p> element to provide additional
information or control its appearance. Each paragraph of text should go in between an opening <p> and a
closing </p> tag. Here's an example of a basic paragraph without any attributes::
Example
<!DOCTYPE html>
<html>
<head>
<title>Paragraph Example</title>
</head>
<body>
<p>Here is a first paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
Class Attribute (class): Used to define a class for the paragraph, allowing you to apply CSS stylesor target
it with JavaScript.
ID Attribute (id): Provides a unique identifier for the paragraph, which can be used to refer to it
from CSS or JavaScript.
Style Attribute (style): Allows you to apply inline CSS styles directly to the paragraph. Here's anexample
of changing the font color and size:
<!DOCTYPE html>
<html>
<head>
<title>Horizontal Line Example</title>
</head>
<body>
<p>This is paragraph one and should be on top</p>
<hr />
<p>This is paragraph two and should be at bottom</p>
</body>
</html>
You can also add attributes to the <hr> element to modify its appearance or behavior. Here aresome
commonly used attributes with examples:
Width Attribute (width): Specifies the width of the horizontal line. It can be set in pixels (px) oras a
percentage of the container width.
<hr width="50%">
Size Attribute (size): Sets the height or thickness of the horizontal line. The value can be a
numeric value or one of the predefined size values: small, medium, or large.
<hr size="3">
<hr align="center">
In HTML, the line break is represented by the <br> element. It is a self-closing tag, meaning it doesn't
require a closing tag. The <br> element is used to insert a line break within a block of textor content, forcing
the text after it to start on a new line. Here's an example of a basic line break: Example:
<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<p>Hello<br />
You delivered your assignment on time.<br />
Thanks<br />
Miskir</p>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<p>Hello<br />
You delivered your assignment on time.<br />
Thanks<br />
Miskir</p>
</body>
</html>
C. Underline (<u>):
The <u> element is used to underline text.
E. Superscript (<sup>):
The <sup> element is used to display text as a superscript, typically for indicating footnotes,mathematical
exponents, or citations.
F. Subscript (<sub>):
The <sub> element is used to display text as a subscript, typically for chemical formulas,mathematical
subscripts, or annotations.
G. Code (<code>):
The <code> element is used to represent a fragment of computer code or inline code snippets.
A. Blockquote (<blockquote>):
The <blockquote> element is used to indicate a longer quotation that is separate from the maintext. It
typically renders as an indented block of text.
Code snip
<blockquote>
<p>This is a longer quotation that should be set apart from the main text.</p>
<cite>John Doe</cite>
</blockquote>
Result
The <cite> element can be used within the <blockquote> element to provide the source or authorof the
quotation.
B. Q (<q>):
The <q> element is used to mark up short inline quotations within a paragraph or sentence.
Code snip
<p>He said, <q>This is a short quotation</q>, and continued his
speech.</p>
Result
Code snip
<p>The article titled <cite>HTML Basics</cite> provides an intr
oduction to web development.</p>
Result
D.Dfn (<dfn>):
The <dfn> element is used to mark the defining instance of a term within a document. It iscommonly
used in glossaries or to provide definitions of technical terms.
Code snip
<p>The <dfn>HTML</dfn> stands for Hypertext Markup Language</p>
Result
E. Address (<address>):
The <address> element is used to represent contact information or the contact details of the authoror owner
of a document.
Code snip
<address>
<p>John Doe</p>
<p>1234 Main Street</p>
<p>City, State ZIP</p>
</address>
Result
Code snip
<bdo dir="rtl">This text is right-to-left.</bdo>
Result
By specifying the dir attribute with a value of "rtl" (right-to-left) or "ltr" (left-to-right), you canchange
the directionality of the text within the <bdo> element.
G. Abbreviation (<abbr>):
The <abbr> element is used to mark up abbreviations or acronyms within a document. It can beused to
provide the full expansion or explanation of an abbreviation.
Code snip
<p>The <abbr title="Hypertext Markup Language">HTML</abbr> is t
he standard markup language for creating web pages.</p>
Result
In the example above, the <abbr> element is used to mark the abbreviation "HTML" and provide the full
expansion using the title attribute. When the user hovers over the abbreviation, the full expansion will be
displayed as a tooltip. Including the <abbr> element helps provide additional
These quotation and citation elements help provide structure and clarity to quoted or cited contentin HTML
documents. They aid in accessibility, search engine optimization, and proper rendering across different
devices and browsers. It's important to use these elements appropriately and in accordance with their
intended purpose to ensure accurate interpretation and presentation of the quoted or cited information.
HTML comments are used to add explanatory or informational notes within the HTML code. Theyare not
displayed on the rendered web page and are intended for developers or anyone reading thecode to understand
the purpose or context of certain elements or sections. Comments are helpful for adding documentation,
reminders, or temporarily disabling code without deleting it. Here's
how you can create HTML comments:
In the example above, comments are used to provide explanations and notes within the HTML code. The
comments labeled "CSS Styles" and "JavaScript Scripts" indicate the purpose of the
linked files. The comment "Main Content" helps identify the main content section within the body. The
"TODO" comment serves as a reminder for future development tasks.
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<!-- CSS Styles -->
A. Color Values
In HTML, you can specify colors using various methods, including predefined color names, hexadecimal
color codes, RGB values, or HSL values. These color representations allow you to define the color of text,
backgrounds, borders, and other elements on your web page. Here are thedifferent ways to specify colors
in HTML:
• Predefined Color Names: HTML provides a set of predefined color names that you can use directly.
Some examples include "red," "green," "blue," "yellow," and "black." Here's how you can use a
predefined color name:
• Hexadecimal Color Codes: Hexadecimal color codes represent colors using a combination of six
hexadecimal digits (0-9 and A-F). The first two digits represent the red component, the next two
represent green, and the last two represent blue. Here's an example:
• HSL Values: HSL (Hue, Saturation, Lightness) values represent colors using three parameters:hue (0-
360), saturation (0-100%), and lightness (0-100%). Here's an example:
These methods can be applied to the color property using inline styles or in a separate CSS file todefine the
color of various HTML elements. Additionally, you can use the same color representations for other CSS
properties such as background-color, border-color, and more. By specifying colors in HTML, you can
customize the visual appearance of your web page and createa visually appealing design. It's important to
choose appropriate colors that provide good contrastand readability for your content.
In HTML, you can use CSS properties to specify colors for text, background, and borders of HTML
elements. Here are examples of how to use the color, background-color, and border-color properties to
control the color of different elements:
• Text Color:
You can use the color property to define the color of text within an HTML element. You can specify the
color using predefined color names, hexadecimal color codes, RGB values, or HSL values.
Result
• Background Color:
The background-color property is used to set the background color of an HTML element. It can beused to
give a specific color to the background of a text block, a container, or the entire page.
• Border Color:
The border-color property is used to specify the color of the border around an HTML element. It can be
combined with other border-related properties to control the style, width, and placement ofthe border.
In these examples, the style attribute is used to apply inline CSS styles to the HTML elements. However,
it's generally recommended to use external CSS files or internal <style> tags for better separation of
concerns and maintainability. By using the color, background-color, and border-colorproperties, you can
easily customize the appearance of text, background, and borders on your HTML elements, allowing for
visually appealing designs and better readability.
There are many reasons why you might want to add an image to a web page: you might want to include a
logo, photograph, illustration, diagram, or chart. There are several things to consider when selecting and
preparing images for your site but taking time to get them right will make it look more attractive and
professional. In this section you will learn how to:
A picture can say a thousand words, and great images help make the difference between an averagelooking
site and a really engaging one. Images can be used to set the tone for a site in less time than it takes to read
a description. If you do not have photographs to use on your website, there arecompanies who sell stock
images; these are images you pay to use (there is a list of stock photography websites below). Remember
that all images are subject to copyright, and you can get in trouble for simply taking photographs from
another website. Images Should...
▪ Be relevant
▪ Convey information
▪ Convey the right mood
▪ Be instantly recognizable
Tinsae D@2024 Internet and web design
▪ Fit the color palette
When using the <img> element, you can supply JPEG (.jpg or .jpeg), GIF (.gif), PNG (.png), or SVG (.svg)
files. The following is a brief description of each file type that should help you decidewhich file type to use
for your application.
▪ JPG Also known as JPEG, this is best for photographs because it offers high compressionand up to
16.8 million color combinations, but the compression algorithm is lossy, meaningthat you lose detail
every time you save the file.
▪ GIF GIF is great to use on small images that have a fixed number of colors. GIF also supports
transparent color. GIF uses lossless compression and is best for logos and worst for photos. GIF
also supports the ability to encapsulate multiple images in one file, which is commonly used to
provide animated GIFs.
▪ PNG PNG is a great all-around file type due to its lossless high compression. PNG files can be 48-
bit true color or 16-bit grayscale. PNG not only supports transparent color but also offers variable
transparency. Photos aren’t compressed to be as small as JPG photos but being lossless makes it
worth the extra size in many scenarios. You might use PNG asyour storage type for photos that you
want to edit, but when displaying them on the web, you might want to save the PNG as JPG to
achieve the best compression.
▪ SVG SVG is Scalable Vector Graphics and is great for drawings but not for photos. SVGimages can
be scaled up or down without losing detail because the file contains the instructions to draw the
image, as opposed to the other file types that contain a raster-basedimage. Raster-based images
are composed of color dots that make up the image. If you need to scale a raster-based image up
or down, you will see that in color, dots are re- sampled, and the image typically ends up looking
blocky.
Adding Images
The <img> tag is an HTML element used to display images on a web page. It is a self-closing tag,meaning
it does not have a closing tag. The <img> tag requires the src attribute, which specifies the source URL or
file path of the image. It also supports several optional attributes to provide additional information and
control the behavior and appearance of the image.
▪ By providing the file path relative to the location of the current web page file.
We will first discuss inserting the image to the webpage & simultaneously, we will understandboth the
above approaches.
Adding images on a webpage: The <img> tag is used to add or embed the images to a webpage/website.
The “img” tag is an empty tag, which means it can contain only a list of attributes and it has no closing tag.
The addition of the images improves the quality along with enhancing the design structure, appearance of
the webpage. Nowadays, a website does not directlyadd images to a web page, as the images are linked to
web pages by using the <img> tag which holds space for the image.
Syntax:
Attributes:
▪ alt: It is used to specify an alternate text for the image. It is useful as it informs the user about what
the image means and also due to any network issue if the image cannot be displayed then this
alternate text will be displayed.
▪ crossorigin: It is used to import images from third-party sites that allow cross-origin access
▪ loading: It is used to specify whether a browser should defer the loading of images until some
conditions are met or load an image immediately.
▪ longdesc: It is used to specify a URL to a detailed description of an image.
▪ referrerpolicy: It is used to specify which referrer information to use when fetching an image i.e.
no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
▪ sizes: It is used to specify image sizes for different page layouts.
Example 1: This simple example illustrates the use of the <img> tag in HTML that is used to embed the
image into the webpage.
<!DOCTYPE html>
<html>
<head>
<title>Welcome To GFG</title>
</head>
<body>
<h2>Inserting Picture</h2>
<p>This is the demo of <img> tag.</p>
<img src="img_girl.jpg">
</body>
</html>
Every image has an src attribute which tells the browser where to find the image you want to display. The
URL of the image provided points to the location where the image is stored. When the webpage loads for
the first time, then the browser gets the image from a web server and insertsit into the page. If the image is
not spotted by the browser then users will get a broken link icon. Itmight be possible if the file path is wrong
or the image got deleted from that location.
The example illustrates the use of the src attribute in the <img> tag.
Note: on the above example you can change the value of the src attribute by your own or it will
be provided by your course instructor. Here is the output of the above example:
alt: If the image cannot be displayed then the alt attribute acts as an alternative description for the image.
The value of the alt attribute is a user-defined text. It generally happens when the user, forsome reason,
cannot view it due to a slow internet connection or an error in the src attribute, or if the user uses a screen
reader.
Example 3: The example illustrates the use of the alt attribute in the <img> tag.
<!DOCTYPE html>
<html>
<head>
<title>Alt Attribute Example</title>
</head>
<body>
<p>inserted image using "img" tag and Adding image name in usi
ng "alt" attribute:</p>
<img src="" alt="Girl in a jacket">
</body>
</html>
Output:
Setting width and height of Image: The width and height attributes are used to specify the height and width
of an image. The attribute values are specified in pixels by default. The width and heightattributes are always
declared in pixels.
Example 4: The example illustrates the use of the width & height attribute in the <img> tag.
<!DOCTYPE html>
<html>
<body>
<h2>Image Size</h2>
<p>Here we specify the width and height of an image with the width an
d height attributes:</p>
<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">
</body>
</html>
Alternatively, You can use the style attribute to specify the width and height of an image.
Example 5: The example illustrates the use of the style attribute to set the width & height of an image.
<!DOCTYPE html>
<html>
<body>
<h2>Image Size</h2>
<p>Here we use the style attribute to specify the width and height of an image:</p>
</body>
</html>
Common Image Format: Here is the commonly used image file format that is supported by allthe browsers.
2. JPEG. Joint Photographic Expert Group image. .jpg, .jpeg, .jfif, .pjpeg, .pjp
The <audio> tag is an HTML element used to embed audio content within a web page. It providesa native
way to play audio files directly in the browser without the need for external plugins. You can use the
<audio> tag to add various audio formats such as MP3, WAV, or OGG to your web pages. Here's an
example of the <audio> tag with some commonly used attributes:
In this example:
▪ src: Specifies the source URL or file path of the audio file. It is a required attribute.
▪ controls: Adds default audio controls (play, pause, volume, etc.) to the audio player,allowing
users to control the playback.
▪ autoplay: Starts playing the audio automatically when the page loads.
The content placed between the opening and closing <audio> tags, in this case, "Your browser does not
support the audio element," will be displayed if the browser does not support the <audio>tag or the specified
audio format.
</audio>
The <video> tag is an HTML element used to embed video content within a web page. It providesa native
way to play video files directly in the browser without the need for external plugins. Withthe <video> tag,
you can add various video formats such as MP4, WebM, or Ogg to your web pages.
Here's an example of the <video> tag with some commonly used attributes:
<!DOCTYPE html>
<html>
<body>
<video controls autoplay loop width="640" height="360">
<source src="movie.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
</html>
In this example:
▪ src: Specifies the source URL or file path of the video file. It is a required attribute.
▪ controls: Adds default video controls (play, pause, volume, etc.) to the video player,allowing
users to control the playback.
▪ autoplay: Starts playing the video automatically when the page loads.
▪ width: Sets the width of the video player in pixels or as a percentage of the parent
container.
▪ height: Sets the height of the video player in pixels or as a percentage of the parent
container.
The content placed between the opening and closing <video> tags, in this case, "Your browser does not
support the video element," will be displayed if the browser does not support the <video>tag or the specified
video format. Here's another example demonstrating additional attributes:
</video>
Lists are used to group together related pieces of information, so they are clearly associated with each other
and easy to read. In modern web development, lists are workhorse elements, frequentlyused for navigation
as well as general content.
Humans are natural list makers, and HTML provides elements for marking up three types of lists:
▪ Unordered lists. Collections of items that appear in no particular order.
▪ Description lists. Lists that consist of name and value pairs, including but not limited to terms and
definitions.
A. Unordered lists
Unordered lists are often referred to as bulleted lists. Instead of being numbered, each element in the list
has the same marker. The markup to create an unordered list looks just like an ordered listexcept that the
list is created by using <ul>...</ul> tags rather than ol. The elements of the list are placed within <li> tags,
just as with ordered lists. Browsers have standardized on using a solid bullet to mark each item in an
unordered list by default. Text browsers usually use an asterisk forthese lists. The following input and output
example shows an unordered list. example shows the results in a browser.
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul>
</ul >
</body>
</html>
As with ordered lists, unordered lists can be customized using the type attribute or the list-style- type
property. As mentioned in the section on ordered lists, the type attribute is no longer valid forHTML5. The
bullet styles are as follows:
▪ "circle"—As compared with the disc, which most browsers render as a filled circle, this value
should generate an unfilled circle.
In this case, the values for list-style-type and for the type attribute are the same. In the following input and
output example, you see a comparison of these three types as rendered in a browser (seeFigure 2.7):
Example
</ul>
</ul>
Output
If you don’t like any of the bullet styles used in unordered lists, you can substitute an image of your own
choosing in place of them. To do so, use the list-style-image property. By setting this property, you can use
an image of your choosing for the bullets in your list. Here’s an example :
<li>Example</li>
</ul>
A nested list is a list inside another list. You can create a nested unordered list, or a nested orderedlist, or
even an ordered list nested inside an unordered one. Remember that the only direct child ofthe <u>l tag is
<li>.
Example: Nested Unordered List, It is used to nest the list items ie., a list inside another list.
<ul>
<li>DSA</li>
<ul>
<li>Array</li>
<li>Linked List</li>
<li>stack</li>
<li>Queue</li>
</ul>
<li>Web Technologies</li>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<li>Aptitude</li>
<li>Gate</li>
<li>Placement</li>
</ul>
B. Ordered lists
Ordered lists are surrounded by the <ol>...</ol> tags (ol stands for ordered list), and each item within the
list is included in the <li>...</li> (list item) tag. When the browser displays an ordered list, it numbers and
indents each of the elements sequentially. You don’t have to perform the numbering yourself and, if you
add or delete items, the browser renumbers them the next time thepage is loaded. Ordered lists are lists in
which each item is numbered or labeled with a counter ofsome kind (like letters or roman numerals).
Use numbered lists only when the sequence of items on the list is relevant. Ordered lists are good for steps
to follow or instructions to the readers, or when you want to rank the items in a list. If you just want to
indicate that something has a number of elements that can appear in any order, use an unordered list instead.
For example, the following is an ordered list of steps that explain how to boil an egg.
You can see how the list is displayed in a browser in the example bellow.
Example:
There are two customizations that are specific to ordered lists. The first enables you to change thenumbering
style for the list, and the second enables you to change the numbering itself. There are two ways to change
the numbering style: the CSS property list-style-type, and the type attribute, which is obsolete in HTML5.
If you’re creating a new ordered list, you should always use the CSSproperty, however, you may see existing
Web pages in which the type attribute is used instead.
Attributes:
▪ compact: It defines the list should be compacted (compact attribute is not supported in HTML5.
Use CSS instead.).
▪ reversed: It defines that the order will be descending.
▪ start: It defines from which number or alphabet the order will start.
▪ type: It defines which type(1, A, a, I, and i) of the order you want in your list of numeric,alphabetic,
or roman numbers.
You can specify types of numbering in the <ol> tag using the style attribute, like this:
If you were to set the list style type upper-roman to the to the <ol> tag, as follows, it wouldappear in a
browser as shown in Figure 2:12
<li>Lundi</li>
<li>Mardi</li>
<li>Mercredi</li>
<li>Jeudi</li>
<li>Vendredi</li>
<li>Samedi</li>
<li>Dimanche</li>
</ol >
Output:
Let me digress briefly to talk about how you can use Chrome’s Developer Tools to edit styles onthe fly. If
you want to see what the list in Figure 5.2 looks like with the lower-roman list style, you can change the
style attribute directly and see the results. Just open the developer tools, make sure the elements tab is open,
and then click on the style attribute of the <ol> tag. You canthen edit the attribute and see the page change
instantly. The updated developer tools window isshown in Figure 2:13
You can also use the list-style-type property with the <li> tag, changing the numbering type in themiddle of
the list, but you need to change every list item following it if you want them all to have the same new type.
Using the start attribute, you can specify the number or letter with which to start your list. The default
starting point is 1, of course. You can change this number by using start.
<ol start="4">, for example, would start the list at number 4, whereas <ol style="list-style-type: lower-
alpha"start="3"> would start the numbering with c and move through the alphabet from there. The value
for the start attribute should always be a decimal number, regardless of the numbering style being used. For
example, you can list the last six months of the year and start numbering with the Roman numeral VII as
follows. The results appear in Figure 2:14
Example:
st<
Figure 2-14 An ordered list with an alternative numbering style and starting number.
a nested ordered list is a list that has a list inside another list.
Output :
C. Definition Lists
Definition lists differ slightly from other lists. Each list item in a definition list has two parts:
▪ A term
Each part of the glossary list has its own tag: <dt> for the term (definition term ), and <dd> forits definition
(definition description). <dt> and <dd> usually occur in pairs, although most browsers can handle single
terms or definitions. The entire glossary list is indicated by the tags
<dl>...</dl> (definition list).
The following is a glossary list example with a set of herbs and descriptions of how they grow(see Figure
2.14):
Example :
<dt>Basil</dt>
ur
is heavenly</dd>
stab
The basic approach with table creation is that you represent tabular data in a linear fashion, specifying what
data goes in which table cells using HTML tags. In HTML, tables are created from left to right and top to
bottom. You start by creating the upper-left cell and finish with the bottom-right cell. This will all become
clearer when you see some actual table code .
Table Parts
▪ The caption indicates what the table is about: for example, “Voting Statistics, 1950–1994,” or
“Toy Distribution Per Room at 1564 Elm St.” Captions are optional.
▪ The table headings label the rows, columns, or both. Usually they’re in an emphasized font that’s
different from the rest of the table. They’re optional.
▪ Table cells are the individual squares in the table. A cell can contain normal table data or a table
heading.
▪ Table data is the values in the table itself. The combination of the table headings and table data
makes up the sum of the table.
<table>
</table>
Here’s the code that produces the table shown in Figure 10.1. Don’t be concerned if you don’t know what
all this means right now. For now, notice that the table starts with a <table> tag and its attributes and ends
with a </table> tag:
</tr>
<tr>
<td>Alison</td>
<td>5'4"</td>
<td>140</td>
<td>Blue</td>
</tr>
<tr>
<td>Tom</td>
<td>6'0"</td>
<td>165</td>
<td>Hazel</td>
</tr>
<tr>
<td>Susan</td>
<td>5'1"</td>
<td>97</td>
<td>Brown</td>
</tr>
Tinsae D@2024 Internet and web design
</table >
<tr>
<th>Name</th>
<th>Height</th>
<th>Weight</th>
<th>Eye Color</th>
</tr>
The top row is followed by three rows of data cells, which are coded as follows:
<td>5'4"</td>
</tr>
</tr>
<td>5'1"</td>
</tr>
As you’ve seen, you can place the headings along the top edge by defining the <th> elements inside
the first row. Let’s make a slight modification to the table. You’ll put the headings along the left edge of
the table instead. To accomplish this, put each <th> in the first cell in each row and followit with the data
that pertains to each heading. The new code looks like the following:
</tr>
<td>5'4"</td>
<td>6'0"</td>
<td>5'1"</td>
</tr>
</tr>
Output:
Figure 2-17 An example of a table that includes headings in the leftmost column.
Captions
Table captions tell your visitor what the table is for. The <caption> element, created just for this purpose,
displays the text inside the tag as the table caption (usually centered above the table). Although you could
use a regular paragraph or a heading as a caption for your table, tools that process HTML files can extract
<caption> elements into a separate file, automatically number them, or treat them in special ways simply
because they’re captions.
If you don’t want a caption, it’s optional. If your table is understandable without a caption or you have
described it in some other location, you can leave it off.
<table>
<caption>Vital Statistics</caption>
<tr >
You can include details inside a caption to provide additional information about the table that is
hidden by default. When you include details, you need to also include a summary that acts as a title for the
additional details. Chrome, Safari, and Opera all support showing and hiding content with the <detail> and
<summary> tags. You can use the <details> and <summary> tags inside the
<caption> tag:
<caption>
<details>
<summary>Vital Statistics</summary>
<p>This table includes the name, height, and, weight of various employees.</p>
</details>
</caption>
Figure 2.18 shows a <detail> element that has been clicked on to show the hidden content.
HTML forms provide a way for users to interact with a website by submitting data. HTML Formsare used
to select different kinds of user input. HTML forms are used to pass data to a server. Theyare essential for
capturing user input, such as text, selections, and file uploads. HTML forms consist of various form
elements, including input fields, checkboxes, radio buttons, dropdown lists,and buttons. These elements are
configured using attributes to define their behavior and appearance. An HTML form can contain input
elements like text fields, checkboxes, radio-buttons,submit buttons and more. HTML provides a range of
form elements that allow developers to createinteractive forms for collecting user input. Each form element
is configured using various attributes to define its behavior and appearance. In addition to the standard
HTML form elements,HTML5 introduced new form elements and attributes that enhance the form-building
process. Let's
Example
</form>
• <form>: Defines a container for form elements. Wraps all form elements and provides thenecessary
context for form submission.
• The form attributes
• action: Specifies the URL where the form data is submitted.
• method: Specifies the HTTP method used for form submission (e.g., "GET" or"POST").
2.10.1. HTML Forms - The Input Element
The most important form element is the <input> element. The <input> element is used to select user
information. An <input> element can vary in many ways, depending on the type attribute. An <input>
element can be of type text field, checkbox, password, radio button, submit button, and more. The most
common input types are described below.
A. Text Fields
<input type="text"> defines a one-line input field that a user can enter text or alphanumericcharacters. The
default width of a text field is 20 characters. :
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeh
older="Enter your username" required maxlength="20">
</form>
• type="text": Specifies that the input field should accept text input.
• id="username": Assigns a unique identifier to the input field, which can be used toassociate
it with labels or perform JavaScript manipulations.
• name="username": Provides a name for the input field. When the form is submitted, thisname-
value pair will be sent to the server.
• placeholder="Enter your username": Displays a hint or example value within the inputfield to
guide users on what information to enter.
• required: Specifies that the input field must be filled out before the form can be submitted. It
enforces mandatory user input.
• maxlength="20": Sets the maximum number of characters that can be entered into theinput
field. In this case, the username is limited to 20 characters.
This <input type="text"> example demonstrates the usage of attributes to define the behavior and
appearance of the text input field. Users will see a labeled input field where they can enter their username.
The required attribute ensures that the field cannot be left blank, and the maxlengthattribute limits the input
to a maximum of 20 characters. The placeholder text provides additional guidance to users regarding the
expected input format.
B. Password Field
The <input type="password"> element is used to create a password input field in HTML. It masksthe user's
input, displaying asterisks or bullets instead of the actual characters. This helps protect sensitive
information, such as passwords or PINs. Here's an example of <input type="password">with attributes and
a description.
Note: The characters in a password field are masked (shown as asterisks or circles).
C. Radio Buttons
The <input type="radio"> element is used to create a set of radio buttons in HTML. Radio buttonsallow
users to select a single option from a group of mutually exclusive choices. Here's an example of <input
type="radio"> with attributes and a description:
<form>
<label>Preferred Language:</label>
<input type="radio" id="english" name="language" value="
english" checked>
<label for="english">English</label>
<input type="radio" id="spanish" name="language" value="s
panish">
<label for="spanish">Spanish</label>
</form>
• type="radio": Specifies that the input field should be rendered as a radio button.
• id="english" and id="spanish": Assigns unique identifiers to each radio button. TheseIDs are used
to associate the labels with the corresponding radio buttons.
• name="language": Provides a common name for the radio buttons. This ensures that only one
option can be selected within the same group.
• value="english" and value="spanish": Assigns a value to each radio button. When theform is
submitted, the selected value will be sent to the server.
• checked: Specifies the default selected radio button. In this case, the "English" option ispre-
selected.
D.Checkboxes
The <input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options of
a limited number of choices. Here's an example of <input type="checkbox"> with attributes and a
description:
<form>
<label for="option1">Option 1:</label>
<input type="checkbox" id="option1" name="options[]" value="op
tion1">
This <input type="checkbox"> example demonstrates the usage of attributes to create a group of
checkboxes. Users will see labeled checkboxes for "Option 1," "Option 2," and "Option 3." Theycan select
one or more checkboxes based on their preferences. The name attribute groups the checkboxes together,
and the value attribute determines the value associated with each checkbox. Upon form submission, the
selected values will be sent to the server as an array, indicated by the name attribute using square brackets
[].
E. Submit Button
A submit button is used to send form data to a server. The data is sent to the page specified in the form's
action attribute. The file defined in the action attribute usually does something with the received input:
If you type some characters in the text field above, and click the "Submit" button, the browser willsend your
input to a page called "demo_form_action.asp". The page will show you the received input.
The <textarea> element is used to create a multi-line text input field in HTML. It allows users to enter and
edit larger amounts of text. Here's an example of <textarea> with attributes and a description:
<form>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="30" placeho
lder="Enter your message" required></textarea>
</form>
In this example, we have a textarea for capturing a message from the user. Let's break down theattributes
and their significance:
• rows="4": Specifies the visible number of rows (lines) for the textarea. In this case, thetextarea
will display four rows.
This <textarea> example demonstrates the usage of attributes to create a multi-line text input field.Users will
see a labeled textarea where they can enter their message. The rows and cols attributes control the size of
the textarea, specifying the visible number of rows and columns. The placeholder attribute provides
additional guidance to users regarding the expected input. The required attribute ensures that the textarea
cannot be left blank before form submission.
<form>
<label for="country">Country:</label>
<select id="country" name="country">
<option value="usa">Ethiopia</option>
<option value="canada">USA</option>
<option value="uk">UK</option>
<option value="australia">Australia</option>
</select>
</form>
In this example, we have a select menu for choosing a country. Let's break down the attributes and their
significance:
• <option> elements: Represent the available options within the select menu. Each <option>element
contains a value attribute and the text content that represents the option. Users canchoose one of
these options.
The selected option in the select menu will be sent to the server upon form submission. By default,the first
option (<option>) in the list is displayed as the initially selected option. In the example, "Ethiopia" will be
the initially selected option. This <select> example demonstrates the usage of attributes to create a select
menu in HTML. Users will see a labeled drop-down list where they can choose a country. The available
options are represented by the <option> elements. The selected option will be sent to the server when the
form is submitted, associated with the specified name.
2.10.4. Button
The <button> element is used to create a clickable button in HTML. It allows users to trigger an action or
perform an operation. Here's an example of <button> with attributes and a description:
<form>
<button type="button" id="submitBtn" onclick="submitForm()">Logi
n</button>
</form>
• type="button": Specifies that the button element should be rendered as a regular button.It is used
to perform custom actions or trigger JavaScript functions.
• onclick="submitForm()": Specifies the JavaScript code or function to be executed whenthe button
is clicked. In this example, the submitForm() function will be called.
• Button content: The text "Submit" is the content of the button, which is displayed to theuser.
When the button is clicked, it triggers the JavaScript function specified in the onclick attribute. The function
can perform various actions, such as validating form data, manipulating the DOM, or initiating an AJAX
request.
<form>
<fieldset>
<legend>Contact Information</legend>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="website">Website:</label>
<input type="url" id="website" name="website">
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone">
In this example, we have a <fieldset> element that groups related form fields together, and a
<legend> element that provides a caption or title for the fieldset. Inside the fieldset, there arevarious
input fields with different types and attributes.
The HTML <div> element is a block level element that can be used as a container for grouping other HTML
elements. The <div> element has no special meaning. Except that, because it is a block level element, the
browser will display a line break before and after it. When used togetherwith CSS, the <div> element can
be used to set style attributes to large blocks of content. Anothercommon use of the <div> element, is for
document layout. It replaces the "old way" of defining layout using tables. Using <table> elements for
layout is not the correct use of <table>. The purpose of the <table> element is to display tabular data.
The HTML <span> element is an inline element that can be used as a container for text. The
<span> element has no special meaning. When used together with CSS, the <span> element can be used to
set style attributes to parts of the text.
Output
In this example, we have a <div> element with the attributes id="container" and class="wrapper". Inside the
<div>, there is an <h1> element and another <div> element with the class "content". Within the "content"
<div>, there are two <p> elements. The <span> element with the class "highlight" is used within the <h1>
and one of the <p> elements. Let's break down the example:
The usage of <div> and <span> elements in combination provides flexibility in structuring and styling the
content within HTML documents, allowing you to create visually appealing and well-organized web pages.
HTML5 offers new semantic elements to clearly define different parts of a web page:
Tag Desc
Defines a header for a document
header
or a section
Defines a container for
nav
navigation links
section Defines a section in a document
Defines an independent self-
article
contained article
Defines content aside from the
aside
content (like a sidebar)
Defines a footer for a document
footer
or a section
details Defines additional details
Defines a heading for the details
summary
element
Below is an example of a simple website layout using HTML5. This example includes a header,navigation
menu, main content area, sidebar, and footer.
<!DOCTYPE html>
<html>
<head>
<title>Simple Website Layout</title>
header {
background-color: #333;color: #fff;
text-align: center;padding: 10px;
}
nav {
background-color: #444;color: #fff;
text-align: center;padding: 10px;
}
nav a {
color: #fff;
text-decoration: none;padding: 5px 10px;
}
nav a:hover {
background-color: #555;
}
.container {
display: flex; flex-wrap: wrap; max-width: 1200px;
main {
flex: 3; padding: 20px;
}
aside {
flex: 1;
background-color: #f5f5f5;padding: 20px;
}
footer {
background-color: #333;color: #fff;
text-align: center;padding: 10px; clear: both;
}
</style>
</head>
<body>
<header>
<h1>Simple Website</h1>
</header>
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Contact</a>
</nav>
<div class="container">
</p>
</main>
<aside>
<h3>Side Bar</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipisci
ng elit. Nulla eget nulla vel nisi commodo rutrum in at nunc.
</p>
</aside>
</div>
<footer>
<p>© 2023 Simple Website. All rights reserved.</p>
</footer>
</body>
The above example demonstrates a simple website layout using HTML5 and basic CSS styling.
Let's break down the different components of the layout:
▪ <!DOCTYPE html>: This line specifies the document type and version, indicating that thedocument
follows the rules of HTML5.
▪ <html>: The root element of the HTML document, encompassing all the content.
▪ <head>: Contains metadata about the document, such as the page title and links to external
stylesheets.
▪ <title>: Specifies the title of the webpage that appears in the browser's title bar or tab.
▪ <style>: This section includes inline CSS code that defines the styles for various elements used in
the layout.
The output:
Overall, this example serves as a foundation for building a simple, responsive, and visually appealing
website layout using HTML5 and basic CSS styling techniques. More elements, content,and styles can be
added to create a complete and fully functional website.
The div element is a block level element, designed for grouping HTML elements. But layout canbe designed
using <div> elements, because CSS can position and style <div> elements. The following example uses
five <div> elements to create a multiple column layout:
Example
<!DOCTYPE html>
<html>
<body>
<div id="container" style="width:500px">
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">Main Title of Web Page</h1></div>
<div id="menu" style="background-color:#FFD700;height:200px;widt
h:100px;float:left;">
<b>Menu</b><br>
HTML<br>
CSS<br>
JavaScript</div>
</div>
</body>
</html>
The purpose of the <table> element is to display tabular data. But layout can be designed using
<table> element, because all table elements can be styled with CSS. The following example usesa table
with 3 rows and 2 columns - the first and last row spans 2 columns using the colspan attribute:
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
CSS is the acronym for "Cascading Style Sheet". It's a style sheet language used for describing
the presentation of a document written in a markup language like HTML. CSS helps the web
developers to control the layout and other visual aspects of the web pages. CSS plays a crucial
role in modern web development by providing the tools necessary to create visually appealing,
accessible, and responsive websites.
CSS Versions
Since the inception of CSS, several versions have come into existence. Some of the notable
versions include:
• CSS1 (Cascading Style Sheets Level1) - The initial version of CSS, released in
December 1996. CSS1 provided basic styling capabilities for HTML documents,
including properties for text, colors, backgrounds, margins, and borders.
• CSS2 (Cascading Style Sheets Level2) - Released in May 1998, CSS2 introduced new
features such as positioning, z-index, media types, and more advanced selectors like
attribute selectors and child selectors.
• CSS2.1 - The version 2.1, published as a W3C Recommendation in June 2011, clarified
and refined CSS2, addressing inconsistencies and ambiguities in the specification. CSS2.1
focused on improving interoperability among web browsers.
• CSS3 (Cascading Style Sheets Level 3) - CSS3 is a collection of modules that extend the
capabilities of CSS. It introduces numerous new features and enhancements, including
advanced selectors, multiple column layouts, animations, transformations, gradients,
shadows, and more.
• CSS4 (Cascading Style Sheets Level 4) - CSS4 is an ongoing effort to extend CSS3 with
new features and enhancements.
Each version of CSS builds upon the previous ones, adding new features and refining existing
capabilities to meet the evolving needs of web developers and designers. CSS is referred as just
CSS now, without a version number.
Components of CSS
CSS works by associating rules with HTML elements. A CSS rule contains two main parts:
Sample Code
Just to give you a little excitement about CSS, here is a sample CSS snippet for your reference.
<html>
<head>
<title>CSS Tutorial</title>
<style>
h1 {
color: #36CFFF;
}
p{
font-size: 1.5em;
color: white;
}
div {
border: 5px inset gold;
background-color: black;
width: 300px;
text-align: center;
}
</style>
</head>
<body>
<div>
<h1>Hello World!</h1>
<p>This is a sample CSS code.</p>
</div>
</body>
</html>
• h1, p, and div are the selectors that target the <h1>, <p>, and <div> elements.
• color, font-size, border, background-color, width, and text-align are the properties.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what
background images or colors are used, layout designs,variations in display for different devices
and screen sizes as well as a variety of other effects.
CSS is easy to learn and understand but it provides powerful control over the presentation of an
HTML document. Most commonly, CSS is combined with the markup languages HTML or
XHTML.
Advantages of CSS
• CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages
as you want.
• Pages load faster − If you are using CSS, you do not need to write HTML tag attributes
every time. Just write one CSS rule of a tag and apply it to all the occurrences of that tag.
So less code means faster download times.
• Easy maintenance − To make a global change, simply change the style, and all elements
in all the web pages will be updated automatically.
• Superior styles to HTML − CSS has a much wider array of attributes than HTML, so
you can give a far better look to your HTML page in comparison to HTML attributes.
• Multiple Device Compatibility − Style sheets allow content to be optimized for more
than one type of device. By using the same HTML document, different versions of a
website can be presented for handheld devices such as PDAs and cell phones or for
printing.
• Global web standards − Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages to
make them compatible to future browsers.
CSS – Syntax
• Selector − A selector is an HTML tag at which a style will be applied. This could be any
tag like <h1> or <table> etc.
• Property − A property is a type of attribute of HTML tag. Put simply, all the HTML
attributes are converted into CSS properties. They could be color, border etc.
• Value − Values are assigned to properties. For example, color property can have value
either red or #F1F1F1 etc.
Here table is a selector and border is a property and given value 1px solid #C00 is the value of
that property.
You can define selectors in various simple ways based on your comfort. Let me put these selectors
one by one.
This is the same selector we have seen above. Again, one more example to give a color to all level
1 headings −
h1 {
color: #36CFFF;
}
Rather than selecting elements of a specific type, the universal selector quite simply matches the
name of any element type −
* {
color: #000000;
}
This rule renders the content of every element in our document in black.
Suppose you want to apply a style rule to a particular element only when it lies inside a particular
element. As given in the following example, style rule will apply to <em> element only when it
lies inside <ul> tag.
ul em {
color: #000000;
}
The Class Selectors
You can define style rules based on the class attribute of the elements. All the elements having
that class will be formatted according to the defined rule.
.black {
color: #000000;
}
This rule renders the content in black for every element with class attribute set to black in our
document. You can make it a bit more particular. For example −
h1.black {
color: #000000;
}
This rule renders the content in black for only <h1> elements with class attribute set to black.
You can apply more than one class selectors to given element. Consider the following example −
The ID Selectors
You can define style rules based on the id attribute of the elements. All the elements having
that id will be formatted according to the defined rule.
#black {
color: #000000;
}
This rule renders the content in black for every element with id attribute set to black in our
document. You can make it a bit more particular. For example −
h1#black {
color: #000000;
}
This rule renders the content in black for only <h1> elements with id attribute set to black.
The true power of id selectors is when they are used as the foundation for descendant selectors,
For example −
#black h2 {
color: #000000;
}
In this example all level 2 headings will be displayed in black color when those headings will lie
with in tags having id attribute set to black.
You have seen the descendant selectors. There is one more type of selector, which is very similar
to descendants but have different functionality. Consider the following example −
body > p {
color: #000000;
This rule will render all the paragraphs in black if they are direct child of <body> element. Other
paragraphs put inside other elements like <div> or <td> would not have any effect of this rule.
You can also apply styles to HTML elements with particular attributes. The style rule below will
match all the input elements having a type attribute with a value of text −
input[type = "text"] {
color: #000000;
}
The advantage to this method is that the <input type = "submit" /> element is unaffected, and the
color applied only to the desired text fields.
You may need to define multiple style rules for a single element. You can define these rules to
combine multiple properties and corresponding values into a single block as defined in the
following example −
h1 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
For a while, don't bother about the properties mentioned in the above block. These properties will
be explained in the coming chapters and you can find complete detail about properties in CSS
References
Grouping Selectors
You can apply a style to many selectors if you like. Just separate the selectors with a comma, as
given in the following example −
h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
This define style rule will be applicable to h1, h2 and h3 element as well. The order of the list is
irrelevant. All the elements in the selector will have the corresponding declarations applied to
them.
CSS - Selectors
CSS selectors are patterns used to select and style HTML elements on a web page. They allow
you to target specific elements or groups of elements to apply styles like colors, fonts, margins,
and more. CSS selectors are a fundamental part of Cascading Style Sheets (CSS), which is a
language used to control the presentation and layout of web documents.
The element or elements that are selected by the selector are referred to as subject of the selector.
If same CSS is used by more than one selector, then these selectors can be combined together to
form a selector list. Thus the CSS rule is applied to all the individual selectors.
For example, if the same CSS, color: crimson is applied to p element and .sample class, it is
written as:
p {
color: crimson;
}
.sample {
color: crimson;
}
But, we can combine these two rules into one selector list, by adding a comma to separate them
as shown below:
p, .sample {
color: crimson;
}
Following syntax will be deemed invalid, as one of the selector is invalid (..sample - is an incorrect
way of defining a class).
p {
color: crimson;
}
..sample {
color: crimson;
}
p, ..sample {
color: crimson;
}
• A white space is acceptable before or after the comma in a selector list declaration.
• If any of the selectors in the selector list is invalid, the whole rule gets ignored and deemed
invalid.
• It is advisable to define each selector in a new line, as it makes it more legible.
CSS Selector - Type Selector
h1 {
text-decoration-line: underline;
}
<html>
<head>
<style>
div {
border: 5px inset gold;
width: 300px;
text-align: center;
}
p {
color: green;
}
h1 {
text-decoration-line: underline;
}
</style>
</head>
<body>
<div>
<h1>Type selector</h1>
<p>div with border and text-aligned to center</p>
<p>paragraph with green color</p>
<p>h1 with an underline</p>
</div>
</body>
</html>
CSS Selector - Class Selector
A class selector targets an element with a specific value for its class attribute.
.style-h1 {
text-decoration-line: underline;
}
Following example demonstrates the use of a class selector, where .style-p, .style-h1 and .style-
div are class selectors:
<html>
<head>
<style>
.style-div {
border: 5px inset gold;
width: 300px;
text-align: center;
}
.style-p {
color: green;
font-size: 25px;
}
.style-h1 {
text-decoration-line: underline;
}
</style>
</head>
<body>
<div class="style-div">
<h1 class="style-h1">class selector</h1>
<p class="style-p">class .style-p applied</p>
<p>No class applied on this p element</p>
</div>
</body>
</html>
CSS Selector - ID Selector
#style-p {
color: green;
font-size: 25px;
}
Following example demonstrates the use of an id selector, where #style-p, #style-h1 and #style-
div are the id selectors applied on the elements:
<html>
<head>
<style>
#style-div {
border: 5px inset purple;
width: 300px;
text-align: center;
background-color: lightgoldenrodyellow;
}
#style-p {
color: green;
font-size: 25px;
}
#style-h1 {
text-decoration-line: underline;
color: red;
}
</style>
</head>
<body>
<div id="style-div">
<h1 id="style-h1">ID selector</h1>
<p id="style-p">id #style-p applied</p>
<p>No id applied on this p element</p>
</div>
</body>
</html>
You can also specify the element with an attribute having a specific value.
a[href="https://www.tutorialspoint.com"] {
background-color: peachpuff;
}
<html>
<head>
<style>
a[target] {
background-color: peachpuff;
color: blueviolet;
font-size: 2em;
}
</style>
</head>
<body>
<h2>Attribute selector</h2>
<p>Styling applied to anchor element with target attribute:</p>
<a href="#">Tutorialspoint</a>
<a href="#" target="_blank">google</a>
<a href="#" target="_self">wikipedia</a>
</body>
</html>
A pseudo-class selector is used to style a specific state of an element, such as :hover is used to
style an element when hovered.
a :hover {
background-color: peachpuff;
color: green;
font-size: 2em;
}
<html>
<head>
<style>
a:hover {
background-color: peachpuff;
color: green;
font-size: 2em;
}
</style>
</head>
<body>
<h2>Pseudo-class selector</h2>
<p>Styling applied to anchor element with a pseudo-class:</p>
<a href="#">Tutorialspoint</a>
</body>
</html>
A pseudo-element selector is used to style a specific part of an element rather than the element
itself.
a::before {
content: url();
}
<html>
<head>
<style>
a::before {
content: url('images/smiley.png');
}
a::after {
content: " Pseudo-element ::after applied";
color: red;
background-color: chartreuse;
}
Combinator shows the relationship between the selectors. Two or more simple selectors can be
combined using a combinator, to form a selector. You can read more about combinator here.
Following example demonstrates the use of a descendant selector (space) and child combinator:
<html>
<head>
<style>
/* style applied to only div */
div {
border: 2px solid black;
width: 300px;
}
/* style applied to all li elements directly under ul */
ul li {
background-color: lightpink;
color: purple;
font-size: 1.5em;
padding: 5px;
margin-right: 15px;
}
Universal selector, denoted by an asterisk mark (*), is a special selector that matches any and all
elements in an HTML document.
As per the above syntax, the universal selector is used to apply a margin and padding of 0 to all
HTML elements.
<html>
<head>
<style>
* {
background-color: peachpuff;
color: darkgreen;
font-size: 25px;
}
</style>
<div>Parent element
<p>Child paragraph 1</p>
<p>Child paragraph 2</p>
</div>
<p>Paragraph 3</p>
</body>
</html>
CSS - Inclusion
There are four ways to associate styles with your HTML document. Most commonly used
methods are inline CSS and External CSS.
screen
tty
tv
projection Specifies the device the document will be displayed on.
media handheld Default value is all. This is an optional attribute.
print
braille
aural
all
Inline CSS - The style Attribute
You can use style attribute of any HTML element to define style rules. These rules will be applied
to that element only. Here is the generic syntax −
Attributes
Example
Following is the example of inline CSS based on the above syntax − <html>
<head>
</head>
The <link> element can be used to include an external stylesheet file in your HTML document.
An external style sheet is a separate text file with .css extension. You define all the Style rules
within this text file and then you can include this file in any HTML document using <link>
element.
<head>
<link type = "text/css" href = "..." media = "..." />
</head>
Attributes
screen
tty Specifies the device the document will be displayed on.
media
tv Default value is all. This is optional attribute.
projection
Example
Consider a simple style sheet file with a name mystyle.css having the following rules −
h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
Now you can include this file mystyle.css in any HTML document as follows −
<head>
<link type = "text/css" href = "mystyle.css" media = " all" />
</head>
Imported CSS - @import Rule
@import is used to import an external stylesheet in a manner similar to the <link> element. Here
is the generic syntax of @import rule.
<head>
@import "URL";
</head>
Here URL is the URL of the style sheet file having style rules. You can use another syntax as
well −
<head>
@import url("URL");
</head>
Following is the example showing you how to import a style sheet file into HTML document −
<head>
@import "mystyle.css";
</head>
A border, in the context of design and styling, refers to a decorative or functional element that
surrounds the content of an object, such as a text box, image, or any other HTML element on a
web page.
The border property is used to create a border around an element, such as a div, image, or text.
It allows you to customize the appearance of the border, including its color, width, and style.
Borders play a vital role in the overall aesthetics and design of the webpage.
Importance of borders
Following table describes the various properties of border, their description and default values
they hold:
The border-style property is one of the essential properties of border. Following values can be
passed to border-style:
Value Description
none No border
The property border-style can be exclusively specified for each single-side. The same set of
values can be passed to each single-side for border-style:
• border-top-style
<html>
<head>
<style>
p {border-top-style: dotted; border-right-style: solid; border-bottom-
style: dashed; border-left-style: double;
padding: 2em;}
</style>
</head>
<body>
<h2>border-style (single-side)</h2>
<p>Different border styles on all sides.</p>
</body>
<html>
CSS BorderS - width Property
The border-width property is next in line after setting border style. Following values can be
passed to border-width:
Value Description
Declare a border-style before declaring border-width, else the border effect will not be seen.
<html>
<head>
<style>
The property border-width can be exclusively specified for each single-side. The same set of
values can be passed to each single-side for border-width:
• border-top-width
• border-right-width
• border-bottom-width
• border-left-width
<html>
<head>
<style>
p {border-style: solid;
border-top-width: thin;
border-right-width: thick;
border-bottom-width: medium;
border-left-width: 10px;
The border-color is the third constituent property of border. It sets the color of the border.
Value Description
Declare a border-style before declaring border-color, else the border effect will not be seen.
<html>
<head>
<style>
p.color1 {border-color: red;}
p.hexa1 {border-color: #00ff00;}
p.color2 {border-style: dashed; border-color: red;}
p.hexa2 {border-style: solid; border-color: #00ff00;}
</style>
</head>
<body>
<h2>border-color without <i>border-style</i> property</h2>
The property border-color can be exclusively specified for each single-side. The same set of
values can be passed to each single-side for border-color:
• border-top-color
• border-right-color
• border-bottom-color
• border-left-color
<html>
<head>
<style>
p {border-style: solid;
border-top-color: red;
border-right-color: #0000ff;
border-bottom-color: rgb(100,123,111);
border-left-color: rgba(50,123,111,0.4);
padding: 0.5in;}
</style>
</head>
<body>
<h2>Different border color on all sides</h2>
<p>Check the border colors!!!</p>
</body>
</html>
CSS - border-block
The CSS shorthand property border-block is a logical property that defines width, style and color
of both the start and end in the block dimension at once.
• border-block-color
• border-block-style
• border-block-width
Syntax
border-block: <border-block-width> || <border-block-style> || <border-
block-color>
Applies to
<html>
<head>
<style>
.border-demo {
width: 300px;
height: 150px;
margin: 20px;
padding: 20px;
background-color: #f0f0f0;
border-block: 5px dotted #3498db;
}
.add-demo {
font-size: 18px;
color: #111;
The following example demonstrates the CSS properties border-block with vertical writing
mode.
<html>
<head>
<style>
.vertical-border {
writing-mode: vertical-rl;
direction: ltr;
width: 150px;
height: 250px;
margin: 50px;
padding: 20px;
background-color: #f0f0f0;
border-block: 1rem solid red;
}
.add-style {
font-size: 18px;
color: #333;
}
</style>
</head>
<body>
<div class="vertical-border">
<p class="add-style">This is a vertical bordered element with a solid
red border.</p>
</div>
</body>
</html>
This chapter discusses about the margins in CSS. Margins are used to create space around an
element.
They define the amount of space between an element's border and adjacent elements.
Possible Values
Value Description
% The margin is specified in percentage (%) of the width of the containing element
You can specify margins for all sides at once (top, right, bottom, left) or set specific values for
individual sides.
You can set the margin for each side individually, which is as follows:
Property Description
margin a shorthand property that sets the margin properties in one declaration
margin-
sets the bottom margin of the element
bottom
margin-block sets logical block start and end margins for an element.
CSS padding is a property that is used to create spacing and add additional space inside the
boundary of an element. This chapter will discuss about the CSS padding property.
• allows you to specify how much space should appear between the content of an element
and its border.
• It adds extra space inside the element, effectively increasing or decreasing the distance
between the content and the border.
• has a default value of 0 (zero). So if you don’t set a padding value then no padding should
appear around the element.
• Negative values are not allowed.
The order of the padding properties is important, and follows this pattern:
The following diagram demonstrates the various padding properties for reference:
Let us see a simple example to set padding with a single length value, which is applied equally to
all four padding sides. Here we add 5 px padding on h2 element :
<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
Adding padding to an element makes it look clear and attractive. Observe the following example
for the difference between padding and no padding:
<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
#myDIV {border: 2px solid;}
h2 {padding: 2em; background-color: skyblue}
h3 {background-color: silver;}
</style>
</head>
<body>
<div id="myDIV">
<h2>The padding can be seen around the text.</h2>
</div>
<div id="myDIV">
<h3>No padding added to the h3 element. Hence the border is
nearly touching the text.</h3>
</div>
</body>
</html>
Padding - Single-side Properties
CSS provides four separate properties to set padding for top, right, bottom, and left for an element.
• padding-top
Following example shows how different padding properties can be set around an h2 element:
<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
h2 {padding-top: 10px; padding-right: 20px; padding-bottom:
30px; padding-left: 40px; background-color: skyblue; border: 1px
solid;}
</style>
</head>
<body>
<div>
<h2>The different padding property values are set to the h2
element.</h2>
</div>
</body>
</html>
Padding - Shorthand Property
Padding can be set to all the sides of an element at once. The value for padding properties can be
in pixels, inches, ems, or centimeters, apart from percentage.
<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
Three values can be passed to the padding as padding: 20px 40px 10px. In this case top padding
will be 20px, right and left paddings will be 40px and bottom padding will be 10px.
<!DOCTYPE html>
<html>
<head>
<title>CSS - Padding</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<style>
h2 {padding: 20px 40px 10px; background-color: silver;}
</style>
</head>
<body>
<div>
<h2>The three different padding property values are set to
the h2 element.</h2>
</div>
</body>
</html>
4.1. Introduction
Evolution of JavaScript
JavaScript, HTML, and CSS are fundamental technologies in web development, each serving
distinct yet interconnected roles in creating dynamic and visually appealing web applications.
While HTML (Hypertext Markup Language) provides the structural backbone of web pages,
defining elements and their arrangement, CSS (Cascading Style Sheets) enhances the presentation
by styling and formatting these elements. In contrast, JavaScript adds interactivity and dynamic
behavior to web pages, enabling features like form validation, DOM manipulation, and
asynchronous communication with servers.
Comparison:
Dynamic Typing:
• JavaScript variables can hold values of any data type, and the data type of a variable can
change at runtime. Example:
var dynamicVar;
dynamicVar = 10; // Number
dynamicVar = 'Hello'; // String
dynamicVar = true; // Boolean
Naming Conventions:
• Variables can include letters, digits, underscores, and dollar signs. They must begin with
a letter, underscore, or dollar sign (not a digit).
• Variable names are case-sensitive.
• It's recommended to use camelCase for variable names to improve readability. Example:
var myVariable;
var firstName;
var numStudents;
Best Practices:
3. Undefined: Represents a variable that has been declared but not assigned a value.
let x;
console.log(x); // Output: undefined
4. Null: Represents an intentional absence of any object value.
let y = null;
5. Symbol: Introduced in ES6, represents unique identifiers. Symbols are immutable and
can be used as property keys in objects.
const sym = Symbol('description');
1. Object: Represents a collection of key-value pairs where values can be primitive types, other
objects, or functions
let obj = {
name: 'John',
age: 30,
isAdmin: false
};
Arithmetic Operators:
Assignment Operators:
Comparison Operators:
Comparison operators compare two values and return a Boolean result (true or false).
• Equal (==): Checks if two operands are equal in value, but not necessarily in type.
• Strict Equal (===): Checks if two operands are equal in value and type.
• Not Equal (!=): Checks if two operands are not equal in value.
Logical Operators:
Unary Operators:
Bitwise Operators:
JavaScript control statements are statements that enable developers to control the flow of
execution within their programs. They include conditional statements, loops, and other structures
that determine which statements should be executed under certain conditions. Here's a detailed
discussion of JavaScript control structures:
Conditional Statements:
Conditional statements allow you to execute different blocks of code based on specified
conditions.
if Statement: Executes a block of code if a specified condition is true.
if (condition) {
// code block
}
if...else Statement: Executes one block of code if a specified condition is true and another block
if it's false.
if (condition) {
// code block
} else {
// code block
}
if...else if...else Statement: Executes different blocks of code for different conditions.
if (condition1) {
// code block
} else if (condition2) {
// code block
} else {
// code block
}
switch Statement: Evaluates an expression and executes a block of code based on matching case
labels.
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
Loop Statements:
Loop statements allow you to execute a block of code repeatedly as long as a specified condition
is true.
• for Loop: Executes a block of code a specified number of times
for (initialization; condition; increment) {
// code block
}
while Loop: Executes a block of code while a specified condition is true.
while (condition) {
// code block
}
do...while Loop: Executes a block of code once before checking if the condition is true, then
repeats the loop as long as the condition is true.
do {
// code block
} while (condition);
for...in Loop: Iterates over the enumerable properties of an object
for (variable in object) {
// code block
}
for...of Loop: Iterates over iterable objects such as arrays, strings, and collections.
for (variable of iterable) {
// code block
}
• break Statement: Terminates the current loop or switch statement and transfers control
to the statement immediately following the loop or switch.
• continue Statement: Skips the current iteration of a loop and continues with the next
iteration.
• return Statement: Exits the current function and returns a value to the caller.
• try...catch Statement: Executes a block of code and catches any exceptions that occur
within that block.
• throw Statement: Throws an exception explicitly.
JavaScript functions are blocks of code designed to perform a specific task or calculate a value.
They are a fundamental building block of JavaScript programming and can be used to organize
and reuse code efficiently. Here's a detailed discussion of JavaScript functions:
i. Function Declaration:
A function declaration defines a named function using the function keyword. It typically
consists of:
Introduced in ES6, arrow functions provide a concise syntax for writing anonymous functions.
They are especially useful for short, single-expression functions and maintain the this context
from the enclosing scope. e.g:
An anonymous function is a function without a name. It's often used in function expressions or
as callback functions.
v. Function Parameters:
Functions can accept parameters, which are variables that represent values passed to the function
when it is called. Parameters are listed within the parentheses of the function declaration.
function greet(name) {
return 'Hello, ' + name + '!';
}
console.log(greet('John')); // Output: Hello, John!
Return Statement:
The return statement is used to specify the value that a function should return. It ends the
function's execution and returns the specified value to the caller.
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8
Functions are invoked (called) using their name followed by parentheses containing any
arguments. This triggers the execution of the function's code.
function greet(name) {
return 'Hello, ' + name + '!';
Variables declared inside a function are scoped to that function and are not accessible from
outside. This is known as function scope.
function test() {
let x = 10;
console.log(x); // Output: 10
}
console.log(x); // Error: x is not defined
Function declarations are hoisted to the top of their containing scope, allowing them to be called
before they are declared.
A recursive function is a function that calls itself, often used for tasks that can be broken down
into smaller, similar subtasks. It's crucial to have a base case to prevent infinite recursion.
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
x. Callback Function:
A callback function is a function passed as an argument to another function, which is then invoked
inside the outer function. This is often used in asynchronous programming and event handling.
Parameters are the variables listed inside the parentheses of a function declaration, while
arguments are the values passed to the function when it is invoked. Parameters and arguments
enable the passing of data into functions.
function add(a, b) {
return a + b;
}
console.log(add(3, 4)); // Arguments: 3, 4 | Output: 7
Global Scope:
Variables declared outside of any function have global scope, meaning they can be accessed from
anywhere in the code, including within functions.
let globalVar = 'I am global';
function test() {
console.log(globalVar); // Output: I am global
}
test();
Local Scope:
Variables declared inside a function have local scope, meaning they are accessible only within
that function. They are not visible outside of the function.
test();
console.log(localVar); // Error: localVar is not defined
Function Scope:
JavaScript uses function scope, meaning that variables declared with var within a function are
scoped to that function. They are not visible outside of the function.
function test() {
var localVar = 'I am function-scoped';
console.log(localVar); // Output: I am function-scoped
}
test();
console.log(localVar); // Error: localVar is not defined
Introduced in ES6, let and const allow for block-scoped variables. Variables declared with let
or const within a block (such as within curly braces {}) are scoped to that block and are not
visible outside of it.
if (true) {
let blockVar = 'I am block-scoped';
console.log(blockVar); // Output: I am block-scoped
}
Lexical Scope:
JavaScript has lexical scope, meaning that the visibility of variables is determined by their
location in the source code. Functions can access variables defined in their outer scope, but not
vice versa.
function outer() {
let outerVar = 'I am outer';
function inner() {
inner();
}
outer();
console.log(outerVar); // Error: outerVar is not defined
Closure:
A closure is a combination of a function and the lexical environment within which that function
was declared. Closures allow functions to retain access to variables from their enclosing scope
even after the outer function has finished executing.
function outer() {
let outerVar = 'I am outer';
function inner() {
console.log(outerVar); // Output: I am outer
}
return inner;
}
HTML:
CSS:
JavaScript:
Throughout this module, you will explore the versatility and power of PHP (Hypertext
Preprocessor), a server-side scripting language widely used for web development. PHP seamlessly
integrates with HTML, enabling you to embed dynamic content, interact with databases, and
perform server-side processing to create robust and feature-rich web applications. Whether you're
a beginner or an experienced programmer, this module offers a comprehensive overview of PHP's
syntax, features, and best practices, ensuring that you have the skills and confidence to tackle real-
world web development projects.
In this module, you will delve into the core concepts of PHP programming, including variable
declaration, data types, control structures, functions, and object-oriented programming (OOP)
principles. You will learn how to write clean and efficient code, handle user input securely, validate
form data, and manage sessions and cookies to create personalized user experiences. Additionally,
you will explore how to interact with databases using PHP's built-in database extensions, such as
MySQL, and execute SQL queries to retrieve, manipulate, and store data effectively.
By the end of this module, you will have acquired the knowledge and skills necessary to develop
dynamic web applications using PHP, empowering you to pursue a career in web development or
enhance your existing skill set. Whether you aspire to become a full-stack developer, front-end
designer, or back-end engineer, the concepts covered in this module will provide you with a solid
foundation to excel in the rapidly evolving field of web programming. Get ready to unleash your
creativity and bring your web development projects to life with PHP!
PHP plays a pivotal role in modern web development by enabling developers to create dynamic
web pages that respond to user actions in real-time. From simple contact forms to complex e-
commerce platforms, PHP empowers developers to implement server-side logic and processing,
delivering personalized and engaging user experiences. Moreover, PHP seamlessly integrates with
HTML, CSS, and JavaScript, allowing developers to combine server-side functionality with client-
side interactivity to build feature-rich web applications. Whether it's fetching data from a database,
processing form submissions, or generating dynamic content, PHP provides the tools and
capabilities to meet the diverse needs of web development projects.
Furthermore, PHP boasts a vast ecosystem of frameworks, libraries, and tools that streamline the
development process and enhance productivity. Frameworks like Laravel, Symfony, and
CodeIgniter offer pre-built components, MVC (Model-View-Controller) architecture, and robust
security features, enabling developers to build scalable and maintainable web applications with
ease. Additionally, PHP's compatibility with various operating systems and web servers makes it
a versatile choice for deploying web applications across different environments, ensuring optimal
performance and reliability.
• PHP (Hypertext Preprocessor): Widely used for web development due to its simplicity,
versatility, and extensive community support. PHP powers popular content management
systems like WordPress, Joomla, and Drupal.
• Python: Known for its readability and wide range of libraries, Python is used for various
server-side scripting tasks, including web development with frameworks like Django and
Flask.
• Ruby: Popular for building web applications with the Ruby on Rails framework, offering
rapid development, convention over configuration, and elegant code.
• Node.js (JavaScript): Enables server-side scripting using JavaScript, leveraging its
asynchronous and event-driven nature for building scalable, real-time web applications.
• ASP.NET (C#): Developed by Microsoft, ASP.NET allows for server-side scripting with
C#, providing powerful tools and frameworks like ASP.NET Core and MVC for building
enterprise-grade web applications.
• Syntax: PHP has a syntax similar to C and Perl, while ASP.NET uses languages like C#
or Visual Basic (VB) for server-side scripting.
• Performance: Performance can vary depending on the specific use case, but ASP.NET
benefits from the performance optimizations provided by the .NET runtime.
• Community Support: PHP has a large and active open-source community, while
ASP.NET benefits from Microsoft's support and resources, including extensive
documentation and enterprise-level support.
• Ecosystem: PHP has a vast ecosystem with popular frameworks like Laravel, Symfony,
and CodeIgniter, while ASP.NET provides a comprehensive framework with ASP.NET
MVC, ASP.NET Core, and Web Forms for building web applications.
• Use Cases: PHP is widely used for web development, particularly for building CMSs, e-
commerce platforms, and enterprise applications. ASP.NET is popular for building
enterprise-level web applications, especially in corporate environments where integration
with other Microsoft technologies is essential.
• Syntax: PHP syntax is more similar to C and Perl, while Python emphasizes readability
and simplicity with its clean syntax.
• Performance: Python tends to be faster than PHP for certain tasks due to its efficient
interpreter and optimized runtime.
• Community Support: Both PHP and Python have large and active communities, with
extensive documentation, libraries, and frameworks available.
• Ecosystem: PHP has a vast ecosystem of CMSs (Content Management Systems) like
WordPress and frameworks like Laravel, while Python offers frameworks like Django and
Flask for web development.
• Use Cases: PHP is widely used for web development, especially for building dynamic
websites and web applications. Python is versatile and used for web development, scientific
computing, data analysis, artificial intelligence, and more.
• Syntax: PHP has a syntax similar to C and Perl, while Ruby emphasizes simplicity and
readability with its elegant syntax.
Tinsae D. @ 2024 Web Programming
• Performance: Ruby is generally slower than PHP due to its interpreter, but performance
differences may vary depending on the specific use case.
• Community Support: Both PHP and Ruby have active communities, with numerous
frameworks and libraries available for web development.
• Ecosystem: PHP has a larger ecosystem with widely used frameworks like Laravel,
Symfony, and CodeIgniter, while Ruby's main framework, Ruby on Rails, is renowned for
rapid development and convention over configuration.
• Use Cases: PHP is commonly used for web development, particularly for building CMSs,
e-commerce platforms, and enterprise applications. Ruby is popular for web development,
especially for startups and small to medium-sized projects.
• Syntax: PHP uses its syntax, while Node.js allows for server-side scripting using
JavaScript, providing a unified language for both client and server-side development.
• Performance: Node.js is known for its event-driven, non-blocking I/O model, which can
result in better performance for certain types of applications compared to PHP.
• Community Support: Both PHP and Node.js have active communities, but Node.js
benefits from being part of the broader JavaScript ecosystem, with extensive libraries and
tools available.
• Ecosystem: PHP has a mature ecosystem with popular frameworks like Laravel, while
Node.js has frameworks like Express.js and Meteor for building scalable and real-time web
applications.
• Use Cases: PHP is traditionally used for web development, while Node.js is favored for
real-time applications, APIs, and microservices where asynchronous and event-driven
architecture is beneficial.
What is PHP?
PHP is an open-source general purpose scripting language, widely used for website development.
It is developed by Rasmus Lerdorf. PHP stands for a recursive acronym PHP: Hypertext
Preprocessor.
PHP is the world’s most popular server-side programming language. Its latest version PHP 8.2.8,
released on July 4th, 2023.
A large number of reusable classes and libraries are available on PEAR and Composer. PEAR
(PHP Extension and Application Repository) is a distribution system for reusable PHP libraries or
classes. Composer is a dependency management tool in PHP.
PHP one of the most preferred languages for creating interactive websites and web applications.
PHP scripts can be easily embedded into HTML. With PHP, you can build
A number of PHP based web frameworks have been developed to speed-up the web application
development. The examples are WordPress, Laravel, Symfony etc.
PHP is a MUST for students and working professionals to become great Software Engineers,
especially when they are working in Web Development Domain.
Some of the most notable advantages of using PHP are listed below −
There are five important characteristics of PHP that make its practical nature possible:
Simplicity, Efficiency, Security, Flexibility, and Familiarity.
Just to give you a little excitement about PHP, I'm going to give you a small conventional PHP
Hello World program. You can try it using the Demo link.
<? php
echo "Hello, World!";
?>
Some of the basic syntax and structure required in writing a PHP script are:
PHP Tags:
• PHP code is enclosed within PHP opening and closing tags. The most common tag is
<?php ?>.
• PHP code can also be embedded within HTML markup, allowing for seamless integration
of server-side logic with client-side content.
• Additionally, short tags <? ?> and ASP-style tags <% %> can also be used, but they are
not recommended due to compatibility issues and are often disabled in server
configurations.
• Each PHP statement ends with a semicolon; This indicates the end of a statement and
allows multiple statements to be written on the same line if desired.
PHP comments
i. Single-line Comments:
Single-line comments in PHP begin with // or # and extend until the end of the line. They are
commonly used for short explanations or comments on a single line of code.
Example:
Multi-line comments in PHP are enclosed between /* and */ and can span multiple lines. They
are ideal for providing detailed explanations or commenting out blocks of code.
Example:
/*
This is a multi-line comment in PHP.
It can span multiple lines and is useful for
providing detailed documentation or commenting out
blocks of code.
*/
• PHP variables are declared using the $ symbol followed by the variable name. For example:
$name, $age, $price.
• Variable names must start with a letter or an underscore (_) and can be followed by letters,
numbers, or underscores.
• Variable names are case-sensitive in PHP, meaning $name, $Name, and $NAME are
treated as different variables.
• It's good practice to choose descriptive and meaningful variable names to improve code
readability and maintainability.
• PHP variables are dynamically typed, meaning their data type is determined by the value
assigned to them.
• PHP supports various data types, including:
Tinsae D. @ 2024 Web Programming
• Integers: Whole numbers without decimal points (e.g., $age = 25).
• Floats (Doubles): Numbers with decimal points (e.g., $price = 10.99).
• Strings: Sequences of characters enclosed in single ' ' or double " quotes (e.g., $name =
"John").
• Booleans: Representing true or false values ($isStudent = true).
• Arrays: Ordered collections of data elements (e.g., $colors = array('red', 'green', 'blue')).
• Objects: Instances of user-defined classes or built-in PHP classes.
• Null: Represents a variable with no value assigned to it ($x = null).
• PHP variables have different scopes, determining where they can be accessed within a
script:
• Local Scope: Variables declared inside a function are only accessible within that function.
• Global Scope: Variables declared outside of any function can be accessed from anywhere
in the script.
• Static Scope: Static variables retain their values between function calls, preserving their
state across function invocations.
• Superglobal Scope: Superglobal variables like $_GET, $_POST, and $_SESSION are
accessible from any part of the script and carry data across different parts of a web
application.
• Variables in PHP can be assigned values using the assignment operator =. For example:
$name = "John".
• Variables can be updated by assigning them new values. For example: $age = 30; $age =
35;.
v. Variable Variables:
vi. Constants:
• In addition to variables, PHP supports constants, which are identifiers whose values
cannot be changed during script execution.
• Constants are defined using the define() function or the const keyword. For example:
define("PI", 3.14);
Operators are symbols used to perform operations on variables and values. They enable developers
to manipulate data, perform calculations, and make decisions within PHP scripts. PHP supports a
wide range of operators, including arithmetic, assignment, comparison, logical, and bitwise
operators. Here are some of the PHP operators in detail:
i. Arithmetic Operators:
• Comparison operators are used to compare values and return true or false.
• They include equal ==, not equal !=, identical ===, not identical !==, greater than >, less
than <, greater than or equal >=, and less than or equal <=.
• Example
$num1 = 10;
$num2 = 5;
$result = $num1 > $num2; // Returns true
• Logical operators are used to combine conditions and perform logical operations.
• They include logical AND && (or and), logical OR || (or or), and logical NOT !.
• Example
$age = 25;
$isStudent = true;
if ($age > 18 && $isStudent) {
// Code executed if age is greater than 18 and is a student
}
• Increment ++ and decrement -- operators are used to increase or decrease the value of a
variable by one.
• They can be used in both pre-increment/decrement (where the value is modified before
being used) and post-increment/decrement (where the value is modified after being used)
forms.
• Example
$num = 10;
$num++; // Increment by 1
• Bitwise operators are used to perform operations on individual bits of binary numbers.
• They include bitwise AND &, bitwise OR |, bitwise XOR ^, bitwise NOT ~, left shift <<,
and right shift >>.
• Bitwise operators are often used in low-level programming and manipulating binary data.
• Example
$x = 0b1010; // Binary representation of 10
$y = 0b1100; // Binary representation of 12
$result = $x & $y; // Bitwise AND operation
Control statements are an integral part of any programming language, including PHP. These
statements allow developers to control the flow of execution in their programs, making
decisions, iterating over data, and executing code conditionally. With PHP control statements,
developers can create dynamic and interactive applications that respond to user input and
perform tasks based on specific conditions. Here are PHP control statements detail:
i. Conditional Statements:
Conditional statements in PHP allow developers to execute blocks of code based on specified
conditions. The most commonly used conditional statement is the if-else statement.
• if-else Statement:
if (condition) {
// Code block executed if condition is true
} else {
// Code block executed if condition is false
}
• elseif (else-if) Statement:
if (condition1) {
// Code block executed if condition1 is true
} elseif (condition2) {
// Code block executed if condition2 is true
} else {
// Code block executed if none of the conditions are true
}
ii. Loops:
Loops in PHP allow developers to iterate over data structures or execute a block of code
repeatedly until a condition is met.
for Loop
for ($i = 0; $i < 5; $i++) {
// Code block executed for each iteration
}
while Loop
$i = 0;
while ($i < 5) {
// Code block executed as long as the condition is true
Tinsae D. @ 2024 Web Programming
$i++;
}
do-while Loop
$i = 0;
do {
// Code block executed at least once, then repeatedly as long as the condition is
true
$i++;
} while ($i < 5);
foreach Loop
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
// Code block executed for each element in the array
}
The switch statement in PHP allows developers to compare a value against multiple possible
cases and execute code based on the matching case.
switch ($variable) {
case value1:
// Code block executed if $variable equals value1
break;
case value2:
// Code block executed if $variable equals value2
break;
default:
// Code block executed if none of the cases match
}
Control transfer statements in PHP alter the flow of execution within loops and switch
statements.
2.6.Functions in PHP
Functions are reusable blocks of code that perform specific tasks or operations. They enable
developers to organize their code into modular units, promoting code reuse, readability, and
maintainability. PHP provides extensive support for defining and calling functions, as well as
passing arguments and returning values.
Defining Functions:
• Functions in PHP are defined using the function keyword followed by the function name
and parameters enclosed within parentheses.
• The syntax for defining a function is as follows:
• Function names must follow the same rules as variable names: start with a letter or
underscore, followed by letters, numbers, or underscores.
• PHP allows functions to be defined globally or within classes (as methods), supporting
both procedural and object-oriented programming paradigms.
Calling Functions:
• Once defined, functions can be called (or invoked) by using their name followed by
parentheses containing any required arguments.
• Function calls are typically used within PHP scripts to execute the code defined within
the function body.
• Example of calling a function:
functionName($arg1, $arg2);
Function Parameters:
• Function parameters (or arguments) are variables passed into a function when it is called.
• Parameters can be specified in the function definition within the parentheses.
• PHP supports both required parameters and optional parameters with default values.
• Example of defining a function with parameters:
function greet($name) {
Tinsae D. @ 2024 Web Programming
echo "Hello, $name!";
}
Returning Values:
Function Scope:
• PHP functions have their own scope, meaning variables declared within a function are
only accessible within that function (local scope).
• Variables declared outside of a function are considered global variables and can be
accessed from anywhere in the script.
• PHP also supports static variables within functions, which retain their values between
function calls.
• PHP supports anonymous functions, also known as closures, which are functions without
a specified name.
• Anonymous functions are defined using the function keyword followed by parentheses
containing the function parameters and the function body enclosed within curly braces.
• Example of defining an anonymous function:
$greet = function($name) {
echo "Hello, $name!";
};
Embedding PHP code within HTML documents allows developers to create dynamic web pages
by combining static HTML content with PHP-generated dynamic content. The syntax for
embedding PHP within HTML is straightforward and follows a few basic rules. Let's discuss it in
detail:
• PHP code is enclosed within PHP opening <?php and closing ?> tags.
• These tags indicate the beginning and end of PHP code blocks within an HTML
document.
• Example:
<!DOCTYPE html>
<html>
<head>
<title>PHP and HTML Integration</title>
</head>
<body>
<h1>Embedding PHP within HTML</h1>
<?php
// PHP code block
echo "Hello, World!";
?>
</body>
</html>
• Within PHP tags, developers can write PHP code blocks to perform various tasks, such as
outputting dynamic content, executing conditional statements, or accessing databases.
• PHP code blocks can contain any valid PHP code, including variable declarations,
function calls, control structures, and database queries.
• Example
<p><?php echo "Today's date is: " . date("Y-m-d"); ?></p>
• Developers can seamlessly mix HTML and PHP within the same document to generate
dynamic HTML content based on PHP logic.
Tinsae D. @ 2024 Web Programming
• PHP code can be used to generate HTML elements, attributes, and content dynamically,
allowing for flexible and customizable web pages.
• Example
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Web Page</title>
</head>
<body>
<?php
$username = "John";
echo "<h1>Welcome, $username!</h1>";
?>
<p>Today's date is: <?php echo date("Y-m-d"); ?></p>
</body>
</html>
• PHP code can also be embedded within HTML attribute values to dynamically set
attribute values based on PHP variables or expressions.
• It's essential to ensure that PHP code within attribute values is properly enclosed within
quotes to avoid syntax errors.
• Example
<img src="<?php echo $imageUrl; ?>" alt="Image">
• PHP variables can be directly outputted within HTML content using PHP echo or print
statements.
• It's common to concatenate PHP variables with HTML strings to generate dynamic
content seamlessly.
• Example
<p>Welcome, <?php echo $username; ?>!</p>
• To include static HTML content within PHP code blocks without interpreting it as PHP
code, developers can escape from PHP mode using HTML tags.
• HTML tags and content within PHP code blocks are treated as plain text and will be
included in the output HTML document.
PHP enables developers to output dynamic content using the echo or print statements. These
statements can be used to display text, variables, or the result of expressions within HTML
documents.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content with PHP</title>
</head>
<body>
<h1>Welcome <?php echo "Abebe"; ?>!</h1>
<p>Today's date is: <?php echo date("Y-m-d"); ?></p>
</body>
</html>
3.3.Using PHP to output HTML elements dynamically (e.g., <div>, <p>, <ul>).
Using PHP to output HTML elements dynamically involves generating HTML markup based on
dynamic data or logic within PHP scripts. This allows developers to create dynamic web pages
that adapt to different scenarios, such as displaying lists of items from a database or generating
HTML elements conditionally. Let's discuss how to use PHP to output common HTML elements
dynamically:
The <div> element is a versatile container used for grouping and styling content. PHP can output
<div> elements dynamically by embedding PHP code within HTML.
Example:
<?php
$className = "container";
echo "<div class='$className'>This is a dynamic div element.</div>";
?>
The <p> element represents a paragraph of text. PHP can output <p> elements dynamically to
display text content based on dynamic data or conditions.
Example:
<?php
$text = "This is a paragraph of dynamic text.";
echo "<p>$text</p>";
?>
Lists in HTML are represented using <ul> (unordered lists) and <li> (list items) elements. PHP
can output lists dynamically by iterating over an array or database query result.
Example:
<?php
$items = array("Item 1", "Item 2", "Item 3");
echo "<ul>";
foreach ($items as $item) {
echo "<li>$item</li>";
}
echo "</ul>";
?>
PHP can output various other HTML elements dynamically, including headers (<h1>, <h2>,
etc.), links (<a>), images (<img>), forms (<form>, <input>, etc.), and more.
<?php
$url = "https://example.com";
$linkText = "Visit Example";
echo "<a href='$url'>$linkText</a>";
?>
PHP can conditionally output HTML elements based on specific conditions using if-else
statements or other control structures.
Example:
<?php
$loggedIn = true;
if ($loggedIn) {
echo "<p>Welcome back, User!</p>";
} else {
echo "<p>Please log in to access the content.</p>";
}
?>
PHP can generate complex HTML structures dynamically by combining various HTML
elements, attributes, and content based on dynamic data or logic.
<?php
$rows = array(
array("John", "Doe", 30),
array("Jane", "Smith", 25),
array("Alice", "Johnson", 35)
);
echo "<table>";
foreach ($rows as $row) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>";
}
Tinsae D. @ 2024 Web Programming
echo "</table>";
?>
HTML forms provide a mechanism for users to input data and submit it to a server for
processing. Forms consist of various input elements such as text fields, checkboxes, radio
buttons, select dropdowns, and buttons.
Example:
When a user submits a form, the data is sent to a server-side PHP script specified in the form's
action attribute. In the PHP script, the submitted form data can be accessed using the $_POST or
$_GET superglobal arrays, depending on the form's submission method (POST or GET).
Example (process_form.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
Tinsae D. @ 2024 Web Programming
$password = $_POST["password"];
// Process the form data (e.g., validate, sanitize, store in database)
}
?>
3.5.$_POST Vs $_GET
The $_POST and $_GET superglobal arrays in PHP are used to collect form data submitted via
HTTP POST and GET methods, respectively. While both methods serve a similar purpose of
passing data from the client (browser) to the server (PHP script), they differ in how they transmit
and handle the data. Let's discuss the differences between $_POST and $_GET variables:
• $_POST: Data submitted using the POST method is transmitted in the body of the HTTP
request. This method is typically used for submitting sensitive or large amounts of data,
such as form submissions or file uploads. The data is not visible in the URL.
• $_GET: Data submitted using the GET method is transmitted in the URL as query
parameters. This method is suitable for passing small amounts of data, such as search
queries or navigation parameters. The data is visible in the URL, making it less secure for
sensitive information.
Security Implications:
• $_POST: Since data submitted via POST is not visible in the URL, it's generally
considered more secure for transmitting sensitive information such as passwords or
personal details. POST requests can also be encrypted using HTTPS for additional
security.
• $_GET: Data submitted via GET is visible in the URL, which poses security risks,
especially when transmitting sensitive information. Parameters passed in the URL can be
manipulated or intercepted more easily, making GET requests less secure for sensitive
data.
• $_POST: There are typically no size limitations for data submitted via POST. However,
servers and PHP configurations may impose limits on the maximum size of POST data to
prevent abuse or denial-of-service attacks.
• $_GET: The amount of data that can be submitted via GET is limited by the maximum
URL length supported by browsers and servers. Exceeding this limit may result in
truncation of the URL or errors in processing the request.
• $_POST: Data submitted via POST is not cached by browsers, and form submissions
using POST are not bookmarkable. This behavior ensures that sensitive information is
not inadvertently stored or shared.
• $_GET: Data submitted via GET can be cached by browsers, and URLs containing GET
parameters can be bookmarked or shared easily. However, this also means that sensitive
information may be stored in browser history or shared inadvertently.
Use Cases:
• $_POST: Use POST when submitting forms with sensitive data, such as login forms,
registration forms, or payment information. POST requests are also suitable for
operations that modify server-side data (e.g., updating database records).
• $_GET: Use GET for passing parameters in URLs, such as search queries, filtering
criteria, or navigation links. GET requests are ideal for retrieving data from the server
without modifying server-side state.
User input validation is essential to ensure that submitted data meets specific criteria or
constraints (e.g., required fields, data format, length). PHP scripts can validate form data by
checking for errors or inconsistencies and providing feedback to users if validation fails.
Example:
if (empty($username)) {
$errors[] = "Username is required.";
}
if (strlen($password) < 8) {
$errors[] = "Password must be at least 8 characters long.";
}
// Check for other validation rules...
Sanitization involves removing potentially harmful or unwanted characters from user input to
prevent security vulnerabilities such as cross-site scripting (XSS) attacks or SQL injection. PHP
provides functions for sanitizing input data, such as htmlspecialchars() and
mysqli_real_escape_string().
Example:
In cases where form submission fails due to validation errors, it's helpful to repopulate form
fields with previously submitted data. This provides a better user experience by preserving user
input and allowing users to correct errors easily.
Example:
Cross-Site Request Forgery (CSRF) attacks occur when malicious actors trick users into
unknowingly submitting unwanted requests. To prevent CSRF attacks, developers can use
techniques such as CSRF tokens or the SameSite attribute for cookies.
First, we generate a CSRF token when rendering the form and store it in the session.
<?php
session_start();
We include the CSRF token as a hidden input field within the form.
In the PHP script that processes the form submission (process_form.php), we validate the
CSRF token before processing any data.
<?php
session_start();
1. Server-side Validation:
a. Required Fields:
Check if required fields are not empty.
Example:
Tinsae D. @ 2024 Web Programming
if (empty($_POST['username'])) {
$errors[] = "Username is required.";
}
b. Data Format:
Validate data format, such as email addresses, phone numbers, or dates.
Example:
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
c. Length Restrictions:
Ensure input length does not exceed maximum limits.
Example:
if (strlen($_POST['password']) < 8) {
$errors[] = "Password must be at least 8 characters long.";
}
d. Numeric or Alphanumeric Values:
Validate numeric or alphanumeric input.
Example:
if (!ctype_alnum($_POST['username'])) {
$errors[] = "Username can only contain letters and numbers.";
}
e. Custom Rules:
Implement custom validation rules specific to the application's requirements.
Example:
2. Server-side Sanitization:
a. HTML Encoding:
Convert special characters to HTML entities to prevent XSS attacks.
Example:
Tinsae D. @ 2024 Web Programming
$username = htmlspecialchars($_POST['username']);
c. Filtering Input:
Use PHP filter functions to validate and sanitize input data.
Example:
Example:
3.7.Session
Sessions are a fundamental concept in web development that allows servers to maintain stateful
information across multiple HTTP requests from the same user. They enable the server to
identify and track users as they navigate through a web application, providing a way to store and
retrieve user-specific data securely. Sessions are commonly used for tasks such as user
authentication, maintaining shopping cart contents, and personalizing user experiences. Let's
delve into the details of sessions:
1. Session Initialization:
Sessions in PHP are initiated using the session_start() function. This function starts a new
session or resumes an existing one by sending a session identifier (or session ID) to the client's
browser.
session_start();
Once a session is started, data can be stored in the $_SESSION superglobal array. This array
persists throughout the user's session and is accessible across different pages of the website.
4. Session Management:
Sessions can be managed using various configuration settings and functions provided by PHP.
For example, you can set the session lifetime and cookie parameters in the php.ini file.
5. Session Security:
Session security is crucial to prevent unauthorized access to user data. Best practices include
using HTTPS, regenerating session IDs, and validating session data.
6. Session Expiration:
Sessions have a limited lifespan, and they expire after a certain period of inactivity. You can
configure the session expiration time using session configuration settings.
7. Destroying Sessions:
Sessions can be explicitly destroyed when they are no longer needed, such as when a user logs
out of the application.
session_start();
1. How can PHP be used to output HTML elements dynamically on web pages?
2. What is the purpose of using PHP to generate dynamic content within HTML markup?
3. How can PHP be utilized to create dynamic lists using arrays or database query results?
4. What are some examples of HTML elements that PHP can output dynamically?
5. How does PHP enable conditional output of HTML elements based on specific conditions?
6. What is the significance of using PHP to output <div> elements dynamically in web
development?
7. How can PHP be employed to output <p> elements dynamically for displaying text content?
8. What are the advantages of using PHP to generate dynamic links on web pages?
9. How does PHP facilitate the conditional output of HTML elements using if-else statements?
10. What role does PHP play in dynamically generating headers, links, images, and forms on
web pages?
11. How can PHP be used to create personalized user experiences through dynamic content?
12. What are the benefits of using PHP to adapt web pages to different scenarios based on
dynamic data?
13. How does PHP contribute to the interactive and engaging nature of web applications?
14. What are some common practices for integrating PHP with HTML to create dynamic web
pages?
15. How can PHP enhance the user experience by dynamically generating content based on user
interactions?
A database is a structured collection of data organized for efficient storage, retrieval, and
management. It serves as a centralized repository for storing and managing data in various formats,
allowing users and applications to interact with the data effectively. Databases play a crucial role
in modern software development, powering web applications, mobile apps, enterprise systems,
and more.
1. Relational Model: MySQL follows the relational database model, organizing data into tables with
rows and columns. This structured approach allows for efficient storage, retrieval, and
manipulation of data.
2. Scalability: MySQL is highly scalable, designed to handle large datasets and high traffic loads. It
supports horizontal scaling through features like replication and sharding, enabling the distribution
of workload and data across multiple servers.
3. Performance Optimization: MySQL offers various optimization techniques such as indexing,
query caching, and storage engines to enhance performance. These features ensure fast query
execution and high throughput, even under heavy workloads.
4. High Availability: With features like replication and automatic failover, MySQL ensures high
availability and fault tolerance. Redundancy mechanisms minimize downtime and data loss,
contributing to robust data management.
5. Security: MySQL prioritizes data security with authentication, access control, and encryption
features. It provides mechanisms to enforce security policies and compliance requirements,
safeguarding sensitive information from unauthorized access.
6. Community Support: MySQL boasts an extensive community of users and developers who
contribute to its development, support, and documentation. This vibrant community provides
valuable resources, including guides, tutorials, and forums, ensuring users have access to
comprehensive assistance.
7. Ease of Use and Integration: MySQL's user-friendly interface and extensive
documentation make it accessible to developers of all levels. Its seamless integration with
PHP, as well as other programming languages and frameworks, simplifies database
PHP offers several extensions for interacting with databases, each designed to work with specific
database systems. The most commonly used extensions include:
Before establishing a database connection, ensure that the necessary database drivers are
installed and enabled in your PHP environment. You can check the php.ini configuration file or
use the phpinfo() function to verify the availability of database drivers.
To establish a database connection, you need to provide connection parameters such as the host,
username, password, and database name. These parameters vary depending on the database
system you are connecting to.
Once you have the necessary database extension installed and the connection parameters
configured, you can establish a connection to the database using PHP code. The process involves
creating a connection object using the appropriate database extension and passing the connection
parameters to it.
// Create a connection
$conn = mysqli_connect($host, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
} else {
echo "Connected successfully";
}
It's essential to handle connection errors gracefully to provide meaningful feedback to users and
developers. Use error handling mechanisms such as try-catch blocks (for PDO) or conditional
statements (for MySQLi) to detect and handle connection errors.
After executing database queries and operations, it's good practice to close the database
connection to free up system resources. For MySQLi, use the close() method, while for PDO,
the connection is automatically closed at the end of the script execution.
Executing SQL queries with PHP involves establishing a connection to a database, preparing and
executing SQL statements, and handling the results. Let's break down the process step by step
with an example for OOP, Procedural and PDO:
//OOP
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
//PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
• $servername: This variable holds the hostname of the database server. It's typically
"localhost" if the database is hosted on the same server as your PHP script.
• $username: This is the username used to connect to the database server.
• $password: This is the password associated with the username.
• $dbname: This variable specifies the name of the database you want to connect to.
• The mysqli class in PHP is used to establish a connection to a MySQL database server.
•
//OOP
<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
?>
//procedural
<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
?>
//PDO
<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->rowCount() > 0) {
foreach($result as $row) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
• $sql: This variable holds the SQL query you want to execute.
• $conn->query($sql): This method executes the SQL query against the database. It
returns a result set for SELECT queries.
• fetch_assoc(): This method fetches a row from the result set as an associative array.
3. Inserting Data:
//OOP
<?php
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
//procedural
<?php
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
// PDO
<?php
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
try {
$conn->exec($sql);
echo "New record created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
?>
4. Updating Data:
//OOP
<?php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=1";
//procedural
<?php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
?>
//PDO
<?php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=1";
try {
$conn->exec($sql);
echo "Record updated successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
?>
• This example uses an SQL UPDATE statement to modify an existing record in the
MyGuests table.
5. Deleting Data:
//OOP
//Procedural
<?php
$sql = "DELETE FROM MyGuests WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
?>
//PDO
<?php
$sql = "DELETE FROM MyGuests WHERE id=1";
try {
$conn->exec($sql);
echo "Record deleted successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
?>
• This example uses an SQL DELETE statement to remove a record from the MyGuests
table.
6. Closing Connection:
//OOP
<?php
$conn->close();
?>
1. How does PHP facilitate the establishment of database connections for web applications?
2. What are the key database extensions in PHP for interacting with databases, and how do
they differ?
3. How can PHP be used to install and enable database drivers before establishing
connections?
4. What are the essential database connection parameters required in PHP for connecting to
a database system?
5. How does PHP handle database connections using MySQLi in a procedural manner?
6. What steps are involved in establishing a database connection using PDO in PHP?
7. How can PHP execute SQL queries to interact with databases and retrieve data
efficiently?
8. What role does PHP play in handling database transactions for data manipulation and
storage?
9. How does PHP ensure secure data handling when interacting with databases in web
applications?
10. What are the best practices for managing database connections and executing queries
using PHP in web development projects?
Apply object-oriented programming (OOP) principles using PHP involves structuring your code
into classes and objects, encapsulating related functionality within these classes, and utilizing
inheritance, polymorphism, and other OOP concepts. Below is a detailed outline of the contents
you can include in your PHP module:
1. Define Classes:
a. Main Class:
Create a main class that encapsulates the core functionality of your module. This class acts as a
central point of coordination for other classes and operations within your module.
Example:
class ECommerceSystem {
// Properties, constructor, and methods go here
}
b. Additional Classes:
Identify different entities or services within your module and create classes to represent them.
Each class should have a specific responsibility and adhere to the Single Responsibility Principle
(SRP).
Example:
class Product {
// Properties, constructor, and methods related to products
}
class ShoppingCart {
// Properties, constructor, and methods related to managing a shopping cart
}
class Order {
// Properties, constructor, and methods related to processing orders
}
Declare properties within each class to encapsulate the state of objects. Choose appropriate
visibility (public, protected, or private) based on encapsulation principles.
Example:
class Product {
public $id;
public $name;
public $price;
private $description;
}
3. Define Constructor:
Implement a constructor method in each class to initialize object properties when instances are
created. This method is called automatically upon object instantiation.
Example:
class Product {
public function __construct($id, $name, $price, $description) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->description = $description;
}
}
4. Define Methods:
Define methods within classes to encapsulate behavior and functionality. Each method should
have a clear purpose and perform a specific action or computation.
Example:
Example:
class Product {
private $id;
private $name;
private $price;
private $description;
• Inheritance: Create a class hierarchy if there are common behaviors or attributes shared
among different types of objects.
Example:
Example:
interface Shippable {
public function calculateShippingCost();
}
Handle errors and validate input data within methods to ensure robustness and reliability. Use
exceptions or error codes to communicate and manage errors effectively.
Example:
class Product {
public function __construct($id, $name, $price, $description) {
if (empty($id) || empty($name) || empty($price)) {
throw new InvalidArgumentException("ID, name, and price are
required.");
}
$this->id = $id;
$this->name = $name;
$this->price = $price;
$this->description = $description;
}
}
Provide comprehensive comments and documentation for classes, properties, and methods to
facilitate understanding and usage by other developers.
Example:
/**
* Represents a product in the e-commerce system.
*/
class Product {
/**
* @var int The unique identifier of the product.
*/
public $id;
8. Example Usage:
Include example code snippets demonstrating how to use your module to perform common tasks.
Example:
9. Testing:
Write unit tests using a testing framework such as PHPUnit to validate the correctness and
robustness of your classes and methods.
Example:
Multimedia has become an integral part of our daily lives, revolutionizing the way we
communicate, learn, and interact with the world around us. From entertainment and education to
business and communication, multimedia encompasses a diverse range of uses that impact
virtually every aspect of modern society. In this module, we will explore the multifaceted nature
of multimedia and its profound influence on our daily lives. By delving into its various
components, files, and software applications, we aim to provide a comprehensive understanding
of multimedia and its potential applications.
Firstly, we will discuss the different uses of multimedia and how they affect the daily lives of
people. Multimedia transcends traditional forms of communication by combining text, images,
audio, video, and interactive elements to convey information and evoke emotions. Whether
through social media platforms, streaming services, or interactive websites, multimedia enriches
our experiences and facilitates seamless communication across diverse audiences. Understanding
its impact can empower individuals to harness its potential for personal, educational, and
professional endeavors.
Next, we will identify the different components of multimedia and explore how they can be utilized
with the latest software tools and technologies. From graphic design and video production to web
development and animation, multimedia encompasses a myriad of components that require
specialized software applications for creation and manipulation. By familiarizing ourselves with
these components and their corresponding software, we can unleash our creativity and leverage
cutting-edge technologies to produce compelling multimedia content.
Furthermore, we will delve into the realm of multimedia files, examining the various formats and
codecs used to store and transmit multimedia content. Whether it's images, videos, audio
recordings, or interactive presentations, multimedia files come in a multitude of formats, each with
its own strengths and limitations. Understanding the characteristics of different file formats is
essential for optimizing media delivery, ensuring compatibility, and preserving quality throughout
the production process.
Lastly, we will utilize multimedia software to develop multimedia files, focusing on photo and
video editing techniques, terminologies, and concepts. Through hands-on practice and exploration,
participants will gain proficiency in editing photos and videos, mastering essential techniques for
enhancing visual content, manipulating images, and refining storytelling narratives. By acquiring
these skills, individuals can unleash their creativity, express their ideas effectively, and produce
multimedia content that captivates and inspires audiences.
Multimedia refers to the integration of different forms of media elements such as text, graphics,
images, audio, video, and animations in a single digital presentation or application. It encompasses
a wide range of digital content that is designed to engage and communicate with users through
various sensory channels.
Multimedia content is typically delivered through various digital platforms and devices, including
computers, smartphones, tablets, televisions, and multimedia projectors. It is commonly used in a
wide range of applications across different fields, including entertainment, education,
communication, marketing, healthcare, business, and industry.
The key characteristics of multimedia include interactivity, flexibility, and the ability to combine
different media types to create engaging and immersive experiences for users. Multimedia
presentations can be interactive, allowing users to navigate, manipulate, and customize content
according to their preferences or needs.
i. Text:
• Definition: Text refers to written or typed content that provides information,
instructions, or explanations within multimedia presentations.
• Characteristics: Text can be static or dynamic, displayed in various fonts, sizes,
and styles to convey meaning effectively. It is often used in titles, captions, labels,
instructions, and annotations.
• Purpose: Text complements other media elements by providing context, guiding
user interactions, conveying messages, and enhancing the readability and
accessibility of multimedia content.
• Examples: Titles and headings, body text, bullet points, labels in diagrams or
charts, instructional text in tutorials, and textual content in interactive applications.
ii. Graphics and Images:
• Definition: Graphics and images are visual representations such as photographs,
illustrations, diagrams, charts, and graphs.
• Characteristics: Graphics and images can be static or dynamic, consisting of pixels
or vector-based shapes. They convey visual information, evoke emotions, and
enhance the aesthetic appeal of multimedia presentations.
• Purpose: Graphics and images help illustrate concepts, depict scenes, clarify
complex ideas, evoke emotions, and engage the audience visually. They play a
crucial role in storytelling, branding, and visual communication.
• Examples: Photographs, illustrations, infographics, diagrams, charts, logos, icons,
buttons, and graphical user interface (GUI) elements.
iii. Audio:
• Definition: Audio refers to sound elements such as music, narration, sound effects,
ambient sounds, and spoken dialogue.
• Characteristics: Audio can be recorded, synthesized, or generated digitally. It
enhances the immersive experience of multimedia presentations, providing
auditory cues, ambiance, and emotional impact.
• Purpose: Audio enriches multimedia content by providing context, atmosphere,
mood, and emphasis. It supports storytelling, reinforces messages, and creates a
sense of presence or engagement for the audience.
• Examples: Background music, voiceovers, sound effects (e.g., footsteps, doorbell),
ambient sounds (e.g., nature sounds), dialogues in podcasts or audiovisual content.
iv. Video:
• Definition: Video consists of moving images or sequences of frames that depict
scenes, events, or actions.
• Characteristics: Video content can be recorded, edited, and played back in various
formats and resolutions. It conveys visual information dynamically, capturing
motion, expressions, and storytelling elements.
By combining these components creatively and strategically, multimedia designers and developers
can create compelling, informative, and engaging digital experiences across various platforms and
applications. Each component contributes to the overall richness and effectiveness of multimedia
content, catering to diverse audience preferences and communication objectives.
1.3.Importance of Multimedia
The relevance and importance of multimedia in today's digital age are profound, impacting various
aspects of our lives, society, and economy. Here's a discussion highlighting its significance:
Multimedia holds immense importance in the realm of education and training, revolutionizing
traditional teaching methods and enhancing the learning experience for students of all ages. By
integrating various media elements such as text, graphics, images, audio, and video, multimedia
transforms educational content into interactive and engaging resources. In the classroom,
multimedia presentations, digital textbooks, and interactive tutorials captivate students' attention,
facilitate comprehension, and cater to diverse learning styles. Visual aids and animations clarify
complex concepts, while audio narration and video demonstrations bring lessons to life, making
abstract topics more relatable and accessible. Moreover, multimedia enables educators to create
personalized learning experiences, allowing students to learn at their own pace and explore content
through interactive exercises and simulations.
Outside the classroom, multimedia plays a vital role in lifelong learning and professional
development. E-learning platforms, online courses, and educational apps leverage multimedia
technologies to deliver high-quality educational content to learners worldwide. Multimedia
Tinsae D. @ 2024 Multimedia System and Development
tutorials, simulations, and virtual laboratories provide hands-on training in various fields, from
science and engineering to healthcare and business. Additionally, multimedia facilitates
collaborative learning experiences, enabling learners to connect with instructors and peers, share
knowledge, and collaborate on projects remotely. As technology continues to advance, multimedia
will continue to shape the future of education and training, empowering learners to acquire
knowledge, develop skills, and pursue lifelong learning opportunities in dynamic and engaging
ways. Some of the significances are:
Generally, multimedia enriches e-learning platforms, interactive tutorials, virtual laboratories, and
vocational training programs by providing engaging, interactive, and immersive learning
experiences. It enhances comprehension, retention, and skills development, empowering learners
to acquire knowledge and competencies effectively in diverse educational and training contexts.
Multimedia serves as the cornerstone of modern marketing and advertising strategies, offering
dynamic and captivating ways to engage audiences across various channels. Through a rich
combination of visual, auditory, and interactive elements, multimedia breathes life into brand
messages, effectively capturing attention and leaving a lasting impression. In advertising
campaigns, multimedia content such as videos, animations, and images serves as powerful
storytelling tools, enabling brands to convey their narrative and values with authenticity and
creativity. Interactive multimedia advertisements take audience engagement to the next level,
inviting viewers to actively participate in the ad experience through quizzes, games, and immersive
experiences like virtual tours. Moreover, multimedia facilitates product demonstrations and
showcases, allowing consumers to explore products in detail and make informed purchase
decisions. With personalized marketing initiatives leveraging multimedia channels, brands can
tailor content to individual preferences and behaviors, forging deeper connections and fostering
brand loyalty. In essence, multimedia is the driving force behind impactful marketing and
Moreover, multimedia's versatility shines through video and animation components, which bring
motion, narrative, and interactivity to digital experiences. Video content captivates audiences with
moving images and dynamic storytelling, fostering engagement and retention. From cinematic
masterpieces to informative tutorials, video offers a powerful medium for communication and
expression. Animations, on the other hand, introduce playful dynamics and interactive elements to
multimedia, enabling users to explore concepts, navigate interfaces, and interact with content in
engaging ways. By integrating these diverse components, multimedia transcends traditional
boundaries, offering immersive, multi-sensory experiences that captivate, inform, and inspire
audiences across diverse domains.
Graphics and image components form the visual backbone of multimedia, providing
captivating visual elements that enhance communication and engagement. Graphics
encompass a wide range of visual representations, including illustrations, diagrams, charts,
logos, and icons, which serve to illustrate concepts, clarify information, and reinforce messages
within multimedia presentations. These graphical elements are meticulously designed to
convey complex ideas succinctly, capturing the audience's attention and facilitating
comprehension. Additionally, images play a crucial role in evoking emotions, establishing
connections, and immersing viewers in multimedia experiences. Whether photographs,
illustrations, or infographics, images evoke visceral reactions and enrich storytelling by
providing vivid depictions of people, places, and objects. Through their aesthetic appeal and
communicative power, graphics and images elevate the visual impact of multimedia content,
making it more memorable, engaging, and effective in conveying information and eliciting
responses from audiences.
Exploring the use of graphics and images for visual communication involves delving into their
diverse applications and significance in conveying information, eliciting emotions, and engaging
audiences across various mediums. Here's a detailed discussion:
1. Enhancing Clarity and Understanding: Graphics and images are powerful tools for
enhancing clarity and understanding in visual communication. In fields such as education,
science, and technical documentation, complex concepts and data can be difficult to convey
through text alone. Visual representations such as charts, graphs, diagrams, and
infographics provide visual context and structure, making it easier for audiences to grasp
abstract ideas and complex relationships. For example, a pie chart illustrating the
distribution of global energy sources allows viewers to quickly understand the relative
proportions of different energy sources without needing to interpret lengthy numerical data.
2. Capturing Attention and Engagement: Visual communication relies on capturing
attention and engaging audiences effectively. In today's fast-paced digital environment,
where content consumption is often rapid and fragmented, visuals play a crucial role in
attracting and retaining audience interest. Eye-catching graphics, striking images, and
compelling visual narratives can capture attention in a crowded media landscape and
encourage viewers to explore further. For instance, in advertising and marketing
campaigns, attention-grabbing visuals are essential for standing out from competitors and
making a memorable impression on consumers.
3. Eliciting Emotional Responses: Graphics and images have the power to evoke emotions
and create meaningful connections with audiences. Visual storytelling relies on the ability
to convey mood, tone, and atmosphere through imagery, allowing viewers to emotionally
connect with the message being communicated. For example, in journalism and
documentary filmmaking, powerful images can elicit empathy, compassion, or outrage by
depicting human experiences, social issues, and current events. By tapping into the
Image editing software plays a crucial role in enhancing, retouching, and manipulating images
for various purposes, including professional photography, graphic design, digital art, and more.
Here's an overview of some popular image editing software:
1. Adobe Photoshop: This is perhaps the most well-known and widely used image editing
software. It offers a comprehensive set of tools for enhancing, retouching, and
manipulating images, including layers, masks, filters, and various editing options.
Photoshop is favored by professionals for its versatility and extensive capabilities.
2. Adobe Lightroom: Lightroom is another Adobe product, primarily focused on organizing,
editing, and enhancing digital photographs. It offers powerful tools for color correction,
exposure adjustment, and batch editing, making it ideal for photographers who need to
process large volumes of images efficiently.
3. GIMP (GNU Image Manipulation Program): GIMP is a free and open-source alternative
to Photoshop. While it may not have all the features of Photoshop, it offers a wide range
of tools for image editing, including layers, masks, filters, and customizable brushes. GIMP
is popular among amateur photographers and designers due to its accessibility and
affordability.
4. Affinity Photo: Affinity Photo is a professional-grade image editing software that provides
many of the same features as Photoshop at a lower price point. It offers advanced tools for
retouching, compositing, and HDR processing, making it a compelling option for both
professionals and enthusiasts.
5. Corel PaintShop Pro: PaintShop Pro is a versatile image editing software that caters to
both beginners and experienced users. It offers a range of tools for photo editing, graphic
design, and digital painting, along with features like content-aware fill and lens correction.
Tinsae D. @ 2024 Multimedia System and Development
6. Pixlr: Pixlr is a web-based image editing tool that offers a simplified interface and basic
editing features. It's suitable for quick edits and minor adjustments and is accessible to
users who may not have access to more advanced software.
7. Capture One: Capture One is primarily designed for professional photographers and offers
advanced tools for raw image processing, tethered shooting, and color grading. It's known
for its excellent color accuracy and robust workflow features.
8. Skylum Luminar: Luminar is an AI-powered image editing software that automates many
common editing tasks, such as enhancing colors, improving skin tones, and removing
imperfections. It's popular among photographers who want to streamline their editing
process.
These are just a few examples of image editing software available in the market, each offering its
own set of features, tools, and capabilities to suit different user needs and preferences.
Note: in this course we are mainly focusing on Adobe Photoshop
Integrating graphics and images into multimedia projects involves a combination of design,
illustration, and photo editing software to create visually appealing and cohesive elements. Let's
break down how each type of software contributes to this process:
• Planning and Conceptualization: Defining the visual style, theme, and purpose of the
project, and determining the types of graphics and images needed to convey the intended
message or story.
• Creation and Editing: Using design, illustration, and photo editing software to create or
modify graphics and images according to the project requirements. This may involve
designing custom graphics, illustrating key elements, or editing photographs to achieve the
desired look and feel.
• Integration and Composition: Incorporating the graphics and images into the multimedia
project, arranging them within the layout or timeline, and ensuring visual consistency and
coherence across different media elements.
• Optimization and Export: Optimizing the graphics and images for their intended output
format (e.g., web, print, video) and exporting them in the appropriate file formats and
resolutions to ensure optimal quality and performance.
By leveraging the capabilities of design, illustration, and photo editing software, multimedia
creators can produce engaging and visually compelling projects that effectively communicate their
ideas and captivate their audience.
Audio plays a crucial role in multimedia projects, enhancing the overall experience and engaging
multiple senses simultaneously. Here's a discussion covering various aspects of audio in
multimedia:
Audio plays a fundamental role in multimedia presentations, videos, and interactive applications,
contributing significantly to the overall user experience. Here's an exploration of its importance
across these different mediums:
2.2.2. Audio editing and mixing tools in digital audio workstations (DAWs).
Audio editing and mixing tools in digital audio workstations (DAWs) encompasses a wide
array of functionalities designed to manipulate, enhance, and refine audio recordings.
DAWs serve as the central hub for music production, offering a comprehensive set of tools
for both creative and technical processes. Let's delve into the details of these tools:
These tools collectively empower audio engineers, producers, and musicians to sculpt, refine, and
craft professional-quality audio productions within the digital realm. With continuous
advancements in technology, DAWs evolve to offer increasingly sophisticated features, enabling
users to unleash their creativity and achieve their artistic visions with precision and efficiency.
In the realm of multimedia, the integration of video content stands as a pivotal element,
revolutionizing the way information is conveyed and consumed. Video transcends the static
limitations of text and images, offering a dynamic medium that engages multiple senses
simultaneously. Its immersive nature captivates audiences, making it an indispensable tool for
storytelling, education, and entertainment. With the proliferation of high-speed internet and
advancements in video compression technologies, the accessibility of video content has surged,
empowering creators to reach global audiences with ease. From instructional tutorials to cinematic
masterpieces, video in multimedia serves as a versatile canvas for expression, enabling the
seamless fusion of visuals, audio, and interactivity to evoke emotion, provoke thought, and foster
connections across diverse demographics and cultures.
Moreover, the evolution of video in multimedia has been profoundly shaped by technological
innovations, from the advent of motion pictures to the digital revolution of online streaming
platforms. The democratization of video production tools has empowered individuals and
organizations to produce professional-grade content without the need for extensive resources or
expertise. Furthermore, the integration of interactive elements such as clickable annotations, VR
(Virtual Reality), and AR (Augmented Reality) overlays has elevated the interactive potential of
video, transforming passive viewers into active participants. As the boundaries between traditional
media formats blur, video continues to evolve, driving innovation in areas such as live streaming,
360-degree video, and AI-driven personalized content delivery. In essence, video in multimedia
not only reflects the current state of technological progress but also serves as a catalyst for future
advancements, pushing the boundaries of creativity and communication in the digital age.
Some of video editing software for cutting, editing, and enhancing video footage:
• Adobe Premiere Pro and Final Cut Pro X: Industry-standard software offering advanced
editing tools, multi-camera support, and seamless integration with other creative
applications.
The integration of video with other multimedia elements using multimedia authoring, animation,
and web development software opens up a world of creative possibilities, allowing content creators
to craft immersive and engaging experiences for their audiences across various platforms.
Multimedia authoring software, such as Adobe Animate and Tumult Hype, enables the seamless
integration of video with interactive elements such as buttons, animations, and sound effects.
These platforms provide intuitive interfaces and robust tools for designing and organizing
multimedia content, making it easy to synchronize video playback with other elements to create
dynamic presentations, e-learning modules, and interactive experiences. For example, a
multimedia authoring tool might allow users to embed videos within interactive slideshows or
incorporate video backgrounds into interactive web applications, enhancing user engagement and
retention.
Animation software, such as Adobe After Effects and Blender, empowers users to combine video
footage with animated graphics, special effects, and motion graphics to create visually stunning
compositions. These tools offer advanced features such as keyframe animation, particle effects,
and 3D rendering, enabling users to enhance video content with dynamic visual elements that
capture attention and convey information in creative ways. For instance, animators can seamlessly
integrate animated characters or text overlays into video presentations to reinforce key concepts
or tell compelling stories, adding depth and personality to the overall narrative.
Web development software, such as Adobe Dreamweaver and Visual Studio Code, provides the
framework for integrating video content into websites and web applications. These platforms offer
tools for designing, coding, and testing web pages, as well as built-in support for embedding and
optimizing video files for online playback. By leveraging HTML5 video tags, CSS animations,
and JavaScript interactions, developers can seamlessly integrate video content into responsive web
designs, creating immersive multimedia experiences that adapt to different screen sizes and
devices. For example, web developers can implement video backgrounds, interactive galleries, and
video-based tutorials to enhance the visual appeal and functionality of websites, enriching the user
experience and driving engagement.
1. Selections and Masks: Selection tools enable isolating specific areas of an image for
editing, while masks allow applying edits selectively within those areas. This technique is
essential for complex edits, such as changing backgrounds or applying adjustments to
specific objects.
2. Layers and Blending Modes: Layers enable stacking multiple elements within an image,
each with its own set of adjustments and effects. Blending modes control how layers
interact with each other, allowing for creative blending and compositing effects.
3. Retouching and Restoration: Retouching involves removing imperfections or blemishes
from an image, such as dust spots, wrinkles, or skin imperfections. Restoration techniques
aim to repair old or damaged photos by repairing tears, scratches, and discoloration.
4. Filters and Effects: Applying filters and effects can dramatically alter the appearance of
an image, adding artistic flair or stylized looks. Common effects include vintage filters,
black and white conversions, and creative color grading.
Overall, image editing is a versatile and essential skill for anyone working with digital images.
Whether for professional photography, graphic design, or personal projects, mastering image
editing techniques allows for creative expression, visual storytelling, and the enhancement of
visual content.
3.2. Understanding Image Formats
Adobe Photoshop
(Practical Part)
One of Premiere Pro's standout features is its robust set of editing tools and effects, including
advanced audio editing, keyframe animation, and real-time playback. Its extensive library of built-
in transitions, titles, and graphics further enhances the creative possibilities, while third-party
plugins and extensions provide additional flexibility and customization options. Whether editing
short films, commercials, or feature-length movies, Premiere Pro offers the versatility and
performance needed to tackle projects of any scale and complexity. With its constant updates and
improvements, Adobe Premiere Pro remains at the forefront of video editing software,
empowering storytellers and filmmakers to push the boundaries of creativity and innovation.
By following these steps, you can start editing videos in Adobe Premiere Pro and explore its
powerful features to create professional-looking videos for various purposes.
1. What are the key features of JPEG, and why is it widely used for digital photography and web
images?
2. How does multimedia facilitate the creation of meaningful connections in a digital
environment?
3. What is the significance of Multimedia System and Development in today's technological
landscape?
4. How can Adobe Premiere Pro be utilized for video editing, including tasks like importing
audio files, color correction, and exporting projects?
5. What are the learning outcomes expected from students after attending lessons on
multimedia, including understanding multimedia components and software usage?
6. How can multimedia impact daily lives and enhance various aspects of communication,
learning, and entertainment?
7. What are the different multimedia files commonly used in multimedia projects, and how do
they contribute to the overall experience?
8. What are the essential steps involved in developing a multimedia file using multimedia
software?
9. What are the key terminologies, concepts, and editing techniques related to photo and video
editing in multimedia projects?
10. How can multimedia software tools be leveraged to create professional-looking videos for
different purposes?
11. What role does color correction and grading play in enhancing the visual appeal of
multimedia projects?
12. How can adjustment layers and creative LUTs be used to create custom looks in multimedia
projects?
13. What are the best practices for exporting multimedia projects, including choosing the right
format, codec, resolution, and bitrate?
14. How does Adobe Premiere Pro streamline the video editing process and provide a user-
friendly interface for creators?
15. What are the benefits of saving multimedia projects regularly and utilizing backup project
files in Adobe Premiere Pro?
16. How can multimedia software empower individuals to express their creativity and storytelling
through videos?
17. What are the potential challenges faced by beginners when starting to edit videos in Adobe
Premiere Pro, and how can they be overcome?
18. How can multimedia software tools like Adobe Premiere Pro be used to cater to diverse
audiences and create engaging content?
19. What are the ethical considerations that creators should keep in mind when developing
multimedia content for public consumption?
20. How can multimedia technology continue to evolve and shape the future of communication,
entertainment, and education in the digital age?