0% found this document useful (0 votes)
297 views321 pages

Database and Web Development Module

This document is a comprehensive module for students in the Department of Information Technology, focusing on key subjects for their exit exam, including Database Fundamentals, Internet and Web Design, Web Programming, and Multimedia System Development. It outlines the curriculum structure, learning outcomes, and essential concepts related to database management systems (DBMS), emphasizing the importance of relational databases and their applications in various industries. The module aims to equip students with the necessary skills and knowledge to succeed in the digital landscape.

Uploaded by

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

Database and Web Development Module

This document is a comprehensive module for students in the Department of Information Technology, focusing on key subjects for their exit exam, including Database Fundamentals, Internet and Web Design, Web Programming, and Multimedia System Development. It outlines the curriculum structure, learning outcomes, and essential concepts related to database management systems (DBMS), emphasizing the importance of relational databases and their applications in various industries. The module aims to equip students with the necessary skills and knowledge to succeed in the digital landscape.

Uploaded by

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

MODULE FOR EXIT EXAM TUTORIAL

DEPARTMENT OF INFORMATION TECHNOLOGY

THEMATIC AREA: Database and Web Development


◼ Fundamentals Fundamental of database
◼ Internet and web design
◼ Web programing
◼ Multimedia System and Development

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.

Blueprint descriptor of the thematic area

Summer Curriculum Regular Curriculum


Couse code Course Name Course Code Course Name
IT 122 Fundamentals of database ITec 2034 Fundamentals of database
IT 142 Internet and web design ITec 3031 Web Design and
Development I
Web programing Web Design and
IT 311 ITec 3038
Development II
IT 222 Multimedia System and ITec 3039 Multimedia System and
Development Development
Identify the fundamental concepts of
database
Understand the
principles in Apply relational databases employing
Designing and
appropriate database design principles, and
creating relational
databases, entity-relationship modelling.
Database 3 employing
appropriate Identify SQL queries to insert, retrieve,
Fundamentals:
database design delete and update data from relational
principles, and
databases.
entity-relationship
modelling.
Describe data integrity and security
1
measures, including constraints

Explain the web, internet and its protocols 1


Create visually Determine the use of HTML to develop
appealing and
user-friendly webpages
3 websites, utilizing
Web Design HTML, CSS, and Apply CSS in html to create visually
Database and and JavaScript. appealing, user-friendly website.
Web Development I
development Use JavaScript features on the web page to
make it interactive.

Share = 27 items Describe the concepts, principles and


from the total Develop dynamic methods Server Side scripting Languages 1
Web Design and interactive
(PHP).
web applications
and 3 using
Apply php scripting concepts and
Development II programming
languages such as principles, including variables, data types,
PHP, JavaScript, control structures, and functions.
and server-side Identify form handling, validation, session
frameworks. and cookie in server side scripting 2
language.

Apply Database creation with Mysql and


connection and manipulation using PHP.

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

Tinsae D.@2024 Fundamentals of database


Introduction

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.

Tinsae D.@2024 Fundamentals of database


Learning Outcome

By the end of this module, students will be able to:

• Demonstrate a comprehensive understanding of basic database terminologies, enabling


effective communication within the realm of database management.
• Navigate the process of conceptual database design, outlining the initial blueprint for
structuring data within relational databases.
• Apply fundamental concepts in logical database design to organize data logically, ensuring
efficient data retrieval and manipulation.
• Translate Entity-Relationship (ER) diagrams into relational schemas and subsequently into
database tables, facilitating the practical implementation of database designs.
• Grasp the essential principles of physical database design, optimizing database
performance and storage efficiency.
• Utilize SQL statements proficiently to create and manipulate databases, including the
creation, modification, and deletion of database structures.
• Execute SQL statements to insert data into tables and delete data from tables, mastering
the fundamental operations of data manipulation within a relational database environment.
• Design simple databases while applying normalization concepts, ensuring data integrity
and minimizing redundancy within database structures.

Tinsae D.@2024 Fundamentals of database


Unit 1: Introduction to database systems

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)

1.2. DBMS - database management system

Tinsae D.@2024 Fundamentals of database


A Database Management System (DBMS) is a software application that facilitates the creation,
organization, and management of databases. It serves as an intermediary between users and the
underlying database, providing a set of tools and utilities for defining, manipulating, and accessing
data stored in the database. DBMSs are designed to handle large volumes of data efficiently and
support various data models, storage mechanisms, and access methods.
One of the primary functions of a DBMS is to ensure data integrity and consistency within the
database. It achieves this by enforcing data constraints, such as primary key, foreign key, and
uniqueness constraints, to maintain the accuracy and reliability of the stored data. Additionally, a
DBMS provides mechanisms for transaction management, allowing multiple users to concurrently
access and modify the database while ensuring ACID properties (Atomicity, Consistency,
Isolation, Durability).
Here are some examples of DBMS
Relational Database Management System (RDBMS)
• Examples: MySQL, PostgreSQL, Oracle Database, Microsoft SQL Server
• Organizes data into tables with rows and columns
• Supports SQL for data manipulation and querying
• Enforces relationships between tables using primary and foreign keys
NoSQL Database
• Examples: MongoDB, Cassandra, Redis, Couchbase
• Supports flexible data models such as document store, key-value store, column-
family store, and graph databases
• Designed for handling large volumes of unstructured or semi-structured data
• Offers scalability, high availability, and fault-tolerance
In-Memory Database
• Examples: Redis, Memcached, Oracle TimesTen
• Stores data primarily in memory for faster access and retrieval
• Suitable for applications requiring high-performance data processing and real-
time analytics
• Offers features like data replication, persistence, and durability
Cloud Database
• Examples: Amazon RDS, Google Cloud SQL, Microsoft Azure SQL Database
• Hosted on cloud infrastructure, providing scalability, elasticity, and pay-as-you-
go pricing
• Offers features such as automated backups, data replication, and disaster recovery
• Supports integration with cloud-native services and platforms
Columnar Database
• Examples: Amazon Redshift, Google BigQuery, Apache Cassandra
• Stores data in columns rather than rows, enabling efficient query processing and
analytics
• Suitable for data warehousing and analytical workloads
• Offers features like compression, partitioning, and parallel processing

Tinsae D.@2024 Fundamentals of database


Graph Database
• Examples: Neo4j, Amazon Neptune, TigerGraph
• Models data as nodes, edges, and properties, representing relationships between
entities
• Enables efficient traversal of complex networks and graph structures
• Suitable for applications requiring real-time recommendations, social network
analysis, and fraud detection
Object-Oriented Database
• Examples: db4o, ObjectDB, ObjectStore
• Stores data in the form of objects, supporting encapsulation, inheritance, and
polymorphism
• Suitable for applications with complex data structures and object-oriented
programming paradigms
• Offers features like object persistence, indexing, and query optimization

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

Tinsae D.@2024 Fundamentals of database


• Stores information about library users, circulation history, and inventory status
Hospital Management System
• Manages patient records, medical histories, and treatment plans
• Tracks appointments, admissions, and discharges
• Stores information about healthcare providers, facilities, and medical procedures
Inventory Management System
• Tracks inventory levels, stock movements, and product sales
• Manages orders, shipments, and supplier information
• Supports features like barcode scanning, stock alerts, and inventory forecasting
Human Resources Management System (HRMS)
• Manages employee records, payroll processing, and benefits administration
• Tracks employee attendance, performance evaluations, and training programs
• Stores information about job positions, salaries, and organizational structure
Customer Relationship Management (CRM) System
• Manages customer interactions, sales leads, and marketing campaigns
• Tracks customer contacts, purchases, and service requests
• Stores information about customer preferences, demographics, and
communication history
Financial Management System
• Manages financial transactions, accounting records, and budgeting activities
• Tracks income, expenses, assets, and liabilities
• Supports features like invoicing, billing, and financial reporting
Point of Sale (POS) System
• Manages retail sales transactions, inventory levels, and customer orders
• Tracks product prices, discounts, and payment methods
• Stores information about sales receipts, customer profiles, and sales analytics
Hotel Management System
• Manages hotel reservations, room assignments, and guest check-ins/check-outs
• Tracks room availability, rates, and occupancy levels
• Stores information about guest preferences, booking history, and hotel amenities

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.

Tinsae D.@2024 Fundamentals of database


• File Manager manipulates the underlying storage files and manages the allocation of
storage space on disk.
• DML preprocessor converts DML statements embedded in an application program into
standard function calls in the host language.
• DDL compiler converts DDL statements into a set of tables containing metadata. These
tables are then stored in the system catalog.
• Catalog manager manages access to and maintains the system catalog. The system catalog
is accessed by most DBMS components
1.4.A database system versus a file-based system
In a file-based system, data is stored in individual files or documents, often organized in directories
or folders. Each file typically represents a specific data entity or collection of related data, and data
manipulation is performed directly on these files using file operations provided by the operating
system. While file-based systems are simple and easy to implement, they lack centralized control
and structure, leading to issues such as data redundancy, inconsistency, and difficulty in data
retrieval and maintenance. Moreover, file-based systems are prone to data security risks, as there
is limited access control and no built-in mechanisms for enforcing data integrity constraints.

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.

Tinsae D.@2024 Fundamentals of database


This helps maintain data consistency and prevents data corruption or loss due to errors or
inconsistencies.
• Efficient Data Retrieval: Database systems support powerful querying mechanisms that
allow users to retrieve and manipulate data efficiently. Queries can be performed using
structured query languages (e.g., SQL), enabling complex data retrieval operations,
filtering, sorting, and aggregation.
• Concurrent Access and Transaction Management: Database systems support
concurrent access by multiple users, allowing them to access and manipulate data
simultaneously. Transaction management features ensure that database transactions are
executed reliably and consistently, following the principles of ACID (Atomicity,
Consistency, Isolation, Durability).
• Scalability and Performance: Database systems are designed to scale with growing data
volumes and user loads. They offer features like indexing, query optimization, and data
partitioning to improve performance and scalability, ensuring that the system can handle
increasing data and user demands effectively.
• Data Security and Access Control: Database systems provide robust security
mechanisms to protect sensitive data from unauthorized access and ensure compliance with
privacy regulations. They offer features like authentication, authorization, and encryption
to control access to data and safeguard against security threats.
• Data Backup and Recovery: Database systems offer features for data backup and
recovery, allowing users to create backups of their data and restore it in the event of data
loss or system failures. This helps ensure data availability and reliability, minimizing the
risk of data loss due to hardware failures, disasters, or human errors.

Disadvantages of a file-based system


A file-based system with different disadvantages organization is shifting to a database system and
some of the disadvantages of a file base system are:
• Data Redundancy and Inconsistency: In a file-based system, data redundancy and
inconsistency are common issues. Since data is often stored in multiple files, duplicate
copies of the same data may exist, leading to redundancy. Moreover, if the same data is
updated in one file but not in others, inconsistencies can arise, resulting in data integrity
problems.
• Limited Data Sharing and Accessibility: File-based systems typically lack centralized
control and management, making it difficult to share and access data across different
applications or users. Each application may have its own set of files and data formats,
making it challenging to integrate or exchange data between systems.
• Data Isolation and Fragmentation: Data in a file-based system is often isolated within
individual files or applications, leading to data fragmentation. This fragmentation makes it
difficult to view or analyze data comprehensively, as it may be scattered across multiple
files or systems with no centralized view.
• Difficulty in Data Manipulation and Querying: Performing data manipulation or
querying operations in a file-based system can be cumbersome and error-prone. Since data

Tinsae D.@2024 Fundamentals of database


is stored in raw file formats, users may need to write custom scripts or programs to extract,
transform, and analyze data, which can be complex and time-consuming.
• Limited Data Integrity and Security: File-based systems typically lack built-in
mechanisms for ensuring data integrity and security. There is no centralized control over
data access or modification, making it challenging to enforce data consistency, integrity
constraints, or security policies across multiple files or applications.
• Scalability and Performance Issues: As data volume and user loads grow, file-based
systems may encounter scalability and performance issues. Since data is stored in
individual files, accessing or managing large volumes of data can become inefficient and
slow, leading to degraded system performance and responsiveness.

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.

Unit 1: Summary Questions

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?

Tinsae D.@2024 Fundamentals of database


Unit 2: Data models

2.1. What are data models

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.

Tinsae D.@2024 Fundamentals of database


2. Hierarchical Model: Represents data in a tree-like structure, where each record has one
parent record and zero or more child records. It is commonly used in hierarchical databases
like IMS (Information Management System).
3. Network Model: Extends the hierarchical model by allowing each record to have multiple
parent and child records, forming complex networks of relationships. It is used in network
databases like CODASYL (Conference on Data Systems Languages).
4. Object-Oriented Model: Represents data as objects containing attributes and methods,
enabling encapsulation, inheritance, and polymorphism. It is suitable for object-oriented
programming paradigms and is used in object-oriented databases (OODBMS) like db4o
and ObjectDB.
5. Entity-Relationship Model (ER Model): Represents data using entities, attributes, and
relationships, providing a graphical notation for designing databases. It is commonly used
in conceptual data modeling and database design.
6. Document-Oriented Model: Stores data in flexible document formats such as JSON
(JavaScript Object Notation) or XML (eXtensible Markup Language), allowing schema-
less data storage and dynamic schema evolution. It is used in document-oriented databases
(NoSQL) like MongoDB, Couchbase, and Amazon DynamoDB.
7. Columnar Model: Stores data in columns rather than rows, enabling efficient query
processing and analytics. It is commonly used in columnar databases like Amazon
Redshift, Google BigQuery, and Apache Cassandra for data warehousing and analytical
workloads.
8. Key-Value Model: Stores data as key-value pairs, where each key is unique and associated
with a corresponding value. It is used in key-value stores and distributed databases like
Redis, Riak, and Amazon DynamoDB for high-speed data access and caching.

2.2. Database system design and development


Database system design and development play a pivotal role in modern information management,
providing a structured approach to organizing, storing, and accessing data efficiently. At the core
of database system design is the conceptualization and modeling of data, where database designers
analyze the requirements of the system and define the entities, attributes, relationships, and
constraints that will govern the data. This process involves translating real-world business
processes and information requirements into a logical and coherent data model, such as the
relational model, hierarchical model, or object-oriented model. Database designers leverage
various tools and techniques, including Entity-Relationship Diagrams (ERDs), Unified Modeling
Language (UML), and normalization techniques, to ensure that the database schema accurately
represents the underlying domain and supports the desired functionalities and operations.

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

Tinsae D.@2024 Fundamentals of database


database objects to support data manipulation, retrieval, and management operations. Throughout
the development process, database developers adhere to best practices and principles of database
design, such as normalization, indexing, and data integrity enforcement, to ensure the reliability,
scalability, and maintainability of the database system. Ultimately, effective database system
design and development are essential for building robust and efficient information systems that
meet the needs of organizations and facilitate data-driven decision-making.

What are the steps required to develop a database system?


Developing a database system involves several key steps to ensure the successful design,
implementation, and deployment of the system. Here's an overview of the typical steps involved
in developing a database system:

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.

Tinsae D.@2024 Fundamentals of database


6. Testing:
• Test the database system to ensure that it meets the specified requirements and
functions as expected.
• Perform unit testing, integration testing, and system testing to identify and address
any defects or issues.
• Validate data integrity, concurrency control, security, and performance aspects of
the database system.
7. Deployment:
• Deploy the database system to the production environment or relevant stakeholders.
• Ensure proper configuration, security settings, and access controls are in place.
• Monitor the system during deployment to address any issues or concerns that arise.
8. Maintenance and Optimization:
• Monitor the performance and usage of the database system in production.
• Perform regular maintenance tasks such as backups, updates, and patches to ensure
system reliability and security.
• Continuously optimize the database system based on usage patterns, feedback, and
changing requirements to improve performance and efficiency over time.

Part of the Real


World

Problem

Requirement
Analysis

Functional Requirement Data Requirement

Functional Analysis Conceptual Design

High-level Transaction Conceptual Schema


DBMS Specification
Independent (High-level

Implementation
(Logical) Design

Application Program
DBMS Implementation
Design
Dependent (Logical) Schema

Application Program Physical


Structure
Design
Internal Schema
Implementation
(Low-level
Tinsae D.@2024 Fundamentals of database
Application Program

Fig Database System Design Steps


2.3. Conceptual Design
Entity – Relationship Model
An Entity-Relationship (ER) model is a high-level conceptual data model used to represent the
structure and relationships of data within a database. It provides a graphical representation of the
entities, attributes, and relationships that exist within a system. The ER model is based on the
principle of Entity-Relationship Diagrams (ERDs).

Components of E-R model


The Entity-Relationship (ER) model consists of several components that together define the
structure and relationships of data within a database. These components include
• entities
• attributes
• relationships and
• cardinality constraints.
Entity
An entity in the ER model represents a real-world object or concept that is distinguishable from
other objects. Entities are depicted as rectangles in an Entity-Relationship Diagram (ERD). Each
entity is described by a set of attributes that define its properties or characteristics. For example,
in a database for a university, entities could include Student, Course, and Instructor and each
should be represented as below.

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

Tinsae D.@2024 Fundamentals of database


Types of attributes
There are different types of attributes that each should be identified in the E-R diagram some of
the commons are:
1. Simple Attribute: An attribute that cannot be divided into smaller parts.
• Example:
• StudentID
• Name
• Sex
• E-Diagram Representation
• oval

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)

Tinsae D.@2024 Fundamentals of database


• E-Diagram Representation
• Doted oval

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

5. Key Attribute: An attribute that uniquely identifies each instance of an entity.


• Example:
• StudentID (unique identifier for each student)
• ISBN (unique identifier for each book)

• 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

Tinsae D.@2024 Fundamentals of database


Relationships
Relationships in the ER model represent associations or connections between entities. They
describe how entities are related to each other in the database. Relationships are depicted using
Diamonds and lines connecting entities in an ERD, with optional labels indicating the nature of
the relationship. Common types of relationships include one-to-one, one-to-many, and many-to-
many. For example, a relationship between Student and Course entities could be "enrolls in,"
indicating that a student can enroll in multiple courses.

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.

Tinsae D.@2024 Fundamentals of database


A many-to-one (N:1) cardinality constraint indicates that multiple instances of one entity can be
associated with a single instance of another entity. In a many-to-one relationship, multiple
instances of one entity are associated with exactly one instance of another entity. This means that
multiple records or instances of the first entity can relate to a single record or instance of the second
entity.

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

Fig: Sample E-R diagram

Tinsae D.@2024 Fundamentals of database


2.4. Logical Design
Relational Model
Relational data model is the primary data model, which is used widely around the world for data
storage and processing. This model is simple and it has all the properties and capabilities required
to process data with storage efficiency.

Concepts in Relational Model

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

Example: STUDENT Relation

NAME ROLL_NO PHONE_NO ADDRESS AGE

Ram 14795 7305758992 Noida 24

Shyam 12839 9026288936 Delhi 35

Laxman 33289 8583287182 Gurugram 20

Mahesh 27857 7086819134 Ghaziabad 27

Ganesh 17282 9028 9i3988 Delhi 40

Tinsae D.@2024 Fundamentals of database


o In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS, and AGE are the
attributes.
o The instance of schema STUDENT has 5 tuples.
o t3 = <Laxman, 33289, 8583287182, Gurugram, 20>

Properties of Relations (tables)

o Name of the relation is distinct from all other relations.


o Each relation cell contains exactly one atomic (single) value
o Each attribute contains a distinct name
o Attribute domain has no significance
o tuple has no duplicate value
o Order of tuple can have a different sequence

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.

Key constraints force that −

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

Key constraints are also referred to as Entity Constraints.

Tinsae D.@2024 Fundamentals of database


ii. Domain Constraints

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.

iii. Referential integrity Constraints

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.

E-R model vs Relational model

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 contrast, the Relational model is implementation-focused, detailing how data is stored,


organized, and manipulated within a relational database management system (RDBMS). It
structures data into tables, with each table representing an entity, and establishes relationships
between tables using primary and foreign key constraints. Normalization principles, integral to the
Relational model, guide the organization of tables into normalized forms, reducing redundancy
and dependency. The Relational model employs SQL (Structured Query Language) as its
standardized Data Manipulation Language (DML), facilitating data querying and manipulation
operations such as INSERT, SELECT, UPDATE, and DELETE.

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.

Tinsae D.@2024 Fundamentals of database


Note: Experience database designers can directly use Relational model, how ever it is highly
recommended to use E-R modeling (conceptual model) then map it to Relational model (Logical
model).

2.5. Converting E-R diagram to Relations

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.

Tinsae D.@2024 Fundamentals of database


7. Do Normalization to the Tables (Normalization): Normalization is the process of
organizing tables to minimize redundancy and dependency. It involves breaking down
larger tables into smaller, more manageable ones and applying normalization rules to
ensure data integrity.
8. Define Constraints (Constraints): Additional constraints, such as unique constraints or
check constraints, may be defined to enforce data integrity rules beyond primary and
foreign key constraints.
9. Validate the Schema (Schema Definition): The resulting database schema is validated to
ensure that it accurately represents the structure and relationships depicted in the original
E-R diagram. This includes verifying table definitions, column datatypes, and constraints.

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

Tinsae D.@2024 Fundamentals of database


cannot be further divided. This eliminates repeating groups of attributes and ensures that each
column holds a single value for each row.

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:

Student ID Student Name Course ID Course Name


1 Alice 101, 102 Math, Science
2 Bob 101, 103, 104 Math, English, IT

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:

Student ID Student Name Course ID Course Name


1 Alice 101 Math
1 Alice 102 Science
2 Bob 101 Math
2 Bob 103 English
2 Bob 104 IT

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.

Let's illustrate this with an example:

Tinsae D.@2024 Fundamentals of database


Consider a table that stores information about employees and the projects they are assigned to,
with the following structure:

Employee ID Employee Name Project ID Project Name Department


1 Alice 101 Project X HR
2 Bob 102 Project Y IT
1 Alice 103 Project Z HR

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.

After normalization, the tables might look like this:

Employee Table:

Employee ID Employee Name Department


1 Alice HR
2 Bob IT

Project Table:

Project ID Project Name


101 Project X
102 Project Y
103 Project Z

Assignment Table:

Employee ID Project ID
1 101
2 102

Tinsae D.@2024 Fundamentals of database


Employee ID Project ID
1 103

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.

Let's illustrate 3NF with an example:

Consider a table that stores information about courses and instructors, with the following structure:

Course Code Course Name Instructor Name Instructor Office


CS101 Introduction to Computer Science Prof. Smith Room 101
CS102 Database Management Systems Prof. Johnson Room 102
CS103 Web Development Prof. Smith Room 101

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.

After normalization, the tables might look like this:

Course Table:

Course Code Course Name


CS101 Introduction to Computer Science
CS102 Database Management Systems
CS103 Web Development

Tinsae D.@2024 Fundamentals of database


Instructor Table:

Instructor Name Instructor Office


Prof. Smith Room 101
Prof. Johnson Room 102

Course Instructor Table:

Course Code Instructor Name


CS101 Prof. Smith
CS102 Prof. Johnson
CS103 Prof. Smith

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.

Unit 2: summary questions

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?

Tinsae D.@2024 Fundamentals of database


Unit 3: Structured Query Language (SQL)

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.

Generally Structured query language (SQL) is:

• The ANSI standard language for operating relational databases


• Efficient, easy to learn, and use
• Functionally complete (With SQL, you can define, retrieve, and
manipulate data in thetables.)

SQL also provides statements for a variety of tasks, including:

• 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

Tinsae D.@2024 Fundamentals of database


SQL Statements

Table: SQL statements

NO SQL Statements SQL Descriptions


Command
1 Data definition CREATE Sets up, changes, and
language (DDL)
ALTER DROP removes data structures from
RENAME tables. Collectivelyknown as
TRUNCATE data definition language
(DDL)
2 Data manipulation SELECT Retrieves data from the
language(DML) INSERT database, enters new rows,
UPDATE changes existingrows, and
DELETE removes unwanted rows from
tables in
the database, respectively.
Collectively known as data
manipulation language
(DML)
3 Data control GRANT Provides or removes access
language (DCL) REVOKE rights toboth the Oracle
database and the structures
within it

1. Data Definition Language (DDL)

Data definition language (DDL) refers to the set of SQL commands that can create and

Tinsae D.@2024 Fundamentals of database


manipulate the structures of a database. DDL statements are used to create, change, and remove
objects including indexes, triggers, tables, and views. Common DDL statements include:
• CREATE (generates a new table)
• ALTER (alters table)
• DROP (removes a table from the database)
1.1. CREATE Command

The create command allow the creation of the database objects and table.
• The syntax for creating a table is this:

CREATE TABLE table name (field name data type);

For example:

to create Artists Table with artistName column

CREATE TABLE Artists (artistName varchar(50));

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

The Create command is also used to create a database

SQL CREATE DATABASE Syntax

CREATE DATABASE database_name

Example

Tinsae D.@2024 Fundamentals of database


• Now we want to create a database called "my_db".
• We use the following CREATE DATABASE statement:
CREATE DATABASE my_db

The after Database tables can be added with the CREATE TABLE statement.

Creating SQL Table


The CREATE TABLE Statement
Database Tables
• A database most often contains one or more tables. Each table is identified by a name
(e.g. "Customers" or "Orders"). Tables contain records (rows) with data.
• Below is an example of a table called "Persons":
Table 4.1 Person Table

P_Id LastName FirstName Address City

1 Aberu Ola AA Areda Subsity

2 Chala sanyi W/shoa Ambo

3 Mohammad Kari Arsi Asella

Tinsae D.@2024 Fundamentals of database


The table above contains three records (one for each person) and five columns (P_Id,
LastName, FirstName, Address, and City).

The CREATE TABLE statement is used to create the table in a database.

SQL CREATE TABLE Syntax

CREATE TABLE table_name(

column_name1
data_type,
column_name2
data_type,
column_name3
data_type,

....
)

Tinsae D.@2024 Fundamentals of database


CREATE TABLE
Persons(
P_Id int,
LastName
varchar(255),
FirstName
varchar(255),
Address
varchar(255),
City
varchar(255)
)

CREATE TABLE Example


Now we want to create a table called "Persons" that contains five columns: P_Id, LastName,
FirstName, Address, and City.

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:

Table: The table structure is created based on example

P_Id LastName FirstName Address City

The empty table can be filled with data with the INSERT INTO statement.

Tinsae D.@2024 Fundamentals of database


1.1.1. SQL Constraints

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

ii. SQL PRIMARY KEY Constraint on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table
is created:

Tinsae D.@2024 Fundamentals of database


Example: The following code is applying the primary key constraint during table creation.

CREATE TABLE Persons(

P_Id int NOT NULL PRIMARY KEY,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Address varchar(255),

City varchar(255)

Example : the following code is allowing naming of a PRIMARY KEY constraint for
multiple columns

CREATE TABLE Persons(

P_Id int NOT NULL,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Address varchar(255),City

varchar(255),

CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

Tinsae D.@2024 Fundamentals of database


iii. SQL PRIMARY KEY Constraint on ALTER TABLE

To create a PRIMARY KEY constraint on the "P_Id" column when the table is already
created, use the following SQL:

ALTER TABLE Persons ADD

PRIMARY KEY (P_Id)

1.2. ALTER Command


Ok, say you've created a table, Artists, and forgot to add a primary key to the table.

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.

ALTER TABLE Artists ADD PRIMARY KEY (artist_pk);

Tinsae D.@2024 Fundamentals of database


Example : The following code allows to create a foreign key on album table and reference to
parent table Artist.

ALTER TABLE Album

ADD CONSTRAINT artist_fk FOREIGN KEY

(albumArtistID)REFERENCES Artist (artistID);

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.

SQL ALTER TABLE Syntax

To add a column in a table, use the following syntax:

ALTER TABLE table_nameADD

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

ALTER TABLE table_name

DROP COLUMN column_name

Tinsae D.@2024 Fundamentals of database


To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name

ALTER COLUMN column_name datatype

SQL ALTER TABLE Example

Table 4.3 To apply alter command on person table

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons

ADD DateOfBirth date

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.

The "Persons" table will now like this:

Table: The effect of alter command to add DateOfBirth column on person table

P_Id LastName FirstName Address City DateOfBirth

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

Tinsae D.@2024 Fundamentals of database


3 Pettersen Kari Storgt 20 Stavanger

Change Data Type Example

Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:

ALTER TABLE Persons

ALTER COLUMN Date Of Birth year

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.

1.3. DROP Command


So, to drop or remove a table, use DROP TABLE table name;

If you need to remove a constraint, use the DROP command in combination with the ALTER
statement like this:

1. ALTER TABLE Artists


2. DROP CONSTRAINT ArtistID;

DROP COLUMN Example

Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons


DROP COLUMN Date Of Birth

The "Persons" table will now like this:

The effect of alter command to remove DateOfBirth column from Person Table

Tinsae D.@2024 Fundamentals of database


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Tinsae D.@2024 Fundamentals of database


2. SQL Data Manipulation Language (DML)

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

I. SELECT – to query data in the database


II. INSERT – to insert data into a table
III. UPDATE – to update data in a table
IV. DELETE – to delete data from a table

2.1. Select Statement

The SELECT statement is used to select data from a database.

The result is stored in a result table, called the result-set.

SQL SELECT Syntax

SELECT column_name(s)
FROM table_name

Tinsae D.@2024 Fundamentals of database


and
SELECT * FROM table_name

An SQL SELECT Example

The persons table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

SELECT LastName,FirstName FROM Persons

The result-set will look like this:

Table FirstName and LastName is projected from table 4.2


LastName FirstName

Hansen Ola

Svendson Tove

Pettersen Kari

SELECT * Example
Now we want to select all the columns from the "Persons" table.

Tinsae D.@2024 Fundamentals of database


We use the following SELECT statement:

SELECT * FROM Persons

Tip: The asterisk (*) is a quick way of selecting all columns!

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

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.

SQL WHERE Clause


• The WHERE clause is used to filter records.
The WHERE Clause

The WHERE clause is used to extract only those records that fulfill a specified criterion.

SQL WHERE Syntax

SELECT column_name(s)

FROM table_name

WHERE Clause Example

Tinsae D.@2024 Fundamentals of database


The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the persons living in the city "Sandnes" from the table above.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE City='Sandnes'

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

Quotes Around Text Fields

SQL uses single quotes around text values (most database systems will also accept double quotes).
Although, numeric values should not be enclosed in quotes.

Operators Allowed in the WHERE Clause

With the WHERE clause, the following operators can be used:

Table SQL operators

Tinsae D.@2024 Fundamentals of database


Operator Description

= Equal

<> Not equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

BETWEEN Between an inclusive range

LIKE Search for a pattern

IN If you know the exact value you want to return for at least one of the columns

Tinsae D.@2024 Fundamentals of database


Note: In some versions of SQL the <> operator may be written as !=

SQL AND & OR Operators

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

AND Operator Example

Refer table apply SQL AND and OR operator

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the persons with the first name equal to "Tove" AND the last name
equal to "Svendson":

SELECT * FROM Persons

WHERE FirstName='Tove'

AND LastName='Svendson'

Tinsae D.@2024 Fundamentals of database


The result-set will look like this:

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

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

SELECT * FROM Persons

WHERE FirstName='Tove'

OR FirstName='Ola'

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

Combining AND & OR

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

Tinsae D.@2024 Fundamentals of database


SELECT * FROM Persons WHERE

LastName='Svendson'

AND (FirstName='Tove' OR FirstName='Ola')

The result-set will look like this:

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

SQL ORDER BY Keyword

• The ORDER BY keyword is used to sort the result-set.


• The ORDER BY keyword is used to sort the result-set by a specified column.
• The ORDER BY keyword sort the records in ascending order by default.
• If you want to sort the records in a descending order, you can use the DESC
keyword.SQL ORDER BY Syntax

SELECT column_name(s)

ORDER BY Example

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

Tinsae D.@2024 Fundamentals of database


2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Tom Vingvn 23 Stavanger

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:

SELECT * FROM Persons


ORDER BY LastName

The result-set will look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

4 Nilsen Tom Vingvn 23 Stavanger

3 Pettersen Kari Storgt 20 Stavanger

2 Svendson Tove Borgvn 23 Sandnes

ORDER BY DESC Example


Now we want to select all the persons from the table above, however, we want to sort the persons
descending by their last name.

Tinsae D.@2024 Fundamentals of database


SELECT * FROM Persons ORDER BY
LastName DESC

Tinsae D.@2024 Fundamentals of database


The result-set will look like this:

P_Id LastName FirstName Address City

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Tom Vingvn 23 Stavanger

1 Hansen Ola Timoteivn 10 Sandnes

2.2. SQL UPDATE Statement

The UPDATE statement is used to update existing records in a table.


SQL UPDATE Syntax

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:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

Tinsae D.@2024 Fundamentals of database


2 Svendson Tove Borgvn 23 Sandnes

Tinsae D.@2024 Fundamentals of database


3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

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'

The "Persons" table will now look like this:


P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

5 Tjessem Jakob Nissestien 67 Sandnes

SQL UPDATE Warning


Be careful when updating records. If we had omitted the WHERE clause in the example above,
like this:

UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'

Tinsae D.@2024 Fundamentals of database


The "Persons" table would have looked like this:

Tinsae D.@2024 Fundamentals of database


P_Id LastName FirstName Address City

1 Hansen Ola Nissestien 67 Sandnes

2 Svendson Tove Nissestien 67 Sandnes

3 Pettersen Kari Nissestien 67 Sandnes

4 Nilsen Johan Nissestien 67 Sandnes

5 Tjessem Jakob Nissestien 67 Sandnes

2.3. SQL DELETE Statement


The DELETE statement is used to delete records/ rows in a table.
SQL DELETE Syntax
DELETE FROM table_name WHERE
some_column=some_value
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!
SQL DELETE Example
The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes

Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.

Tinsae D.@2024 Fundamentals of database


DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

Delete All Rows


It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

DELETE FROM table_nameor

DELETE * FROM table_name

Note: Be very careful when deleting records. You cannot undo this statement!

2.4. SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.
SQL INSERT INTO Syntax

Tinsae D.@2024 Fundamentals of database


It is possible to write the INSERT INTO statement in two forms.

Tinsae D.@2024 Fundamentals of database


The first form doesn't specify the column names where the data will be inserted, only their
values:

INSERT INTO table_name


VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

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


VALUES (value1, value2, value3,...)

SQL INSERT INTO Example


We have the following "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

Now we want to insert a new row in the "Persons" table.


We use the following SQL statement:

INSERT INTO Persons


VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')

The "Persons" table will now look like this:


P_Id LastName FirstName Address City

Tinsae D.@2024 Fundamentals of database


1 Hansen Ola Timoteivn 10 Sandnes

Tinsae D.@2024 Fundamentals of database


2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

Insert Data Only in Specified Columns


It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the "P_Id", "LastName"
and the "FirstName" columns:

INSERT INTO Persons (P_Id, LastName, FirstName)


VALUES (5, 'Tjessem', 'Jakob')

The "Persons" table will now look like this:


P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

4 Nilsen Johan Bakken 2 Stavanger

5 Tjessem Jakob

3. SQL Data Control Language (DCL)


Introduction to DCL

DCL used to control user access in a database.

Tinsae D.@2024 Fundamentals of database


DCL commands are as follows,
1. GRANT
2. REVOKE

It is used to grant or revoke access permissions from any database user.

1. GRANT COMMAND

• GRANT command gives the user's access privileges to the database.


• This command allows specified users to perform specific tasks.

Syntax:

GRANT <privilege list>


ON <relation name or view name>
TO <user/role list>;

Example: GRANT Command

GRANT ALL ON employee


TO ABC;
[WITH GRANT OPTION]

In the above example, user 'ABC' has been permitted to view and modify the records in the
'employee' table.

Tinsae D.@2024 Fundamentals of database


2. REVOKE COMMAND
• REVOKE command is used to cancel previously granted or denied permissions.
• This command withdraws access privileges given with the GRANT command.
• It takes back permissions from the user.

Syntax:

REVOKE <privilege list>


ON <relation name
or view name>
FROM <user
name>;

Example: REVOKE Command

REVOKE UPDATE
ON employee FROM ABC;

Difference between GRANT and REVOKE command.

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:

o The select operation selects tuples that satisfy a given predicate.


o It is denoted by sigma (σ).

1. Notation: σ p(r)

Where:

σ is used for selection prediction


r is used for relation
p is used as a propositional logic formula which may use connectors like: AND OR and NOT.
These relational can use as relational operators like =, ≠, ≥, <, >, ≤.

For example: LOAN Relation

BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500


Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input:

1. σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

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

A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn


Brooks Senator Brooklyn

Input:

1. ∏ NAME, CITY (CUSTOMER)

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

A union operation must hold the following condition:

o R and S must have the attribute of the same number.


o Duplicate tuples are eliminated automatically.

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:

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)

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

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)

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

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)

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

EMP_ID EMP_NAME EMP_DEPT

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:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

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

1. Operation: (EMPLOYEE ⋈ SALARY)

Result:

EMP_CODE EMP_NAME SALARY


101 Stephan 50000

102 Jack 30000

103 Harry 25000

Types of Join operations:

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:

1. ∏EMP_NAME, SALARY (EMPLOYEE ⋈ SALARY)

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

EMP_NAME STREET CITY

Ram Civil line Mumbai

Shyam Park street Kolkata

Ravi M.G. Street Delhi

Hari Nehru nagar Hyderabad

FACT_WORKERS
EMP_NAME BRANCH SALARY

Ram Infosys 10000

Shyam Wipro 20000

Kuber HCL 30000

Hari TCS 50000

Input:

1. (EMPLOYEE ⋈ FACT_WORKERS)

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru nagar Hyderabad TCS 50000

An outer join is basically of three types:

a. Left outer join


b. Right outer join
c. Full outer join

a. Left outer join:

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

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟕ FACT_WORKERS
EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

b. Right outer join:

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

Example: Using the above EMPLOYEE table and FACT_WORKERS Relation

Input:

1. EMPLOYEE ⟖ FACT_WORKERS

Output:

EMP_NAME BRANCH SALARY STREET CITY

Ram Infosys 10000 Civil line Mumbai

Shyam Wipro 20000 Park street Kolkata

Hari TCS 50000 Nehru street Hyderabad

Kuber HCL 30000 NULL NULL


c. Full outer join:

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

Example: Using the above EMPLOYEE table and FACT_WORKERS table

Input:

1. EMPLOYEE ⟗ FACT_WORKERS

Output:

EMP_NAME STREET CITY BRANCH SALARY

Ram Civil line Mumbai Infosys 10000

Shyam Park street Kolkata Wipro 20000

Hari Nehru street Hyderabad TCS 50000

Ravi M.G. Street Delhi NULL NULL

Kuber NULL NULL HCL 30000

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:

CLASS_ID NAME PRODUCT_ID CITY

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.

Tinsae D@2024 Internet and web design


Learning Objectives
Based on this module students will be able to:

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:

• Write JavaScript code to manipulate HTML elements dynamically, responding to user


interactions and events to create interactive web experiences.
• Apply JavaScript principles to enhance website functionality, including form validation, DOM
manipulation, and asynchronous data loading, to create engaging and responsive web
applications.

Tinsae D@2024 Internet and web design


Unit 1: Fundamentals of Internet and the Web

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

1.1.What is the difference between internet and world wide web?

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.

1.2. Applications of the Internet


The Internet offers a wide range of services and applications that enable users to perform various
tasks.
• World Wide Web (WWW): The web as a collection of interconnected websites, web
pages, and multimedia content accessible through web browsers.
• Email: Electronic mail services that allow users to send and receive messages and
attachments across the Internet.
• Social Media: Platforms that enable users to connect, share, and communicate with
others, fostering online communities and user-generated content.
• Online Streaming: Services for streaming audio, video, and other multimedia content,
such as music, movies, TV shows, and live events.
• E-commerce: Online platforms for buying and selling goods and services, facilitating
electronic transactions and global marketplaces.
• Cloud Computing: The delivery of computing resources, including storage, servers,
and software, over the Internet, providing on-demand access and scalability.

1.3. How the World Wide Web Works

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.

Tinsae D@2024 Internet and web design


All the websites are stored in web servers. Just as someone lives on rent in a house, a website
occupies a space in a server and remains stored in it. The server hosts the website whenever a user
requests its Webpages, and the website owner has to pay the hosting price for the same. The moment
you open the browser and type a URL in the address bar or search something on Google,the WWW
starts working. There are three main technologies involved in transferring information(web pages)
from servers to clients (computers of users). These technologies include Hypertext Markup
Language (HTML), Hypertext Transfer Protocol (HTTP) and Web browsers.

1.4. Web sites


A website is a collection of web pages and related content that are hosted on a web server and can
be accessed via the World Wide Web. It serves as a virtual space where individuals, organizations,
businesses, and other entities can share information, showcase products or services, communicate
with users, and engage in various online activities. Websites are designed to be viewed using web
browsers, and they can range from simple single-page sites to complex multi-page portals. While
Web pages are documents written in HTML, which is a markup language that defines the structure
and layout of content on the page. HTML tags are used to markup elements such as headings,
paragraphs, images, links, and more.

1.5. Internet Protocols


Internet protocols are a set of rules and standards that dictate how data is transmitted and
communicated across networks within the internet infrastructure. These protocols ensure that devices,
computers, and servers can communicate effectively and reliably, regardless of their location or the
underlying technology used. Without these protocols, the seamless exchange of information that
defines the internet would not be possible. Some of the common internet protocols are:

1.5.1. Transmission Control Protocol (TCP):

Tinsae D@2024 Internet and web design


TCP is a connection-oriented protocol responsible for ensuring reliable and ordered delivery of data
packets between devices on a network. It breaks data into smaller segments, assigns sequence numbers
to each segment for reassembly, and includes error checking to guarantee data integrity.
1.5.2. Internet Protocol (IP):
IP is a fundamental protocol responsible for addressing and routing data packets between devices on
the internet. It assigns unique IP addresses to devices and determines the best path for data packets to
reach their destination across interconnected networks.
1.5.3. Hypertext Transfer Protocol (HTTP):
HTTP is the protocol used for transmitting hypertext documents, such as web pages, between web
servers and clients (e.g., web browsers). It operates over TCP and defines how requests and responses
are formatted and transmitted, enabling users to access and interact with web content.
1.5.4. Hypertext Transfer Protocol Secure (HTTPS):
HTTPS is the secure version of HTTP, providing encrypted communication between web servers and
clients. It uses SSL/TLS encryption to protect sensitive data, such as login credentials and payment
information, from interception and eavesdropping.
1.5.5. File Transfer Protocol (FTP):
FTP is a protocol used for transferring files between computers over a network, typically the internet.
It enables users to upload, download, and manage files on remote servers, providing authentication
and data transfer functionalities.
1.5.6. Simple Mail Transfer Protocol (SMTP):
SMTP is the standard protocol for sending email messages between email servers. It defines how email
messages are formatted, relayed, and delivered, ensuring reliable communication between mail
servers.
1.6.7. Domain Name System (DNS):
DNS translates domain names (e.g., www.example.com) into IP addresses (e.g., 192.0.2.1) that
computers use to identify each other on the internet. It acts as a distributed database, mapping human-
readable domain names to numerical IP addresses and facilitating the resolution of domain names to
IP addresses.
1.6.8. Post Office Protocol (POP) / Internet Message Access Protocol (IMAP):
POP and IMAP are protocols used by email clients to retrieve email messages from mail servers.
POP downloads emails to the client's device and typically deletes them from the server, while IMAP
syncs emails between the server and multiple client devices, allowing users to access their emails from
anywhere.

1.6. HTTP vs HTTPs


HTTP (Hypertext Transfer Protocol) and HTTPS (Hypertext Transfer Protocol Secure) are both
protocols used for communication between clients (such as web browsers) and servers (web
servers). However, they differ in terms of security mechanisms and the way data is transmitted.
Here are the main differences between HTTP and HTTPS:

i.Security

Tinsae D@2024 Internet and web design


HTTP: HTTP does not provide any built-in security measures. Data transmitted over HTTP is sent
in plain text, making it vulnerable to interception and eavesdropping. It does not offer data
encryption or protection against tampering.

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.

iv.Authentication and Trust

Tinsae D@2024 Internet and web design


HTTP: HTTP does not provide any built-in mechanisms for server authentication or establishing
trust. As a result, it is susceptible to man-in-the-middle attacks where attackers can impersonate the
server or intercept and modify the communication.

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.

1.7. Domain Name System (DNS)

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

Tinsae D@2024 Internet and web design


can understand. This hierarchical nature allows for efficient and decentralized management of
domain names across the Internet. The Domain Name System (DNS) can be thought of as the
directory of the Internet. We find an online page or website by typing in the URL – like acme.comor
some-site.com. Our web browsers, on the other hand, need to translate the URL to Internet Protocol
(IP) addresses to find the correct site. It is a DNS that translates domain names to IP addresses so our
browsers can resolve, or connect to, requested Internet resources.
Every single device on the Internet has a unique IP address by which it can be uniquely identifiedby
the other online devices. A DNS server eliminates the need for us to memorize these IP addresses
every time we want to visit a site or connect to a device. It is much easier for us to typein a URL than
IPv4 IP addresses (E.g. 192.168.1.1) or, worse, the more complex IPv6 addresses (E.g.
2400:cb00:2048:1::c629:d7a2).
The DNS architecture consists of a hierarchical and decentralized name resolution system for
computers, services or any other resources connected to the Internet or a private network. It storesthe
various associated information of the domain names assigned to each of the resources. Queriesfor a
resource pass through the DNS – with the URLs as parameters. The DNS then takes the URLs,
translates them into the target IP addresses, and sends the queries towards the correct resource.

How does DNS work?


Let’s delve deeper and see more details on how DNS works. The first thing we need to know is that
there isn’t a single DNS, but a selection of them, that can help resolve a single IP address.
A computer has its own cache of DNS data – a local IP-address-to-URL matching – that it uses for
quick references. But, it can’t store all the information for every website or device out there; hence,the
need for root, recursive, Top Level, Second Level, and authoritative DNS servers.
When a user asks to go to a website, the browser first checks the local DNS cache for the correct
resolution (from URL to IP address) and, if not found, goes:
• Out to the recursive DNS server – which is normally operated by the local ISP
provider
– to check which root DNS server it needs to go to find an answer. Once the address is found,
it is escalated to…
• One of the root DNS servers out there – which are run by about 13 independent
organizations – to find the address of the correct Top Level DNS (TLD) server to query
for the address depending on whether it is a “.com”, “.org” or “.net” site, for
example. Root

Tinsae D@2024 Internet and web design


DNS sit at the top of the DNS hierarchy. It should be noted here that every website addressor
URL has an implied “.” at the end, even if we don’t type it in. This “.” designates (or points
to) the DNS root nameservers at the top of the DNS hierarchy where it can find information
about the correct TLD server to head on to.
• At the TLD server – of which there are about 1000 spread across the globe – the query is
pointed towards the correct authoritative DNS where the required information (IP address)
is actually stored.
• And, at the authoritative DNS server – which holds a broad range of IP address information
– the corresponding IP is sent back to the recursive DNS, which forwards it to the client
machine and the user (you) can go on to the website.
Every time a query is made, the IP address to URL mapping is cached in every DNS for the next user
instead of having to go back and search for the information every single time. This helps in keeping
the servers synchronized and updated and results in faster response times.
DNS hierarchy
The DNS hierarchy, also called the domain name space, is an inverted tree structure. The DNS
hierarchy tree has a single domain at the top of the structure called the root domain – indicated bythe
“.” as we have mentioned above. Below the root domain are the top-level domains that dividethe
DNS hierarchy into segments containing second-level domains, sub-domains, and hosts.

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.

Tinsae D@2024 Internet and web design


Within the hierarchy, the resolution process starts at the Root Level DNS, the Top Level DNS,
working its way down to the Second Level DNS, then through any number of sub-domains until we
get to the actual hostname we want to resolve into an IP address. Let’s have a look at each component
individually to see

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.

1.8.1. Popular Web Browsers

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

Tinsae D@2024 Internet and web design


Summary question for Unit 1

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?

Tinsae D@2024 Internet and web design


Unit 2: HTML

2.1. Introduction to HTML

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:

This is an example of a simple HTML document.

Tinsae D@2024 Internet and web design


Example:

<! DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body>

<h1>It is the First Heading</h1>

<p>It is the first paragraph. </p>

</body>

</html>

Output:

2.1. Different Versions of HTML

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.

Tinsae D@2024 Internet and web design


HTML 1.0:

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.

XHTML (Extensible Hypertext Markup Language):

XHTML emerged as a reformulation of HTML as an application of XML, designed to be more compatible


with XML-based technologies and standards. XHTML 1.0, released in 2000, introduced stricter syntax rules
and required documents to be well-formed XML, helping to improve consistency and interoperability across
different platforms and devices.

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.

2.2. HTML Elements , Tags and Attributes

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:

Figure 2-2 The parts of an HTML container element.

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:

<p>This is a paragraph tag.</p>

Tinsae D@2024 Internet and web design


HTML tags can be categorized into different types based on their purpose and the behavior they define for
the elements. Not all elements have content, however. Some are empty by definition, such as the img
element used to add an image to the page.

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:

<element attribute1="value" attribute2="value">

Tinsae D@2024 Internet and web design


An Element with Attributes

What are the different types of HTML Attributes?


There are three types of HTML attributes:
A. Core Attributes
B. Internationalization Attributes
C. Generic Attributes

A. HTML Core Attributes


The most widely used attribute is core attributes. There are 4 types of core attributes:
• Id

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

Tinsae D@2024 Internet and web design


For example:

<p id= "html"> This is HTML tutorial </p>

<p id= “python”> This is Python tutorial </p>

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:

<h4 title= “hello, motto”> TITLE ATTRIBUTE</p>

The style Attribute:


The style attribute is used to give styling to an HTML element. It is a property of CSS (Cascading Style
Sheet). It is mainly used by the CSS. It is the inline property of an element. In CSS, if we want to style
within an HTML element we use the style attribute in inline of anHTML element.

B. HTML Internationalization Attributes


There are three types of internationalization attributes i.e. dir, lang, xml:lang
The dir Attribute:
The dir attribute tells the browser in which direction should the text flow. There are twotypes of dir
attributes:
ltr: Left to rightrtl: Right to left

Tinsae D@2024 Internet and web design


The lang Attribute:
This attribute is replaced by xml:lang attribute. Earlier it was used to indicate thelanguage for the
web page.
The xml:lang Attribute:
Value for the xml:lang should be ISO-639 country code.

C. HTML Generic Attributes


Generic attributes include various attributes which are mostly used. Some common genericattributes
are:
The “align” Attribute:
align attribute uses align name for HTML element and uses left, right, and center values toindicate the
text accordingly. It is used for horizontal aligns tags.
The “valign” Attribute:
valign attribute uses valign name for HTML element and uses top, middle, and bottom valuesto indicate
the text accordingly. It is used for vertical aligns tags.
The “bgcolor” Attribute:
bgcolor attribute uses bgcolor name to HTML element and uses numeric, hexadecimal, RGBcode values
to change the element's background color accordingly.
The “width” Attribute:
The width attribute uses the width name of the HTML element and uses numeric values tochange the
element’s width according to the numeric given.
The “height” Attribute:
The height attribute uses the height name of the HTML element and uses numeric values tochange the
element’s height according to the numeric given.
The “src” Attribute:
The src attribute is mostly used by the img element that we’ll be going to discuss later. Thissrc attribute
specifies the URL path to that element that is to be displayed. We can choose any of the two paths:
1. Absolute URL - Links to an external image that is hosted on another website.
Example: src="https://www.w3schools.com/images/img_girl.jpg".

Tinsae D@2024 Internet and web design


Notes: External images might be under copyright. If you do not get permission to use it, you may be
in violation of copyright laws. In addition, you cannot control external images; it can suddenly be
removed or changed.
2. Relative URL - Links to an image that is hosted within the website. Here, the URL does not
include the domain name. If the URL begins without a slash, it will be relativeto the current page.
Example: src="img_girl.jpg". If the URL begins with a slash, it will be relative to thedomain.
Example: src="/images/img_girl.jpg".
The “alt” Attribute:
The alt attribute is mostly used by the img element. This alt attribute specifies the alternate text to that
image that is to be displayed. For some issues, if that image is not visible then alt text helps to tell us
about the description of that image.

2.2.4. Block and In-line level HTML elements


When working with HTML, it's essential to understand the distinction between block-level elements and
inline-level elements. These two types of elements play a crucial role in structuring and formatting the
content of a web page. In this article, we will explore the characteristics, behaviors, and use cases of block
and inline-level elements in HTML.

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

Key characteristics of block-level elements:

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

Tinsae D@2024 Internet and web design


• Support width and height properties: You can specify custom dimensions for block-levelelements
using CSS properties such as width and height.
• Allow nesting of other elements: Block-level elements can contain other block-levelelements
as well as inline-level elements.
Common use cases for block-level elements:
• Grouping and organizing content: <div> and <section> elements are commonly used asstructural
containers to group and organize related content.
• Paragraphs and headings: <p> elements for paragraphs and <h1> to <h6> elements forheadings
are examples of block-level elements used for text content.
• Creating lists: <ul> and <ol> elements, along with their list items <li>, are block-levelelements
used to create unordered and ordered lists.
2. Inline-Level Elements:
Inline-level elements, as the name suggests, are HTML elements that do not create line breaks and are
contained within a line of text or other inline elements. Examples of inline-level elementsinclude <span>,
<a>, <strong>, <em>, <img>, and <input>.

Key characteristics of inline-level elements:

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

Tinsae D@2024 Internet and web design


• Creating hyperlinks: The <a> element is used to create hyperlinks that allow users tonavigate
to other web pages or different sections within the same page.
• Inserting images: The <img> element is used to insert images into a web page. Althoughit is an
inline-level element, it may affect the flow of surrounding text.
Understanding the distinction between block-level elements and inline-level elements is essentialfor proper
HTML structure and styling. It enables you to organize and format your content effectively, ensuring a
visually pleasing and semantically meaningful web page layout.

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.

2.3. Basic Document structure of an HTML document

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

Tinsae D@2024 Internet and web design


within any other element. It is used for both HTML and XHTML documents.

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.

Figure 2-4The Basic structure of an HTML document.

Tinsae D@2024 Internet and web design


2.3.2 Meta tags and their importance
Meta tags are a fundamental component of HTML that play a crucial role in improving a website'svisibility,
accessibility, and overall performance. These small snippets of code provide valuable information about a
web page to search engines, social media platforms, and browsers. In this section, we will explore the
importance of meta tags in HTML and how they contribute to the success of your website.

What Are Meta Tags?

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

1. Improving Search Engine Optimization (SEO):

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.

Tinsae D@2024 Internet and web design


By optimizing these meta tags with relevant and accurate information, you can improve your website's
visibility in search engine results and attract more organic traffic.

2. Enhancing Social Media Sharing:

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.

3. Improving Website Accessibility:

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:

• <meta name="viewport" content="width=device-width, initial-scale=1.0"> tag: Specifies the


viewport settings for responsive web design, ensuring optimal display on different devices.
• <meta name="theme-color" content="#ffffff"> tag: Sets the theme color for the website,allowing
browsers to customize the user interface based on the specified color.
By including these meta tags, you enhance the accessibility and usability of your website, makingit more
inclusive for all users.

Tinsae D@2024 Internet and web design


In conclusion, meta tags are integral to the success of your website. By utilizing the appropriate meta tags,
you can optimize your website for search engines, enhance social media sharing, and improve accessibility.
Investing time and effort into crafting effective meta tags will positively impact your website's visibility,
user engagement, and overall performance on the web. Rememberto keep your meta tags accurate, concise,
and relevant to maximize their effectiveness.

2.4. HTML Text basic tags

2.4.1. Heading Tags


HTML headings are titles or subtitles that you want to display on a webpage. HTML also has six levels of
headings, which use the elements <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. Search engines use the
headings to index the structure and content of your web pages. Users often skim apage by its headings. It is
important to use headings to show the document structure. <h1> headingsshould be used for main headings,
followed by <h2> headings, then the less important <h3>, andso on. While displaying any heading, browser
adds one line before and one line after that heading.

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>

Tinsae D@2024 Internet and web design


This will produce the following result:

2.4.2. Paragraph Tag

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>

Tinsae D@2024 Internet and web design


<p>Here is a third paragraph of text.</p>
</body>
</html>

This will produce the following result:

Now let's explore some commonly used attributes with examples:

Class Attribute (class): Used to define a class for the paragraph, allowing you to apply CSS stylesor target
it with JavaScript.

<p class="important">This is an important paragraph.</p>

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:

<p id="intro">This is the introduction paragraph.</p>


<p style="color: red; font-size: 18px;">This paragraph has custo
m styles applied.</p>

2.4.3. Horizontal Line Tag


In HTML, the horizontal line tag is represented by the <hr> element. It is used to create a horizontal line
or separator on a webpage. The <hr> tag is a self-closing tag, meaning it doesn't require a closing tag.
Here's an example of a basic horizontal line:

Tinsae D@2024 Internet and web design


Example

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

This will produce the following result:

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

Tinsae D@2024 Internet and web design


Align Attribute (align): Determines the alignment of the horizontal line within its container. Thepossible
values are left, center, right, or justify.

<hr align="center">

2.4.4. Line Break Tag

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>

This will produce the following result:

Tinsae D@2024 Internet and web design


2.4.5. Preserve Formatting Tag
The <pre> tag stands for "preformatted text" and is used to display text exactly as it is written, preserving
all formatting, including spaces, line breaks, and indentation. It is commonly used todisplay code snippets,
poetry, or any content that requires precise formatting. Here's an exampleof using the <pre> tag to preserve
formatting:

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>

This will produce the following result:

Tinsae D@2024 Internet and web design


2.5. HTML Basic Text Formatting and color

2.5.1. HTML – Formatting Elements


In HTML, there are several formatting elements that you can use to apply specific styles or formatting to
your content. These elements help structure and present your text in a visually appealing and meaningful
way. Here are some commonly used formatting elements in HTML:

A. Bold (<b> or <strong>):


The <b> element and its semantic counterpart <strong> are used to make text appear in a bold orstronger
font weight.

Code snip Result

<b>This text is bold.</b>

<strong>This text is also bold.</strong>

B. Italic (<i> or <em>):


The <i> element and its semantic counterpart <em> are used to make text appear in an italicized or
emphasized style.

Code snip Result


<i>This text is italicized.</i>

<em>This text is also emphasized.</em>

C. Underline (<u>):
The <u> element is used to underline text.

Code snip Result


<u>This text is underlined.</u>

D. Strikethrough (<s> or <del>):


The <s> element and its semantic counterpart <del> are used to display text with a strikethrough or line
through it.

Tinsae D@2024 Internet and web design


Code snip Result
<s>This text has a strikethrough.</s>

<del>This text is also deleted.</del>

E. Superscript (<sup>):
The <sup> element is used to display text as a superscript, typically for indicating footnotes,mathematical
exponents, or citations.

Code snip Result


E = mc<sup>2</sup>

F. Subscript (<sub>):
The <sub> element is used to display text as a subscript, typically for chemical formulas,mathematical
subscripts, or annotations.

Code snip Result


H<sub>2</sub>O

G. Code (<code>):
The <code> element is used to represent a fragment of computer code or inline code snippets.

Code snip Result


Use the <code>print()</code> f
unction to display output.
These formatting elements help convey visual cues or semantic meaning to the text within your HTML
documents. It's important to note that the use of semantic elements (<strong>, <em>, <del>,etc.) is preferred
over non-semantic elements (<b>, <i>, <s>, etc.) as they provide additional meaning to assistive
technologies and search engines. However, both options are valid and can beused based on your specific
requirements.

2.5.2. HTML Quotation and Citation Elements


In HTML, there are specific elements designed for marking up quotations and citations. These elements
provide semantic meaning to the quoted or cited content, allowing browsers, search

Tinsae D@2024 Internet and web design


engines, and assistive technologies to interpret and present the information correctly. Here are thequotation
and citation elements in HTML:

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

Tinsae D@2024 Internet and web design


C. Cite (<cite>):
The <cite> element is used to indicate the title of a creative work, such as a book, article, or song, or to
provide a reference to the source of information.

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

Tinsae D@2024 Internet and web design


The <address> element is commonly used within the footer section or at the end of an article to
provide the contact information associated with the document.

F. Bidirectional Override (<bdo>):


The <bdo> element is used to override the text directionality (left-to-right or right-to-left) of thecontent
within it.

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

Tinsae D@2024 Internet and web design


context and understanding for abbreviations or acronyms used in your content. It enhances accessibility,
allowing assistive technologies to provide the full expansion of the abbreviation when necessary.

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.

2.6. HTML Comments

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:

<!-- This is an HTML comment. -->


Comments start with <!-- and end with -->. Anything placed between these delimiters will be treated as a
comment and will not be rendered by the browser. Here's an example of comments used in HTML code:

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

Tinsae D@2024 Internet and web design


<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- Main Content -->
<h1>Welcome to my website!</h1>
<p>This is the homepage.</p>
<!-- TODO: Add more content here -->
<!-- JavaScript Scripts -->
<script src="script.js"></script>
</body>
</html>
Comments are a useful tool for organizing, documenting, and communicating within your HTML
code. They improve code readability and maintainability, especially when working collaboratively or
revisiting the codebase in the future.

2.7. HTML Colors

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:

<p style="color: red;">This text is in red.</p>

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

<p style="color: #00FF00;">This text is in green.</p>

Tinsae D@2024 Internet and web design


• RGB Values: RGB (Red, Green, Blue) values allow you to specify the intensity of each colorcomponent
using decimal values between 0 and 255. Here's an example:

<p style="color: rgb(255, 0, 0);">This text is in red.</p>

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

<p style="color: hsl(120, 100%, 50%);">This text is in green.</p>

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.

Figure 2-5 Standard Colors IN HTML

Tinsae D@2024 Internet and web design


Set color Properties in HTML

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.

<p style="color: red;">This text is in red.</p>


<h1 style="color: #00FF00;">This heading is in green.</h1>
<span style="color: rgb(255, 0, 0);">This span is in red.</span>
<div style="color: hsl(120, 100%, 50%);">This div is in green.</
div>

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.

Tinsae D@2024 Internet and web design


Result

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

Tinsae D@2024 Internet and web design


Result

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.

2.8. HTML Image and Multimedia


2.8.1. HTML Images

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:

▪ Include an image in your web pages using HTML


▪ Pick which image format to use
▪ Show an image at the right size
▪ Optimize an image for use on the web to make pages load faster
Choosing images for your site

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

Tinsae D@2024 Internet and web design


Image file types

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.

Tinsae D@2024 Internet and web design


There are 2 ways to insert the images into a webpage:

▪ By providing a full path or address (URL) to access an internet file.

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

<img src="url" alt="some_text" width="" height="">

Attributes:

The <img> tag has following attributes:

▪ src: It is used to specify the path to the image.

▪ 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

Tinsae D@2024 Internet and web design


to be used with canvas.

▪ height: It is used to specify the height of the image.

▪ width: It is used to specify the width of the image.

▪ ismap: It is used to specify an image as a server-side image map.

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

▪ srcset: It is used to specify a list of image files to use in different situations.

▪ usemap: It is used to specify an image as a client-side image map.

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>

Tinsae D@2024 Internet and web design


Note: on the above example you can change the value of the src attribute by your own or it willbe provided
by your course instructor. Here is the output of the above example:

Output of the above code in a browser:

The ‘src’ attribute

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.

Example 2: Use of src attribute

The example illustrates the use of the src attribute in the <img> tag.

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>src Attribute Example</title>
</head>
<body>
<p>Insert an image from the same folder with the file:</p>
<img src="img_girl.jpg">
<p>Insert an image from another folder:</p>
<img src="/images/stickman.gif">
<p>Insert an image from a web site:</p>
<img src="https://www.w3schools.com/images/lamp.jpg" >
</body>
</html>

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:

Output of the above code in a browser:

Tinsae D@2024 Internet and web design


In the above example the src stands for source. It shows how to Insert an image from the same folder , Insert
an image from another folder and Insert an image from a web site.

The ‘alt’ attribute

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:

Tinsae D@2024 Internet and web design


The width and height attributes -Image Size

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>

<img src="img_girl.jpg" alt="Girl in a jacket" style="width:500px;height:600px;">

</body>

</html>

Tinsae D@2024 Internet and web design


Note that: Both the above examples (4 and 5) have the same output on the browser.

Common Image Format: Here is the commonly used image file format that is supported by allthe browsers.

S.No Abbreviation File Type Extension


.

1. PNG Portable Network Graphics. .png

2. JPEG. Joint Photographic Expert Group image. .jpg, .jpeg, .jfif, .pjpeg, .pjp

3. SVG Scalable Vector Graphics. .svg.

4. GIF Graphics Interchange Format. .gif

5. ICO Microsoft Icon. .ico, .cur

6. APNG Animated Portable Network Graphics. .apng

2.8.2. Adding sound to your HTML document

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:

Tinsae D@2024 Internet and web design


src
ur

Output of the above example on a browser:

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.

▪ loop: Makes the audio repeat continuously.

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.

Here's another example demonstrating additional attributes:

<audio src="audio.mp3" controls preload="metadata" volume="0.5">


Your browser does not support the audio element.

</audio>

Tinsae D@2024 Internet and web design


▪ preload: Specifies the audio preloading behavior. The value "metadata" indicates that only the
audio metadata, such as duration, should be loaded. Other values include "auto" (the entire audio
file is preloaded) and "none" (no preloading).
▪ volume: Sets the initial volume of the audio. The value ranges from 0.0 (silent) to 1.0 (fullvolume).
These are just a few examples of the attributes that can be used with the <audio> tag. Other attributes, such
as muted, controlsList, crossorigin, and more, provide additional control and customization options for
embedding and controlling audio content on a web page.Remember to provide fallback content within the
<audio> tags, as shown in the examples, so that users can understand and interact with the audio content if
their browser does not support the <audio> tag or the specified audio format.

2.8.3. Adding Video to your HTML document

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>

Tinsae D@2024 Internet and web design


Output of the above example on a browser:

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.

▪ loop: Makes the video repeat continuously.

▪ 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 src="video.mp4" controls preload="metadata" poster="poster.jpg">


Your browser does not support the video element.

</video>

Tinsae D@2024 Internet and web design


▪ preload: Specifies the video preloading behavior. The value "metadata" indicates that onlythe video
metadata, such as duration and dimensions, should be loaded. Other values include "auto" (the
entire video file is preloaded) and "none" (no preloading).
▪ poster: Specifies an image to be displayed as a placeholder or poster frame before the video is
played.
These are just a few examples of the attributes that can be used with the <video> tag. Other attributes, such
as muted, controlsList, crossorigin, playsinline, and more, provide additional control and customization
options for embedding and controlling video content on a web page. Remember to provide fallback content
within the <video> tags, as shown in the examples, so thatusers can understand and interact with the video
content if their browser does not support the
<video> tag or the specified video format.

2.9. HTML Lists and Table

2.9.1. HTML Lists

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.

▪ Ordered lists. Lists in which the sequence of the items is important.

▪ Description lists. Lists that consist of name and value pairs, including but not limited to terms and
definitions.

Figure 2-6 Types of lists with example

Tinsae D@2024 Internet and web design


All list elements—the lists themselves and the items that go in them—are displayed as block elements by
default, which means that they start on a new line and have some space above and below, but that may be
altered with CSS. In this section, we’ll look at each list type in detail.

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>

<title> Unordered lists Example</title>

</head>

<p>Things I like to do in the morning:</p>

<body>

<ul>

<li>Drink a cup of coffee</li>

<li>Watch the sunrise</li>

<li>Listen to the birds sing</li>

<li>Hear the wind rustling through the trees</li>

<li>Curse the construction noises for spoiling the peaceful mood</li>

</ul >

</body>

</html>

Tinsae D@2024 Internet and web design


Output

Figure 2-7 An unordered list output

Customizing Unordered Lists

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:

▪ "disc"—A disc or bullet; this style is the default.

▪ "square"—Obviously, a square rather than a disc.

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

Tinsae D@2024 Internet and web design


</ul>

</ul>
Output

Figure 2-8Unordered lists with different bullet styles

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 :

<ul style="list-style-image: url(/https/www.scribd.com/bullet.gif);">

<li>Example</li>

</ul>

Tinsae D@2024 Internet and web design


Nesting Lists

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>

Tinsae D@2024 Internet and web design


Output

Figure 2-9 Nested Unordered List

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:

Tinsae D@2024 Internet and web design


Output :

Figure 2-10 An ordered list in HTML

Tinsae D@2024 Internet and web design


Customizing Ordered Lists

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.

Figure 2-11 Ordered List Numbering Styles

You can specify types of numbering in the <ol> tag using the style attribute, like this:

<ol style="list-style-type: lower-alpha;">

By default, the decimal type is assumed.

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

Tinsae D@2024 Internet and web design


Example:

<h1>The days of the week in French</h1>

<ol style="list-style-type: upper-roman;">

<li>Lundi</li>

<li>Mardi</li>

<li>Mercredi</li>

<li>Jeudi</li>

<li>Vendredi</li>

<li>Samedi</li>

<li>Dimanche</li>

</ol >
Output:

Figure 2-12 An ordered list displayed using an alternative numbering style.

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

Tinsae D@2024 Internet and web design


Figure 2-13 The Chrome developer tools with the updated <ol> tag.

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<

Tinsae D@2024 Internet and web design


Output:

Figure 2-14 An ordered list with an alternative numbering style and starting number.

Example : Nested ordered list,

a nested ordered list is a list that has a list inside another list.

Tinsae D@2024 Internet and web design


Bl

Tinsae D@2024 Internet and web design


</ol>

Output :

C. Definition Lists
Definition lists differ slightly from other lists. Each list item in a definition list has two parts:

▪ A term

▪ The term’s definition

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

Tinsae D@2024 Internet and web design


</dl>
Output :

Figure 2-15 A definition list

2.9.2. HTML Tables


Creating tables in HTML is a degree more complex. Think about how many different types of tables there
are. A table can be a three-by-three grid with labels across the top, or two side-by-sidecells, or a complex
Excel spreadsheet that comprises many rows and columns of various sizes. Representing tables in HTML
is heavy on tags, and the tags can be hard to keep track of when youget going.

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

Tinsae D@2024 Internet and web design


Before getting into the actual HTML code to create a table, here are some table-related terms you’ll see
throughout this lesson:

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

Figure 2-16 The elements that make up a table.

The <table> Element

All the components of a table are placed within a <table>...</table> element:

<table>

...table caption (optional) and contents...

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

Tinsae D@2024 Internet and web design


<table border="1">
<caption>Vital Statistics</caption>
<tr>
<th>Name</th>
<th>Height</th>
<th>Weight</th>
<th>Eye Color</th>

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

Tinsae D@2024 Internet and web design


Rows and Cells
Now that you’ve been introduced to the <table> element, we’ll move on to the rows and cells. Inside the
<table>...</table> element, you define the actual contents of the table. Tables are specified in HTML row
by row, and each row definition contains all the cells in that row. So, to create a table, you start with the top
row and then each cell in turn, from left to right. Then you define a second row and its cells, and so on. The
number of columns is calculated based on how many cells there are in each row. Each table row starts with
the <tr> tag and ends with the closing
</tr>. Your table can have as many rows and columns as you like, but you should make sure that each row
has the same number of cells so that the columns line up. The cells within each row arecreated using one of
two elements:
▪ <th>...</th> elements are used for heading cells. Generally, browsers center the contents
of a <th> cell and render any text in the cell in boldface.
▪ <td>...</td> elements are used for data cells. td stands for table data.
In this table example, the heading cells appear in the top row and are defined with the followingcode:

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

Tinsae D@2024 Internet and web design


<td>6'0"</td>

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

Tinsae D@2024 Internet and web design


Example:

</tr>

<td>5'4"</td>

<td>6'0"</td>

<td>5'1"</td>

</tr>

Tinsae D@2024 Internet and web design


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

Tinsae D@2024 Internet and web design


The <caption> element goes inside the <table> element just before the table rows, and it containsthe title
of the table. It closes with the </caption> tag:

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

Figure 2-18 A visible details

Tinsae D@2024 Internet and web design


2.10. HTML Forms

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

Tinsae D@2024 Internet and web design


explore both the standard and HTML5 form elements along with their attributes: The <form> tagis used to
create an HTML form:

Example

<form action="/submit" method="POST">

<!-- form elements go here -->

</form>

In the above example:

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

Tinsae D@2024 Internet and web design


Output: How the HTML code above looks in a browser:

Description of the code:


In this example, we have a form field for capturing the user's username. Let's break down theattributes and
their significance:

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

Tinsae D@2024 Internet and web design


<form>
<label for="password">Password:</label>
<input type="password" id="password" name="password" req
uired minlength="8">
</form>

Output: How the HTML code above looks in a browser:

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>

Output: How the HTML code above looks in a browser:

Tinsae D@2024 Internet and web design


In this example, we have a set of radio buttons for selecting the preferred language. Let's breakdown the
attributes and their significance:

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

<label for="option1">Option 1</label>


<label for="option2">Option 2:</label>
<input type="checkbox" id="option2" name="options[]" value="op
tion2">

<label for="option2">Option 2</label>

Tinsae D@2024 Internet and web design


<input type="checkbox" id="option3" name="options[]" value="op
tion3">

<label for="option3">Option 3</label>


</form>

Output: How the HTML code above looks in a browser:

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

<input type="submit"> defines a 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:

<form action ="demo_form_action.asp " method="post">


Username: <input type="text" name="user"><br>
Password: <input type="password" id="password" name="password" r
equired minlength="8"><br>
<input type="submit" value="Submit">
</form>

Tinsae D@2024 Internet and web design


Output: How the HTML code above looks in a browser:

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.

2.10.2. Text area

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>

Output: How the HTML code above looks in a browser:

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.

Tinsae D@2024 Internet and web design


• cols="30": Specifies the visible number of columns (characters per row) for the textarea.In this
case, the textarea will display 30 columns.
• placeholder="Enter your message": Displays a hint or example value within the textareato guide
users on what information to enter.
• required: Specifies that the textarea must be filled out before the form can be submitted. It
enforces mandatory user input.

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.

2.10.3. Drop-down list


The <select> element is used to create a drop-down list or a select menu in HTML. It allows usersto choose
an option from a list of predefined options. Here's an example of <select> with attributesand a description:

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

Tinsae D@2024 Internet and web design


Output: How the HTML code above looks in a browser:

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>

Output: How the HTML code above looks in a browser:

Tinsae D@2024 Internet and web design


In this example, we have a button that triggers a form submission. Let's break down the attributes and their
significance:

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

2.10.5. HTML5 Form Elements and Attributes:


HTML5 introduced several new form elements and attributes to enhance the functionality and userexperience
of web forms. Here are some of the notable HTML5 form elements and attributes. These HTML5 form
elements and attributes enhance the functionality and user experience of webforms by providing built-in
validation, specialized input types, and more interactive controls. They allow developers to create more
intuitive and user-friendly forms while reducing the need for custom JavaScript validation and user input
handling. Here is a combined example that illustratesHTML 5 form elements.

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

Tinsae D@2024 Internet and web design


<label for="age">Age:</label>
<input type="number" id="age" name="age" min="0" max="120">
<label for="birthdate">Birthdate:</label>
<input type="date" id="birthdate" name="birthdate">
<label for="meeting-time">Meeting Time:</label>
<input type="time" id="meeting-time" name="meeting-time">
<label for="event-datetime">Event Date and Time:</label>
<input type="datetime-local" id="event-datetime" name="event-datetime">
<label for="color">Favorite Color:</label>
<input type="color" id="color" name="color" value="#ff0000">

<label for="rating">Rating (1-10):</label>


<input type="range" id="rating" name="rating" min="1" max="10"
>
</fieldset>
</form>

Output: How the HTML code above looks in a browser:

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.

Tinsae D@2024 Internet and web design


• <input type="email"> represents an email input field where users can enter their emailaddresses.
The required attribute ensures that the field must be filled out.
• <input type="url"> represents a URL input field for users to enter website addresses.
• <input type="tel"> represents a telephone input field for entering phone numbers.
• <input type="number"> represents a numeric input field where users can enter their age.The min
and max attributes define the allowed range of values.
• <input type="date"> represents a date input field for selecting a specific date.
• <input type="time"> represents a time input field for choosing a particular time of day.
• <input type="datetime-local"> represents a combined date and time input field.
• <input type="color"> represents a color input field that allows users to pick a color froma color
palette.
• <input type="range"> represents a slider input field where users can select a value withina specified
range.
This combined example showcases the usage of different input types and attributes to create a form with
various data input fields. The <fieldset> and <legend> elements provide structure and a caption for the
related fields, enhancing the form's usability and organization.

2.11. The HTML <div> Element

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.

2.12. The HTML <span> Element

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.

HTML Grouping Tags

<div>: Defines a section in a document (block-level)


<span>: Defines a section in a document (inline)
Example

Tinsae D@2024 Internet and web design


<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<div id="container" class="wrapper">
<h1>Welcome to <span class="highlight">My Website</span></h1>
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum consectetur, risus vel fermentum malesuada.</p>
<p>Suspendisse potenti. <span class="highlight">Vivamus</spa
n> accumsan nibh eu leo tincidunt, sit amet ultrices lectus luct
us.</p>
</div>
</div>
</body>
</html>

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:

Tinsae D@2024 Internet and web design


• <div id="container" class="wrapper">: The outer <div> acts as a container with the assigned ID
"container" and the class "wrapper". This can be used for applying styles or targeting the container
with JavaScript.
• <h1>Welcome to <span class="highlight">My Website</span></h1>: The <h1> element contains
the text "Welcome to" followed by the word "My Website" enclosed in a
<span> element with the class "highlight". This allows you to apply specific styles or effects to the
enclosed text.
• <div class="content">: The inner <div> acts as a container with the class "content". It can be used
to group related content or apply specific styles to the content within.
• <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum consectetur, risus vel
fermentum malesuada.</p>: The first <p> element contains some placeholder text.
• <p>Suspendisse potenti. <span class="highlight">Vivamus</span> accumsan nibh eu leotincidunt,
sit amet ultrices lectus luctus.</p>: The second <p> element contains the text "Suspendisse
potenti." followed by the word "Vivamus" enclosed in a <span> element withthe class "highlight".
In this combined example, the <div> element is used as a container to group and organize the content of the
webpage. The <span> element is used within the <h1> and <p> elements to highlight specific words or
phrases. You can style or manipulate the container <div> using the assigned ID or class, and target the
highlighted text using the specified class.

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.

2.13. HTML Layout

2.13.1. HTML Layouts


HTML layouts refer to the structural organization and arrangement of content on a web page. HTML
provides a variety of layout techniques that can be used to create well-structured and visually appealing
web pages. Here are some commonly used HTML layout techniques. By combining these layout techniques
and approaches, web developers can create visually appealing,

Tinsae D@2024 Internet and web design


accessible, and responsive web page layouts. The choice of layout technique depends on the specific
requirements of the project, the complexity of the design, and the level of flexibility and responsiveness
needed.

A. Website Layout Using HTML5

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>

Tinsae D@2024 Internet and web design


<style>
body {
font-family: Arial, sans-serif;margin: 0;
padding: 0;
}

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;

Tinsae D@2024 Internet and web design


margin: 0 auto;
}

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

Tinsae D@2024 Internet and web design


<main>
<h2>Welcome to Our Website</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisci
ng elit. Nulla eget nulla vel nisi commodo rutrum in at nunc.

</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>&copy; 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.

Tinsae D@2024 Internet and web design


▪ <body>: The main content of the webpage is placed within this element.
▪ <header>: Represents the top section of the webpage, commonly used for the site'sbranding,
logo, and main heading.
▪ <h1>: An HTML heading element that indicates the primary heading of the page.
▪ <nav>: Represents the navigation menu section, typically containing links to differentpages or
sections of the website.
▪ <a>: The anchor tag is used to create hyperlinks to other pages or resources. In this example,the
navigation links are styled as buttons.
▪ <div class="container">: A container div used to hold the main content and the sidebar.
▪ <main>: This element contains the primary content of the webpage. In the example, itcontains
a welcome message and some Lorem Ipsum text.
▪ <aside>: Represents the sidebar section, which contains additional content related to themain
content. In this example, it has a simple text paragraph.
▪ <footer>: Represents the footer section of the webpage, usually containing copyright
information, contact details, or other relevant links.
▪ CSS Styling: The embedded CSS code provides basic styling for various elements, such assetting the
font family, background colors, padding, and layout with flexbox.

The output:

Tinsae D@2024 Internet and web design


The layout is designed to be responsive, with the use of flex properties to arrange the main contentand sidebar
in a row on larger screens and stack them vertically on smaller screens. The header, navigation menu, and
footer are styled with consistent colors, creating a unified look and feel throughout the webpage.

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.

B. HTML Layout Using <div> Elements

The <div> element was not designed to be a layout tool.

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>

Tinsae D@2024 Internet and web design


idth:400px;float:left;">
Content goes here</div>

<div id="footer" style="background-color:#FFA500;clear:both;text


-align:center;">
Copyright © 2023</div>

</div>
</body>
</html>

The HTML code above will produce the following result:

C. HTML Layout Using Tables

The <table> element was not designed to be a layout tool.

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>

Tinsae D@2024 Internet and web design


<table style="width:500px;" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" style="background-color:#FFA500;">
<h1 style="margin:0;padding:0;">Main Title of Web Page</h1>
</td>
</tr>
<tr>
<td style="background-color:#FFD700;width:100px;vertical-align:top;">
<b>Menu</b><br>HTML<br> CSS<br>
JavaScript
</td>
<td style="background-color:#eeeeee;height:200px;width:400px;vertical-align:top;">
Content goes here</td>
</tr>
<tr>
<td colspan="2" style="background-color:#FFA500;text-align:center;">
Copyright © W3Schools.com</td>
</tr>
</table>

</body>
</html>

Tinsae D@2024 Internet and web design


Unit 2: Summary Question

1. What is the purpose of the <html> tag in an HTML document?


2. How do you specify the character encoding for an HTML document?
3. Explain the role of the <head> tag in HTML and give examples of common elements within
it.
4. What is the significance of the <title> tag in an HTML document?
5. Describe the difference between the <div> and <span> tags in HTML, and provide
examples of their usage.
6. How do you create an unordered list (<ul>) and an ordered list (<ol>) in HTML? Provide
examples.
7. What are semantic HTML tags, and why are they important for web accessibility and SEO?
8. Explain the purpose of the <img> tag in HTML and how you specify the image source and
alternative text.
9. How do you create a hyperlink in HTML? Provide examples of both relative and absolute
URLs.
10. Describe the <table> tag in HTML and how you structure rows (<tr>), columns (<td>),
and headers (<th>).
11. What are HTML form elements, and how do you create a basic form using <form> and
input tags?
12. Explain the purpose of the <iframe> tag in HTML and give examples of its usage.
13. How do you embed audio and video files in an HTML document? Provide examples using
the <audio> and <video> tags.
14. Describe the <meta> tag in HTML and its role in providing metadata about the document.
15. What is the purpose of the <script> tag in HTML, and how do you include external
JavaScript files?
16. Explain the <blockquote> tag in HTML and its significance for displaying quoted content.
17. How do you create headings (<h1> to <h6>) in HTML, and what is their semantic
significance?
18. Describe the <form> tag attributes action and method, and their role in form submission.
19. Explain the use of the <abbr> tag in HTML for defining abbreviations or acronyms, and
provide an example.
20. How do you create a line break in HTML? Compare and contrast the <br> tag with the CSS
property white-space: pre;.

Tinsae D@2024 Internet and web design


Unit 3: CSS
Basics of Cascading style sheet/CSS

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:

• a selector which specifies the HTML element(s) to style.


• a declaration block which contains one or more declarations separated by semicolons.

Tinsae D@2024 Internet and web design


Each declaration includes a property name and a value, specifying the aspect of the element's
presentation to control.

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>

In the above CSS snippet:

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

Tinsae D@2024 Internet and web design


• #36CFFF, 1.5em, white, 5px inset gold, black, 300px, and center are the corresponding
values passed to these 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

Tinsae D@2024 Internet and web design


A CSS comprises of style rules that are interpreted by the browser and then applied to the
corresponding elements in your document. A style rule is made of three parts −

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

You can put CSS Style Rule Syntax as follows −

selector { property: value }

Example − You can define a table border as follows −

table{ border :1px solid #C00; }

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.

The Type Selectors

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

Tinsae D@2024 Internet and web design


The Universal Selectors

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.

The Descendant Selectors

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 −

Tinsae D@2024 Internet and web design


<p class = "center bold">
This para will be styled by the classes center and bold.
</p>

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.

The Child Selectors

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;

Tinsae D@2024 Internet and web design


}

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.

The Attribute Selectors

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.

There are following rules applied to attribute selector.

• p[lang] − Selects all paragraph elements with a lang attribute.


• p[lang="fr"] − Selects all paragraph elements whose lang attribute has a value of exactly
"fr".
• p[lang~="fr"] − Selects all paragraph elements whose lang attribute contains the word
"fr".
• p[lang|="en"] − Selects all paragraph elements whose lang attribute contains values that
are exactly "en", or begin with "en-".
Multiple Style Rules

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

Tinsae D@2024 Internet and web design


Here all the property and value pairs are separated by a semicolon (;). You can keep them in a
single line or multiple lines. For better readability, we keep them in separate lines.

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.

You can combine the various id selectors together as shown below −

#content, #footer, #supplement {


position: absolute;
left: 510px;
width: 200px;
}

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.

Tinsae D@2024 Internet and web design


Selector lists

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

A type selector targets an HTML element, such as <h1>, <p>, etc.

Tinsae D@2024 Internet and web design


p {
color: green;
}

h1 {
text-decoration-line: underline;
}

Following example demonstrates the use of a type selector:

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

Tinsae D@2024 Internet and web design


.style-p {
color: green;
font-size: 25px;
}

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

An ID selector targets an element with a specific value for its id attribute.

#style-p {
color: green;
font-size: 25px;
}

Tinsae D@2024 Internet and web design


#style-h1 {
text-decoration-line: underline;
color: red;
}

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>

CSS Selector - Attribute Selector

An attribute selector targets an element based on a specific attribute or attribute values on an


element.

Tinsae D@2024 Internet and web design


a[target] {
background-color: peachpuff;
}

You can also specify the element with an attribute having a specific value.

a[href="https://www.tutorialspoint.com"] {
background-color: peachpuff;
}

Following example demonstrates the use of an attribute selector:

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

CSS Selector - Pseudo-class Selector

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.

For a detailed list of pseudo-class selectors, refer this link.

a :hover {
background-color: peachpuff;
color: green;
font-size: 2em;
}

Tinsae D@2024 Internet and web design


Following example demonstrates the use of a pseudo-class selector:

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

CSS Selector - Pseudo-element Selector

A pseudo-element selector is used to style a specific part of an element rather than the element
itself.

For a detailed list of pseudo-element selectors, refer this link.

a::before {
content: url();
}

Following example demonstrates the use of a pseudo-element selector (::before):

<html>
<head>
<style>
a::before {
content: url('images/smiley.png');
}

a::after {
content: " Pseudo-element ::after applied";
color: red;
background-color: chartreuse;
}

Tinsae D@2024 Internet and web design


</style>
</head>
<body>
<h2>Pseudo-element selector</h2>
<p>Styling applied to anchor element with a pseudo-element:</p>
<a href="#">Tutorialspoint</a>
</body>
</html>
Combinators

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

/* style applied to all li elements that are child element to ol


element */
ol > li {
background-color: bisque;
color: black;
font-size: 0.75em;
padding: 5px;
}
</style>
</head>
<body>
<div>

Tinsae D@2024 Internet and web design


<ul>
<li>Item One</li>
<li>Item Two
<ol>
<li>Nested 1</li>
<li>Nested 2</li>
</ol></li>
<li>Item Three</li>
<li>Item Four</li>
<li>Item Five
<ol>
<li>Nested 3</li>
<li>Nested 4</li>
</ol>
</li>
</ul>
</div>
</body>
</html>
CSS Selector - Universal Selector

Universal selector, denoted by an asterisk mark (*), is a special selector that matches any and all
elements in an HTML document.

/* Selects and styles all elements on the page */


* {
margin: 0;
padding: 0;
}

As per the above syntax, the universal selector is used to apply a margin and padding of 0 to all
HTML elements.

Following example demonstrates the use of a universal selector (*):

<html>
<head>
<style>
* {
background-color: peachpuff;
color: darkgreen;
font-size: 25px;
}
</style>

Tinsae D@2024 Internet and web design


</head>
<body>
<h1>Universal selector (*)</h1>

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

Embedded CSS - The <style> Element


You can put your CSS rules into an HTML document using the <style> element. This tag is placed
inside the <head>...</head> tags. Rules defined using this syntax will be applied to all the
elements available in the document. Here is the generic syntax − <!DOCTYPE html>
<html>
<head>
<style type = "text/css" media = "all">
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

It will produce the following result −

Tinsae D@2024 Internet and web design


Attributes

Attributes associated with <style> elements are −

Attribute Value Description

Specifies the style sheet language as a content-type (MIME


type text/css
type). This is required attribute.

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 −

<element style = "...style rules....">

Attributes

Attribute Value Description

The value of style attribute is a combination of style


style style rules
declarations separated by semicolon (;).

Example

Following is the example of inline CSS based on the above syntax − <html>
<head>
</head>

Tinsae D@2024 Internet and web design


<body>
<h1 style = "color:#36C;">
This is inline CSS
</h1>
</body>
</html>

It will produce the following result −

External CSS - The <link> Element

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.

Here is the generic syntax of including external CSS file −

<head>
<link type = "text/css" href = "..." media = "..." />
</head>

Attributes

Attributes associated with <style> elements are −

Attribute Value Description

Specifies the style sheet language as a content-type


type text css
(MIME type). This attribute is required.

Specifies the style sheet file having Style rules. This


href URL
attribute is a required.

screen
tty Specifies the device the document will be displayed on.
media
tv Default value is all. This is optional attribute.
projection

Tinsae D@2024 Internet and web design


handheld
print
braille
aural
all

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>

Tinsae D@2024 Internet and web design


Example

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

The importance of using borders in CSS can be summarized as follows:

• Visual separation: Borders help to visually separate different elements on a webpage,


making it easier for users to understand the layout and navigation.
• Organization and structure: Borders can be given to grids, tables or even boxes that
makes the content look more organized and structured.
• Emphasis and focus: Borders can be given to elements to emphasize and highlight them.
• Design and aesthetics: Borders allow to add you to add decoration to the elements to
enhance the visual appeal. This can be achieved using the style, color and width of border.
Borders - Properties

Following table describes the various properties of border, their description and default values
they hold:

Property Description Default value

specifies whether a border should be


style solid, dashed line, double line, or one none
of the other possible values

Tinsae D@2024 Internet and web design


width specifies the width of a border medium

foreground color of the element


color specifies the color of a border and if element is blank, then color
of the parent element

Now, we will see how to use these properties with examples.

CSS Borders - border-style Property

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

hidden A hidden border, same as 'none' except for table elements

dotted A series of dots

dashes A series of short dashes

solid A single solid line

double Two parallel lines with a small gap between them

groove A border that appears to be carved into the page

ridge A border that appears to be slightly raised above the page

inset A border that appears embedded into the page

outset A border that appears slightly raised out of the page

Tinsae D@2024 Internet and web design


initial Sets the border-style property to its default value

inherit Inherits the border-style property from its parent element

Let us see an example for these values of border-style:


<html>
<head>
<style>
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.dotted {border-style: dotted;}
p.dashes {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.mixed {border-style: none dashed solid dotted;}
</style>
</head>
<body>
<h2>border-style Property</h2>
<p class="none">No border.</p>
<p class="hidden">Hidden border.</p>
<p class="dotted">Dotted border.</p>
<p class="dashes">Dashed border.</p>
<p class="solid">Solid border.</p>
<p class="double">Double border.</p>
<p class="groove">Groove border.</p>
<p class="ridge">Ridge border.</p>
<p class="inset">Inset border.</p>
<p class="outset">Outset border.</p>
<p class="mixed">A mixed border.</p>
</body>
<html>

Single Side - Border Style

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

Tinsae D@2024 Internet and web design


• border-right-style
• border-bottom-style
• border-left-style

Let us see an example:

<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

thin a thin border

medium a medium width border

thick a thick border

length any length specified (like 0.1em, 5px)

Declare a border-style before declaring border-width, else the border effect will not be seen.

Let us see an example (with and without specifying border-style):

<html>
<head>
<style>

Tinsae D@2024 Internet and web design


p.thin {border-width: thin;}
p.medium {border-width: medium;}
p.thick {border-width: thick;}
p.length {border-width: 100px;}
p.thin1 {border-style: double; border-width: thin;}
p.medium1 {border-style: dashed; border-width: medium;}
p.thick1 {border-style: solid; border-width: thick;}
p.length1 {border-style: dotted; border-width: 10px;}
</style>
</head>
<body>
<h2>border-width without <i>border-style</i> property</h2>
<p class="thin">Thin border.</p>
<p class="medium">Medium border.</p>
<p class="thick">Thick border.</p>
<p class="length">Specific length border.</p>
<h2>border-width with <i>border-style</i> property</h2>
<p class="thin1">Thin width.</p>
<p class="medium1">Medium width.</p>
<p class="thick1">Thick width.</p>
<p class="length1">Specific length width border.</p>
</body>
</html>

Single Side - Border Width

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

Let us see an example:

<html>
<head>
<style>
p {border-style: solid;
border-top-width: thin;
border-right-width: thick;
border-bottom-width: medium;
border-left-width: 10px;

Tinsae D@2024 Internet and web design


padding: 2em;}
</style>
</head>
<body>
<h2>border-width (single-side)</h2>
<p>Different border widths on all sides.</p>
</body>
</html>
CSS Borders - color Property

The border-color is the third constituent property of border. It sets the color of the border.

• border can have one, two, three or all four values.


• If no color is specified for border, the default value is currentcolor i.e. the foreground
color.
• Any type of color value can be passed, such as RGB, RGBA, hexadecimal, etc.

Following values can be passed to border:

Value Description

color the border will be of the color specified

transparent the border will be transparent

inherit the parent element's value is inherited

Declare a border-style before declaring border-color, else the border effect will not be seen.

Let us see an example (with and without specifying border-style):

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

Tinsae D@2024 Internet and web design


<p class="color1">Red color with name.</p>
<p class="hexa1">Green color with hexadecimal.</p>
<h2>border-color with <i>border-style</i> property</h2>
<p class="color2">Red color with name.</p>
<p class="hexa2">Green color with hexadecimal.</p>
</body>
</html>

Single Side - Border Color

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

Let us see an example:

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

Tinsae D@2024 Internet and web design


• border-block property acts on both the start and finish in the block dimension. The
writing mode, directionality, and text orientation of the element determine which precise
physical borders are impacted.
• When the writing-mode is set to the default horizontal direction, border-block is applied
to the top and bottom borders of an element.
• Conversely, a vertical writing-mode, applies border-block to the right and left borders.
Possible values
• <border-width> - The width of the border.
• <border-style> - The line style of the border.
• <border-color> - The color of the border.
Constituent Properties

This property is a shorthand for the following CSS properties:

• border-block-color
• border-block-style
• border-block-width
Syntax
border-block: <border-block-width> || <border-block-style> || <border-
block-color>
Applies to

All the HTML elements.

CSS border-block - Basic Example

The following example demonstrates the css border-block property.

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

Tinsae D@2024 Internet and web design


}
</style>
</head>
<body>
<div class="border-demo">
<p class="add-demo">This is a bordered element with padding and
background color.</p>
<p>This is an example for border-block property</p>
</div>
</body>
</html>
CSS border-block - writing-mode Property

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>

Tinsae D@2024 Internet and web design


CSS - Margins Property

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

Following values can be passed to each side:

Value Description

auto The margin is calculated automatically by the browser

length The margin is specified in px, pt, cm, etc

% The margin is specified in percentage (%) of the width of the containing element

inherit The margin is inherited from the parent element

Note: Negative values are allowed to be passed as margin.


Syntax
selector {
margin: top right bottom left;
}

You can specify margins for all sides at once (top, right, bottom, left) or set specific values for
individual sides.

CSS Margins - Related Properties

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

Tinsae D@2024 Internet and web design


margin-top sets the top margin of the element

margin-right sets the right margin of the element

margin-
sets the bottom margin of the element
bottom

margin-left sets the left margin of the element

margin-block sets logical block start and end margins for an element.

margin-inline sets logical inline start and end margins of an element.

CSS - Paddings Property

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.

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

padding: top right bottom left

The following diagram demonstrates the various padding properties for reference:

Tinsae D@2024 Internet and web design


All the padding properties can have the following values:

• length value (in pixels, inches, millimeters, ems).


• percentage (%) value (in % of the width of the containing element).
• inherit value specifies that padding should be inherited from the parent element.
Example -Simple Padding

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>

Tinsae D@2024 Internet and web design


#myDIV {border: 2px solid;}
h2 {padding: 5px; background-color: skyblue}
</style>
</head>
<body>
<div id="myDIV">
<h2>The padding can be seen around the text.</h2>
</div>
</body>
</html>
Example - Padding and No-padding

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

Tinsae D@2024 Internet and web design


• padding-right
• padding-bottom
• padding-left

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.

Let us see an example for the shorthand property of 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>

Tinsae D@2024 Internet and web design


h2 {padding: 50px 20px 30px 40px; background-color:
silver;}
</style>
</head>
<body>
<div>
<h2>The different padding property values are set to the h2
element.</h2>
</div>
</body>
</html>
Padding - Set Three Values

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.

Following is the example for the same:

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

Tinsae D@2024 Internet and web design


Unit 3: Summary Questions

1. What is CSS, and what is its primary purpose in web development?


2. Describe the difference between inline, internal, and external CSS stylesheets.
3. How do you select HTML elements for styling using CSS selectors? Provide examples of
different types of selectors.
4. Explain the concept of specificity in CSS and how it affects the application of styles to
elements.
5. What is the box model in CSS, and how does it influence the layout of elements on a
webpage?
6. Describe the difference between margin, padding, border, and content areas of an element
in the box model.
7. How do you apply styles to a specific element when it has multiple classes? Explain with
an example.
8. What are pseudo-classes and pseudo-elements in CSS, and give examples of each.
9. Describe the difference between the display: block, display: inline, and display: inline-
block CSS properties.
10. Explain the purpose of the position property in CSS and describe the values static,
relative, absolute, and fixed.
11. How do you create a CSS animation? Provide an example illustrating key animation
properties.
12. Describe the concept of CSS specificity and inheritance. How does inheritance work in
CSS?
13. What is the purpose of media queries in CSS, and how do they enable responsive web
design?
14. Explain the difference between em, rem, px, and % units in CSS for defining sizes and
dimensions.
15. How do you use CSS preprocessors like Sass or LESS to enhance the capabilities of
CSS? Provide an example of a feature offered by preprocessors.

Tinsae D@2024 Internet and web design


Unit 4: Java script

4.1. Introduction

JavaScript is a versatile and widely-used programming language primarily employed for


developing web applications. Initially developed by Brendan Eich at Netscape in 1995, it has
since become one of the core technologies of the World Wide Web alongside HTML and CSS.
Unlike Java, JavaScript has no relation to the Java programming language. JavaScript is primarily
a client-side scripting language, meaning it runs on the user's web browser, enabling dynamic
interaction with web pages. It's used for tasks such as form validation, creating interactive
elements like sliders and dropdown menus, and handling asynchronous requests to fetch data from
servers without reloading the entire page.
In addition to client-side scripting, JavaScript can also be used for server-side programming
through platforms like Node.js. This allows developers to write JavaScript code that runs on the
server, enabling full-stack development with a single programming language.
JavaScript is a high-level, interpreted language with dynamic typing, meaning variable types are
determined at runtime rather than compile-time. It supports object-oriented, imperative, and
functional programming paradigms, providing developers with a wide range of tools and
techniques for building complex applications.
Unit 1: Understanding JavaScript
• Objective: To introduce students to JavaScript as a programming language and its role in
web development.

Evolution of JavaScript

1. Creation of JavaScript (1995)


• JavaScript was created by Brendan Eich in 1995 while he was working at Netscape
Communications Corporation.
• Originally named Mocha, it was later renamed to LiveScript, and finally JavaScript due
to a partnership with Sun Microsystems.
2. Introduction of ECMAScript (1997)
• JavaScript was submitted to the European Computer Manufacturers Association (ECMA)
for standardization.
• ECMAScript, the standardized specification for JavaScript, was released as ECMA-262
in June 1997.
• ECMAScript 1 laid the foundation for the language, defining its syntax, data types, and
basic functionality.
3. ECMAScript 3 (1999)
• Significant update to the ECMAScript specification, introducing new features such as
regular expressions, try/catch exception handling, and switch statement improvements.

Tinsae D@2024 Internet and web design


• This version of ECMAScript was widely adopted and formed the basis of JavaScript
implementations in major web browsers.
4. ECMAScript 4 (Abandoned)
• Development of ECMAScript 4 began but was eventually abandoned due to
disagreements among stakeholders regarding the proposed features and complexity.
• Instead of releasing ECMAScript 4, the ECMAScript committee decided to focus on
smaller, incremental updates.
5. ECMAScript 5 (2009)
• Released in December 2009, ECMAScript 5 introduced significant enhancements and
improvements to the language.
• New features included strict mode, which provided better error handling and improved
security, as well as array methods like forEach, map, filter, and reduce.
• ECMAScript 5 was widely adopted and is still supported by all modern web browsers.
6. ECMAScript 6 (ES2015)
• Released in June 2015, ECMAScript 6, also known as ES6 or ES2015, was a major
milestone in the evolution of JavaScript.
• ES6 introduced many new features and syntax enhancements, including let and const for
variable declaration, arrow functions, template literals, classes, and modules.
• It also introduced new data structures like Map, Set, and symbols, as well as promises for
asynchronous programming.
• ECMAScript 6 aimed to make JavaScript code more readable, maintainable, and
expressive.
7. Subsequent ECMAScript Versions
• Following the release of ECMAScript 6, the ECMAScript specification adopted a yearly
release cycle, with new versions introduced annually.
• Subsequent versions, including ECMAScript 7 (ES2016), ECMAScript 8 (ES2017),
ECMAScript 9 (ES2018), ECMAScript 10 (ES2019), ECMAScript 11 (ES2020), and
ECMAScript 12 (ES2021), introduced additional features, syntax enhancements, and
improvements to the language.
• These updates focused on enhancing developer productivity, improving performance, and
addressing pain points in JavaScript development.
8. Latest Version: ECMAScript 13 (ES2022)
• ECMAScript 13, also known as ES2022, is the latest version of the ECMAScript
specification.
• Released in June 2022, ES2022 introduces new features such as class fields, private
methods and accessors, extended numeric separators, and more.
• It continues the tradition of improving JavaScript by adding new capabilities and refining
existing features to meet the needs of modern web development.

Tinsae D@2024 Internet and web design


The evolution of JavaScript, guided by the ECMAScript specification, has transformed it from a
simple scripting language to a powerful, versatile, and widely-used programming language that
powers the modern web.

4.2. JavaScript Vs HTML, and CSS

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:

• Client-side vs. Server-side: JavaScript is primarily known as a client-side programming


language, meaning it is executed on the client's web browser rather than on the server.
However, with the introduction of technologies like Node.js, JavaScript can also be used
for server-side programming like PHP. Node.js allows developers to run JavaScript code
on the server, enabling full-stack development with a single language. Therefore, while
JavaScript's origins lie in client-side scripting, its versatility extends to server-side
programming as well.
• Role: HTML provides the structure and content, CSS styles the presentation, JavaScript
adds interactivity, and PHP handles server-side logic and data processing.
• Integration: JavaScript can be embedded directly within HTML files or included as
external script files. CSS is also included within HTML files or linked externally. PHP
code is typically embedded within HTML files and executed on the server before being
sent to the client.
• Dynamic vs. Static: JavaScript and PHP allow for dynamic content generation, while
HTML and CSS primarily define static content and presentation.

4.3. JavaScript variables


JavaScript variables are containers for storing data values. Unlike other programming languages,
JavaScript is dynamically typed, meaning you don't have to declare the data type of a variable
when you create it. Here's a detailed discussion of JavaScript variables:

Declaration and Initialization:

• var: The traditional way of declaring variables in JavaScript. e.g:

Tinsae D@2024 Internet and web design


var x; // Declaration
x = 10; // Initialization
• let: Introduced in ES6, let allows block-scoped variables that can be reassigned. e.g:
let y; // Declaration
y = 'Hello'; // Initialization
• const: Also introduced in ES6, const declares variables with a constant (unchanging)
value. They must be initialized when declared and cannot be reassigned. Example:
const PI = 3.14; // Declaration and initialization

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:

• Use const for variables that won't be reassigned.


• Use let for variables that may be reassigned.
• Avoid using var due to its function scope and hoisting behavior.
• Always declare variables before using them to avoid unexpected behavior.
JavaScript Datatypes
JavaScript supports several data types, which can be broadly categorized into primitive
and reference types.

Primitive Data Types:

1. Number: Represents numeric values, including integers and floating-point numbers.

Tinsae D@2024 Internet and web design


let num = 10;
let floatNum = 3.14;
2. String: Represents sequences of characters enclosed within single or double quotes.
let str = 'Hello';

2. Boolean: Represents logical values true or false.


let isTrue = true;
let isFalse = false;

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

Reference Data Types:

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

2. Array: Represents an ordered collection of elements, indexed by non-negative integers.


let arr = [1, 2, 3, 4];
3. Function: Represents a reusable block of code that performs a specific task.
function greet(name) {
return 'Hello, ' + name + '!';
}
4. Date: Represents a specific point in time, with methods for working with dates and times.
let today = new Date();
5. RegExp: Represents regular expressions, used for pattern matching within strings.
let pattern = /[a-zA-Z]+/;

Tinsae D@2024 Internet and web design


Special Data Types:

1. NaN (Not a Number): Represents a value that is not a valid number.


let result = 'Hello' / 2;
console.log(result); // Output: NaN
2. Infinity and -Infinity: Represent positive and negative infinity, respectively.
let positiveInfinity = Infinity;
let negativeInfinity = -Infinity;
JavaScript Operators
JavaScript operators are symbols that perform operations on operands (values or variables). They
can be categorized into several types based on their functionality. Here's a detailed discussion of
JavaScript operators:

Arithmetic Operators:

Arithmetic operators perform mathematical calculations on numeric operands.


• Addition (+): Adds two operands.
• Subtraction (-): Subtracts the second operand from the first.
• Multiplication (*): Multiplies two operands.
• Division (/): Divides the first operand by the second.
• Modulus (%): Returns the remainder of the division of the first operand by the second.

Assignment Operators:

Assignment operators assign values to variables.


• Assignment (=): Assigns the value of the right operand to the left operand.
• Addition Assignment (+=): Adds the value of the right operand to the left operand and
assigns the result to the left operand.
• Subtraction Assignment (-=): Subtracts the value of the right operand from the left
operand and assigns the result to the left operand.
• Multiplication Assignment (*=): Multiplies the value of the left operand by the value of
the right operand and assigns the result to the left operand.
• Division Assignment (/=): Divides the value of the left operand by the value of the right
operand and assigns the result to the left operand.

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.

Tinsae D@2024 Internet and web design


• Strict Not Equal (!==): Checks if two operands are not equal in value or type.
• Greater Than (>): Checks if the left operand is greater than the right operand.
• Less Than (<): Checks if the left operand is less than the right operand.
• Greater Than or Equal To (>=): Checks if the left operand is greater than or equal to
the right operand.
• Less Than or Equal To (<=): Checks if the left operand is less than or equal to the right
operand.

Logical Operators:

Logical operators perform logical operations on Boolean operands.


• Logical AND (&&): Returns true if both operands are true.
• Logical OR (||): Returns true if at least one of the operands is true.
• Logical NOT (!): Returns true if the operand is false and vice versa.

Unary Operators:

Unary operators operate on a single operand.


• Unary Plus (+): Converts its operand into a number.
• Unary Negation (-): Negates its operand.
• Increment (++): Increases the value of its operand by 1.
• Decrement (--): Decreases the value of its operand by 1.

Conditional (Ternary) Operator:

The conditional operator (?:) is the only ternary operator in JavaScript.


• Conditional Operator (?:): Evaluates a condition and returns one of two expressions
based on whether the condition is true or false.

Bitwise Operators:

Bitwise operators perform bitwise operations on integer operands.


• Bitwise AND (&): Performs a bitwise AND operation.
• Bitwise OR (|): Performs a bitwise OR operation.
• Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation.
• Bitwise NOT (~): Inverts the bits of its operand.
• Left Shift (<<): Shifts the bits of the left operand to the left by the number of positions
specified by the right operand.
• Right Shift (>>): Shifts the bits of the left operand to the right by the number of positions
specified by the right operand.

Tinsae D@2024 Internet and web design


• Unsigned Right Shift (>>>): Shifts the bits of the left operand to the right by the number
of positions specified by the right operand, filling the leftmost positions with zeros.

Java script Control Statements:

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

Tinsae D@2024 Internet and web design


break;
default:
// 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
}

Other Control Structures:

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

Tinsae D@2024 Internet and web design


Unit 3: Functions
• Objective: To teach students how to define and use functions in JavaScript.

Java script functions

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:

• The function keyword followed by the function name.


• Optional parameters enclosed in parentheses.
• The function body enclosed in curly braces.
• Optionally, a return statement to specify the value that the function should return.
e.g.
function greet(name) {
return 'Hello, ' + name + '!';
}

ii. Function Expression:

A function expression defines a function as part of a larger expression, such as assigning it to a


variable. It's often used when a function is assigned to a variable, passed as an argument to another
function, or used as an immediately-invoked function expression (IIFE). e.g:

let greet = function(name) {


return 'Hello, ' + name + '!';
};

iii. Arrow Function:

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:

Tinsae D@2024 Internet and web design


let greet = (name) => {
return 'Hello, ' + name + '!';
};

iv. Anonymous Function:

An anonymous function is a function without a name. It's often used in function expressions or
as callback functions.

let greet = function(name) {


return 'Hello, ' + name + '!';
};

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

vi. Function Invocation:

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 + '!';

Tinsae D@2024 Internet and web design


}
console.log(greet('Alice')); // Output: Hello, Alice!

vii. Function Scope:

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

viii. Function Hoisting:

Function declarations are hoisted to the top of their containing scope, allowing them to be called
before they are declared.

console.log(add(2, 3)); // Output: 5


function add(a, b) {
return a + b;
}

ix. Recursive Function:

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.

Tinsae D@2024 Internet and web design


function process(callback) {
callback();
}
function greet() {
console.log('Hello!');
}
process(greet); // Output: Hello!

Function Parameters and Arguments:

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

JavaScript Scope of functions


The scope of a function in JavaScript refers to the accessibility and visibility of variables and
functions within that function. Understanding function scope is crucial for writing maintainable
and predictable code. Here's a detailed discussion of function scope in JavaScript:

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.

Tinsae D@2024 Internet and web design


function test() {
let localVar = 'I am local';
console.log(localVar); // Output: I am local
}

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

Block Scope (with let and const):

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
}

console.log(blockVar); // Error: blockVar is not defined

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

Tinsae D@2024 Internet and web design


console.log(outerVar); // Output: I am outer
}

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

let closureFunc = outer();


closureFunc();

Tinsae D@2024 Internet and web design


Summary Questions

Introduction to Web Development and Web Protocols:

1. What is the fundamental difference between client-side and server-side scripting?


2. Explain the role of HTTP in web development and how it facilitates communication
between clients and servers.
3. What is DNS (Domain Name System) and how does it work in the context of web
development?
4. Define SSL/TLS and explain its importance in securing web communication.
5. Describe the purpose of HTTP headers and provide examples of common header fields.
6. What is the key difference between HTTP and HTTPS, and why is HTTPS considered
more secure?
7. Explain the significance of RESTful APIs in web development and give examples of how
they are used.
8. What is a cookie in web development, and how is it used to store user data?
9. Differentiate between stateful and stateless communication in web development,
providing examples of each.
10. Discuss the role of web standards bodies like W3C and WHATWG in shaping the
landscape of web development.

HTML:

1. What is HTML and what is its role in web development?


2. Differentiate between HTML elements and HTML attributes, providing examples of
each.
3. Explain the purpose of semantic HTML and provide examples of semantic elements.
4. What is the key difference between HTML4 and HTML5?
5. Describe the structure of an HTML document, including the essential elements.
6. What is the purpose of the <div> and <span> elements in HTML, and how do they
differ?
7. Explain the significance of the <meta> tag in HTML and provide examples of its usage.
8. Discuss the role of HTML forms in web development and provide examples of form
elements.
9. What is the HTML5 canvas element, and how is it used in web development?
10. Describe the purpose of HTML entities and provide examples of commonly used entities.

CSS:

1. What is CSS, and what is its role in web development?


2. Differentiate between inline, internal, and external CSS, providing examples of each.
3. Explain the box model in CSS and how it influences the layout of elements on a web
page.
4. Describe the difference between classes and IDs in CSS, and when you would use each.
5. What are CSS selectors, and how are they used to target HTML elements for styling?

Tinsae D@2024 Internet and web design


6. Discuss the purpose of CSS preprocessors like Sass and LESS, and provide examples of
their features.
7. Explain the concept of CSS specificity and how it determines which styles apply to an
element.
8. Describe the difference between absolute and relative positioning in CSS.
9. What are CSS frameworks, and how do they simplify the process of styling web pages?
10. Discuss the role of media queries in responsive web design and provide examples of their
usage.

JavaScript:

1. What is JavaScript, and what is its role in web development?


2. Explain the difference between JavaScript and Java.
3. Describe the purpose of variables in JavaScript and provide examples of variable
declarations.
4. What are data types in JavaScript, and how are they classified?
5. Discuss the concept of scope in JavaScript and how it affects variable accessibility.
6. Explain the difference between == and === operators in JavaScript.
7. Describe the purpose of functions in JavaScript and provide examples of function
declarations and expressions.
8. What are JavaScript events, and how are they used to create interactive web pages?
9. Discuss the role of AJAX in web development and how it enables asynchronous
communication with servers.
10. Explain the concept of closures in JavaScript and provide examples of their usage.

Tinsae D@2024 Internet and web design


Sub theme 3: Web Programming
Introduction
Welcome to the Web Programming module, designed to equip you with the essential skills and
knowledge needed to develop dynamic and interactive web applications using PHP. In today's
digital era, web development plays a crucial role in creating engaging online experiences,
powering e-commerce platforms, and facilitating communication between users worldwide. This
module will guide you through the fundamentals of web programming with PHP, providing you
with a solid foundation to build upon as you embark on your journey into the world of web
development.

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!

Tinsae D. @ 2024 Web Programming


Learning Outcome

Upon completion of this module,


• Students will gain a comprehensive understanding of web development concepts, including
client-server architecture, HTTP protocol, and the role of server-side scripting languages
like PHP in creating dynamic web applications.
• Students will learn the syntax, data types, operators, control structures, and functions of
PHP, enabling them to write clean, efficient, and maintainable code for web development
projects.
• Students will be able to integrate PHP with HTML to create dynamic web pages that can
generate content dynamically, handle user input through forms, and interact with databases
to retrieve, manipulate, and display data.
• Students will learn how to perform server-side processing using PHP, including handling
form submissions, processing user input securely, and managing sessions and cookies to
create personalized user experiences.
• Students will gain proficiency in interacting with databases using PHP's built-in database
extensions, such as MySQL. They will learn how to establish database connections,
execute SQL queries, and handle database transactions to store and retrieve data efficiently.
• Students will understand the principles of object-oriented programming (OOP) and learn
how to apply them in PHP to create reusable and modular code. They will learn about
classes, objects, inheritance, encapsulation, and polymorphism.

Tinsae D. @ 2024 Web Programming


Unit 1: Introduction to Web Development
1.1.Introduction
Web development encompasses the creation and maintenance of websites and web applications,
providing a foundation for businesses, organizations, and individuals to establish their online
presence and interact with users across the globe. At its core, web development involves the
integration of various technologies and programming languages to design, develop, and deploy
functional and visually appealing web experiences. PHP (Hypertext Preprocessor) stands out as
one of the most widely used server-side scripting languages in web development, renowned for its
versatility, ease of use, and extensive community support. With PHP, developers can build
dynamic and interactive websites, handle user input securely, and interact with databases to store
and retrieve data efficiently.

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.

1.2. Server-side Scripting (programming) Languages


Server-side scripting refers to the process of running scripts on a web server to generate dynamic
web content before it is sent to the client's web browser. Unlike client-side scripting, which runs
on the user's browser, server-side scripting occurs on the server side, allowing for dynamic content
generation, database interaction, and server-side processing.
How Server-Side Scripting Works
• Client Request: When a user accesses a web page or requests a resource (such as
submitting a form), their web browser sends an HTTP request to the server.
• Server Processing: The server receives the request and determines which server-side script
or program to execute based on the requested URL or resource.

Tinsae D. @ 2024 Web Programming


• Execution of Server-Side Script: The server executes the server-side script, which may
be written in languages like PHP, Python, Ruby, Node.js (JavaScript), ASP.NET (C#), or
others.
• Dynamic Content Generation: The server-side script generates dynamic content by
processing data, interacting with databases, and performing other tasks based on the request
parameters or user input.
• Response Sent to Client: Once the dynamic content is generated, the server sends an
HTTP response back to the client's web browser.
• Client Rendering: The client's web browser receives the response, which includes HTML,
CSS, JavaScript, and other resources, and renders the web page for the user to interact with.

Benefits of Server-Side Scripting:

• Dynamic Content Generation: Server-side scripting enables the generation of dynamic


web content tailored to each user, providing personalized experiences and real-time
updates.
• Database Interaction: Server-side scripts can interact with databases to retrieve, store,
and manipulate data, allowing for the development of database-driven web applications
with rich functionality.
• Server-Side Processing: Complex processing tasks, such as form validation,
authentication, file uploads, data encryption, and business logic execution, can be
performed securely on the server side.
• Security: Server-side scripting enhances security by keeping sensitive operations and data
handling on the server, reducing the risk of client-side vulnerabilities and unauthorized
access.
• Scalability: Server-side scripting facilitates the development of scalable web applications
that can handle large volumes of traffic and dynamically adapt to changing user demands,
ensuring optimal performance and reliability.

Common Server-Side Scripting Languages:

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

Tinsae D. @ 2024 Web Programming


PHP Vs Other Server side scripting (Programming)
Comparing PHP with other server-side scripting languages involves evaluating various factors
such as syntax, performance, community support, ecosystem, and use cases. Here is a comparison
of PHP with some other popular server-side scripting languages like Python, Ruby, and Node.js
(JavaScript):

PHP vs. ASP.NET:

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

PHP vs. Python:

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

PHP vs. Ruby:

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

PHP vs. Node.js (JavaScript):

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

Unit 1: Summary questions

1. What is the significance of web development in today's digital era?


2. How does PHP contribute to the creation of dynamic and interactive websites?
3. What are the key components involved in web development projects?
4. How does server-side scripting differ from client-side scripting in web development?
5. What are some popular PHP frameworks and their advantages in web development?
6. How does PHP interact with databases to store and retrieve data efficiently?
7. What are the advantages of using PHP for students and professionals in the web
development domain?

Tinsae D. @ 2024 Web Programming


Unit 2: Understanding PHP Fundamentals
2.1. Introduction to PHP

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.

PHP is a server-side scripting language that is embedded in HTML. PHP is a cross-platform


language, capable of running on all major operating system platforms and with most of the web
server programs such as Apache, IIS, lighttpd and nginx.

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.

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

• Web Pages and Web-Based Applications


• Content Management Systems, and
• Ecommerce Applications etc.

A number of PHP based web frameworks have been developed to speed-up the web application
development. The examples are WordPress, Laravel, Symfony etc.

Advantages of Using PHP

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 −

• PHP is a multi-paradigm language that supports imperative, functional, object-oriented,


and procedural programming methodologies.
• PHP is a server-side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.

Tinsae D. @ 2024 Web Programming


• PHP is integrated with a number of popular databases including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
• PHP is pleasingly zippy in its execution, especially when compiled as an Apache module
on the Unix side. The MySQL server, once started, executes even very complex queries
with huge result sets in record-setting time.
• PHP supports a number of protocols such as POP3, IMAP, and LDAP. PHP supports
distributed object architectures (COM and CORBA), which makes n-tier development
possible.
• PHP is forgiving: PHP language tries to be as forgiving as possible.
• PHP has a familiar C-like syntax.

There are five important characteristics of PHP that make its practical nature possible:
Simplicity, Efficiency, Security, Flexibility, and Familiarity.

Hello World Using PHP

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

2.2. Syntax and Structure of PHP Code

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.

Statements and Semicolons:

• 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

Tinsae D. @ 2024 Web Programming


Comments in PHP serve as annotations within the codebase, providing explanations,
documentation, and context to developers reading the code. PHP supports both single-line and
multi-line comments. Let's delve into the details of 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:

// This is a single-line comment in PHP


$name = "John"; // Assigning a value to the $name variable

ii. Multi-line Comments:

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

2.3. PHP variables


i. Declaration and Naming:

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

ii. Data Types:

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

iii. Variable Scope:

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

iv. Variable Assignment and Manipulation:

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

• PHP supports variable variables, allowing the variable name to be determined


dynamically at runtime.
• Variable variables are created by prefixing the variable name with another variable
containing the variable name. For example:
$varName = "name";
$$varName = "John";
echo $name; // Output: John

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

Tinsae D. @ 2024 Web Programming


const SITE_NAME = "My Website";

2.4. PHP Operators

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:

• Arithmetic operators are used to perform mathematical calculations.


• They include addition +, subtraction -, multiplication *, division /, and modulus %
(returns the remainder of a division).
• Example
$num1 = 10;
$num2 = 5;
$sum = $num1 + $num2; // Addition
$difference = $num1 - $num2; // Subtraction
$product = $num1 * $num2; // Multiplication
$quotient = $num1 / $num2; // Division
$remainder = $num1 % $num2; // Modulus

ii. Assignment Operators:

• Assignment operators are used to assign values to variables.


• They include the simple assignment =, as well as compound assignment operators like
+=, -=, *=, /=, and %=.
• Example:
$num = 10;
$num += 5; // Equivalent to: $num = $num + 5;

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

Tinsae D. @ 2024 Web Programming


iv. Logical Operators:

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

v. Increment and Decrement Operators:

• 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

vi. Concatenation Operator:

• The concatenation operator . is used to concatenate strings together.


• It allows for the joining of two or more strings to form a single string.
• Example:
$name = "John";
$message = "Hello, " . $name . "!";

vii. Bitwise Operators:

• 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

Tinsae D. @ 2024 Web Programming


2.5.PHP Control Structures

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
}

iii. Switch Statement:

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:

Control transfer statements in PHP alter the flow of execution within loops and switch
statements.

• break Statement: Terminates the execution of a loop or switch statement.


• continue Statement: Skips the remaining code in the current iteration of a loop and
moves to the next iteration.
Tinsae D. @ 2024 Web Programming
• return Statement: Exits a function and optionally returns a value to the calling code.

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 functionName($param1, $param2, ...) {


// Function body: code to be executed
}

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

• PHP functions can return values using the return statement.


• The return statement terminates the function execution and optionally returns a value
back to the calling code.
• Example of a function with a return value:

function add($num1, $num2) {


return $num1 + $num2;
}

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.

Variable-length Argument Lists:

• PHP allows functions to accept a variable number of arguments using variable-length


argument lists.
• This is achieved using the func_get_args() function or the ... operator (also known as the
splat operator) in the function definition.
• Example of using variable-length argument lists
function sum(...$nums) {
return array_sum($nums);
}

Anonymous Functions (Closures):

• 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!";
};

Tinsae D. @ 2024 Web Programming


Unit 2: Summary Questions

1. What is PHP, and why is it widely used in web development?


2. How does PHP seamlessly integrate with HTML for creating dynamic web pages?
3. What are the core concepts of PHP programming, such as variable declaration and data
types?
4. How does PHP handle user input securely in web applications?
5. What role does object-oriented programming (OOP) play in PHP development?
6. How can PHP be used to validate form data effectively?
7. What are the best practices for writing clean and efficient PHP code?
8. How does PHP manage sessions and cookies to create personalized user experiences?
9. What are the built-in database extensions in PHP, and how do they interact with
databases like MySQL?
10. How can PHP execute SQL queries to retrieve, manipulate, and store data in web
applications?

Tinsae D. @ 2024 Web Programming


Unit 3: Creating Dynamic Web Pages with PHP

3.1.Integrating PHP with HTML

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:

i. Opening and Closing PHP Tags:

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

ii. Writing PHP Code Blocks:

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

iii. Mixing HTML and PHP:

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

iv. Mixing PHP within HTML Attributes:

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

v. Outputting PHP Variables:

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

vi. Escaping from PHP Mode:

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

Tinsae D. @ 2024 Web Programming


• Example
<?php
// Escaping from PHP mode
?>
<p>This HTML content is outside of PHP mode.</p>
<?php
// Back to PHP mode
?>

3.2.Writing basic PHP scripts to generate dynamic content.

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:

Tinsae D. @ 2024 Web Programming


i. Outputting <div> Elements:

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

ii. Outputting <p> Elements:

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

iii. Outputting <ul> and <li> Elements (Lists):

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

iv. Outputting Other HTML Elements:

PHP can output various other HTML elements dynamically, including headers (<h1>, <h2>,
etc.), links (<a>), images (<img>), forms (<form>, <input>, etc.), and more.

Tinsae D. @ 2024 Web Programming


Example (Dynamic Link):

<?php
$url = "https://example.com";
$linkText = "Visit Example";
echo "<a href='$url'>$linkText</a>";
?>

v. Conditional Output of HTML Elements:

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

vi. Generating Complex HTML Structures:

PHP can generate complex HTML structures dynamically by combining various HTML
elements, attributes, and content based on dynamic data or logic.

Example (Dynamic Table):

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

3.4.Handling User Input with Forms


Handling user input with forms in PHP involves capturing data submitted by users through
HTML forms, processing the data on the server-side with PHP scripts, and performing validation
and sanitization to ensure data integrity and security. Let's discuss the process of handling user
input with forms in detail:

1. Creating HTML Forms:

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:

<form action="process_form.php" method="POST">


<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br>
<input type="submit" value="Submit">
</form>

2. Processing Form Data with PHP:

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:

Method of Data Transmission:

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

Data Size Limitations:

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

Tinsae D. @ 2024 Web Programming


Caching and Bookmarking:

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

3. Validating User Input:

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

4. Sanitizing User Input:

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:

Tinsae D. @ 2024 Web Programming


$username = htmlspecialchars($_POST["username"]);
$password = htmlspecialchars($_POST["password"]);

5. Repopulating Form Fields:

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:

<input type="text" id="username" name="username" value="<?php echo


isset($_POST['username']) ? $_POST['username'] : ''; ?>">

6. Preventing CSRF Attacks:

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.

i. Generating CSRF Token:

First, we generate a CSRF token when rendering the form and store it in the session.

<?php
session_start();

// Generate CSRF token


if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];
?>

ii. Adding CSRF Token to Form:

We include the CSRF token as a hidden input field within the form.

<form action="process_form.php" method="POST">


<!-- Other form fields -->
<input type="hidden" name="csrf_token" value="<?php echo $csrfToken;
?>">
<button type="submit">Submit</button>
</form>
Tinsae D. @ 2024 Web Programming
iii. Processing Form Submission with CSRF Check:

In the PHP script that processes the form submission (process_form.php), we validate the
CSRF token before processing any data.

<?php
session_start();

// Check CSRF token


if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['csrf_token']) && $_POST['csrf_token'] ===
$_SESSION['csrf_token']) {
// Process form data
// ...
// Reset CSRF token after successful submission
unset($_SESSION['csrf_token']);
// Redirect or display success message
} else {
// Invalid CSRF token or CSRF attack detected
// Handle error (e.g., redirect to error page)
exit("CSRF attack detected!");
}
?>

3.6.Implementing Server-side Validation and Sanitization

Implementing server-side validation and sanitization is a critical aspect of web


development to ensure the security and integrity of user-submitted data. Server-side
validation involves verifying that user input meets predefined criteria, while sanitization
entails cleaning and filtering input data to prevent security vulnerabilities such as SQL
injection and cross-site scripting (XSS) attacks. Let's delve into the details of implementing
server-side validation and sanitization in PHP with examples:

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:

// Check if the username is available


if (usernameExists($_POST['username'])) {
$errors[] = "Username is already taken.";
}

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:

$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);


b. Database Escaping:
Escape special characters in input data before inserting into a database to prevent SQL injection.

Example:

$email = mysqli_real_escape_string($conn, $_POST['email']);

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

2. Storing Data in Sessions:

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.

// Storing data in sessions


$_SESSION['username'] = 'john_doe';
$_SESSION['cart'] = ['item1', 'item2', 'item3'];

3. Retrieving Data from Sessions:


Tinsae D. @ 2024 Web Programming
Data stored in sessions can be retrieved using the session variables stored in the $_SESSION
array.

// Retrieving data from sessions


$username = $_SESSION['username'];
$cartItems = $_SESSION['cart'];

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.

session.gc_maxlifetime = 3600 ; Session lifetime in seconds


session.cookie_lifetime = 0 ; Cookie lifetime (0 means until the browser is
closed)

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.

// Regenerate session ID to prevent session fixation


session_regenerate_id(true);

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.

// Destroy the session


session_destroy();

Example: Using Sessions for User Authentication:

Here's an example of how sessions can be used for user authentication:

session_start();

// Check if the user is logged in


Tinsae D. @ 2024 Web Programming
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
echo "Welcome back, " . $_SESSION['username'] . "!";
} else {
echo "Please log in to access this page.";
}

In this example, the $_SESSION['loggedin'] variable is used to determine if the user is


authenticated. If the variable is set to true, the user is considered logged in, and a personalized
welcome message is displayed.

Unit 3: Summary Questions

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?

Tinsae D. @ 2024 Web Programming


Unit 4 : Interacting with Databases using PHP

4.1. Introduction to Databases and MySQL

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.

MySQL is a robust and widely-used open-source relational database management system


(RDBMS) renowned for its reliability, performance, and ease of use. Originating from the Swedish
company MySQL AB, it became an essential component in web development due to its seamless
integration with various programming languages and frameworks. MySQL is instrumental in
storing and managing structured data for web applications, making it a cornerstone technology in
modern web development.

Key Features of MySQL:

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

Tinsae D. @ 2024 Web Programming


interactions, enabling developers to focus on application logic rather than database
management.

4.2. Establishing Database Connections in PHP

Establishing database connections in PHP is a fundamental aspect of web development, enabling


PHP scripts to interact with relational database management systems (RDBMS) such as MySQL,
PostgreSQL, SQLite, and others. Let's explore the process of establishing database connections
in PHP in detail:

1. Choosing a Database Extension:

PHP offers several extensions for interacting with databases, each designed to work with specific
database systems. The most commonly used extensions include:

• MySQLi (MySQL Improved): An improved version of the MySQL extension with


added functionality and support for newer MySQL features.
• PDO (PHP Data Objects): A database abstraction layer providing a consistent interface
for accessing various database systems, including MySQL, PostgreSQL, SQLite, and
more.

2. Installing Database Drivers:

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.

3. Database Connection Parameters:

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.

4. Establishing the Connection:

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.

Example using MySQLi: (Procedural)


// Database connection parameters
$host = 'localhost';
Tinsae D. @ 2024 Web Programming
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';

// Create a connection
$conn = mysqli_connect($host, $username, $password, $database);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";


Example using MySQLi: (OOP)
// Database connection parameters
$host = 'localhost';
$username = 'username';
$password = 'password';
$database = 'dbname';

// Create a MySQLi connection


$mysqli = new mysqli($host, $username, $password, $database);

// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
} else {
echo "Connected successfully";
}

Example using PDO:


// Database connection parameters
$host = 'localhost';
$username = 'username';
$password = 'password';
$database = 'dbname';

// Create a PDO connection


try {
$pdo = new PDO("mysql:host=$host;dbname=$database", $username,
$password);
echo "Connected successfully";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
Tinsae D. @ 2024 Web Programming
5. Handling Connection Errors:

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.

6. Closing the Connection:

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.

Example (Procedural MySQLi)


// Close connection
mysqli_close($conn);
Example (OOP MySQLi)
// Close connection
$mysqli->close();

4.3. Executing SQL Queries with PHP

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:

1. Establishing Connection to the Database:

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

Tinsae D. @ 2024 Web Programming


// Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

Tinsae D. @ 2024 Web Programming


2. Executing SQL Queries:

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

Tinsae D. @ 2024 Web Programming


?>

• $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]')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>

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

Tinsae D. @ 2024 Web Programming


• This example uses an SQL INSERT statement to add a new record to the MyGuests
table.

4. Updating Data:

//OOP
<?php
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=1";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
?>

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

Tinsae D. @ 2024 Web Programming


<?php
$sql = "DELETE FROM MyGuests WHERE id=1";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
?>

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

Tinsae D. @ 2024 Web Programming


//procedural
<?php
mysqli_close($conn);
?>
//PDO – this is optional
<?php
$conn = null;
?>

Unit 4: Summary questions

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?

Tinsae D. @ 2024 Web Programming


Unit 5: Applying Object Oriented using PHP

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
}

Tinsae D. @ 2024 Web Programming


2. Define Properties:

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:

Tinsae D. @ 2024 Web Programming


class Product {
public function displayDetails() {
echo "Product ID: " . $this->id . "<br>";
echo "Name: " . $this->name . "<br>";
echo "Price: $" . $this->price . "<br>";
echo "Description: " . $this->description . "<br>";
}
}

5. Utilize OOP Concepts:

• Encapsulation: Encapsulate properties and hide internal implementation details to


protect object integrity and ensure modularity.

Example:

class Product {
private $id;
private $name;
private $price;
private $description;

// Constructor and methods go here


}

• Inheritance: Create a class hierarchy if there are common behaviors or attributes shared
among different types of objects.

Example:

class DigitalProduct extends Product {


private $downloadLink;
private $expiryDate;

// Additional properties, constructor, and methods specific to digital products


}

Tinsae D. @ 2024 Web Programming


• Polymorphism: Implement polymorphic behavior by overriding methods in subclass
implementations or by using interfaces.

Example:

interface Shippable {
public function calculateShippingCost();
}

class PhysicalProduct extends Product implements Shippable {


public function calculateShippingCost() {
// Implementation specific to calculating shipping cost for physical products
}
}

6. Implement Error Handling and Validation:

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

Tinsae D. @ 2024 Web Programming


7. Documentation:

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;

// Additional documentation for properties, constructor, and methods


}

8. Example Usage:

Include example code snippets demonstrating how to use your module to perform common tasks.

Example:

// Create a new product


$product = new Product(1, "Example Product", 50.99, "Description of the
product");

// Display product details


$product->displayDetails();

9. Testing:

Write unit tests using a testing framework such as PHPUnit to validate the correctness and
robustness of your classes and methods.

Example:

class ProductTest extends PHPUnit\Framework\TestCase {


public function testProductDisplayDetails() {
Tinsae D. @ 2024 Web Programming
$product = new Product(1, "Test Product", 10.99, "Description");
$expectedOutput = "Product ID: 1<br>Name: Test Product<br>Price:
$10.99<br>Description: Description<br>";
$this->expectOutputString($expectedOutput);
$product->displayDetails();
}
}

Unit 5 : Summary Questions

1. How does object-oriented programming (OOP) enhance code organization and


reusability in PHP?
2. What are the fundamental principles of OOP, and how are they applied in PHP
development?
3. How can encapsulation be implemented in PHP classes to protect object integrity and
ensure modularity?
4. What is the significance of inheritance in OOP, and how can it be utilized in PHP for
code reusability?
5. How does polymorphism contribute to flexible and extensible code design in PHP OOP?
6. What are the key features of classes and objects in PHP, and how are they utilized in
OOP development?
7. How can PHP developers create class hierarchies and utilize inheritance to share
common behaviors among objects?

Tinsae D. @ 2024 Web Programming


Tinsae D. @ 2024 Web Programming
Sub theme 4: Multimedia System and Development

Tinsae D. @ 2024 Multimedia System and Development


Introduction

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.

Tinsae D. @ 2024 Multimedia System and Development


Learning Outcomes
After attending the lessons the students are expected to:
• Discuss the different uses of Multimedia and how could affect the daily lives of people
• Identify the different components of Multimedia and how could it be use with the latest
software
• Familiarized with the different Multimedia Files
• Use a multimedia software to developed a multimedia file Understand Photo and Video
terminologies, concepts, usage and editing techniques

Tinsae D. @ 2024 Multimedia System and Development


Unit 1: Introduction to Multimedia

1.1. What is Multimedia?

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.

A comprehensive definition of multimedia involves understanding its fundamental components:

1. Text: Written or typed content that provides information, instructions, or explanations


within multimedia presentations. Text is often used to complement other media elements
and convey specific messages.
2. Graphics and Images: Visual representations such as photographs, illustrations, diagrams,
charts, and graphs that enhance the visual appeal and understanding of multimedia content.
Graphics and images are used to convey complex concepts, depict scenarios, or evoke
emotions.
3. Audio: Sound elements such as music, narration, sound effects, and spoken dialogue that
accompany multimedia presentations. Audio enhances the immersive experience and can
provide additional context or information to the audience.
4. Video: Moving images or sequences of frames that depict scenes, events, or actions. Video
content adds dynamic visual elements to multimedia presentations and can be used for
storytelling, demonstrations, tutorials, or entertainment purposes.
5. Animations: Dynamic graphical elements that simulate motion or change over time.
Animations can range from simple transitions and effects to complex sequences that
illustrate processes, interactions, or simulations.

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.

1.2. Components of multimedia

Tinsae D. @ 2024 Multimedia System and Development


Multimedia encompasses a diverse range of components, each playing a unique role in creating
engaging and immersive digital experiences. Here's a detailed discussion of the key components
of multimedia:

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.

Tinsae D. @ 2024 Multimedia System and Development


• Purpose: Video engages the audience visually and emotionally, facilitating
demonstrations, tutorials, storytelling, entertainment, and information
dissemination.
• Examples: Video clips, movies, TV shows, documentaries, video advertisements,
video presentations, and tutorials.
v. Animations:
• Definition: Animations are dynamic graphical elements that simulate motion or
change over time.
• Characteristics: Animations can be created using frame-based animation
techniques or through algorithms that generate motion dynamically. They add
visual interest, interactivity, and dynamism to multimedia presentations.
• Purpose: Animations illustrate processes, interactions, transitions, and visual
effects, enhancing the user experience and conveying complex concepts more
effectively.
• Examples: Animated characters, motion graphics, transition effects, interactive
simulations, and visual effects in games or multimedia applications.

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:

1.3.1. Communication and Information Sharing

Multimedia facilitates effective communication by combining multiple media elements such


as text, graphics, images, audio, and video. It enables the creation of rich, engaging content
that can convey complex ideas, emotions, and messages more comprehensively than any single
medium.

In today's interconnected world, multimedia is instrumental in disseminating information


rapidly across different channels and platforms. It powers news websites, social media
platforms, online publications, and educational resources, enabling people to stay informed
and connected globally.

i. Social Media Platforms and Multimedia Sharing:


• Importance:
• Social media platforms rely heavily on multimedia content to engage
users and facilitate communication. Multimedia, including images,
videos, and interactive posts, enhance the visual appeal and storytelling
capabilities of social media.
Tinsae D. @ 2024 Multimedia System and Development
• Multimedia sharing on social media allows users to express themselves
creatively, share experiences, and connect with others on a deeper level.
It fosters a sense of community and belonging by enabling users to share
their thoughts, memories, and interests through visual means.
• Businesses leverage multimedia on social media for marketing and
branding purposes. Visual content attracts more attention and
engagement from users, leading to increased brand visibility, customer
engagement, and conversion rates.
• Multimedia sharing on social media has transformed the way
information spreads, enabling rapid dissemination of news, trends, and
viral content. It has democratized content creation, allowing individuals
and organizations to reach a global audience with minimal barriers.
ii. Video Conferencing and Online Collaboration Tools:
• Importance:
• Video conferencing and online collaboration tools have become
indispensable in the modern workplace, enabling remote
communication and collaboration among distributed teams.
• Multimedia, particularly video and audio, enhances the quality and
effectiveness of virtual meetings, presentations, and collaborative
sessions. It facilitates face-to-face interactions, non-verbal
communication cues, and real-time engagement among participants.
• Multimedia features such as screen sharing, document collaboration,
and virtual whiteboards empower teams to collaborate on projects, share
ideas, and brainstorm creatively regardless of geographic location.
• Video conferencing and online collaboration tools increase
productivity, efficiency, and flexibility in the workplace by reducing the
need for travel and enabling remote work arrangements. They foster a
culture of inclusivity and collaboration, leading to better teamwork and
decision-making outcomes.
iii. Multimedia Messaging Applications:
• Importance:
• Multimedia messaging applications, such as WhatsApp, Messenger,
and Snapchat, have revolutionized personal communication by enabling
users to exchange text, images, videos, voice messages, and emojis
seamlessly.
• Multimedia messaging enhances the expressiveness and emotional
depth of communication, allowing users to convey nuanced messages,
emotions, and experiences through visual and auditory means.
• Multimedia messaging applications facilitate instant communication
and real-time interaction, enabling users to stay connected with friends,
family, and colleagues regardless of distance or time zone.
• Multimedia messaging fosters intimacy, authenticity, and
personalization in communication by enabling users to share moments,
memories, and experiences in a multimedia-rich format. It strengthens

Tinsae D. @ 2024 Multimedia System and Development


relationships and creates meaningful connections in a digital
environment.

iv. Impact of Multimedia on Interpersonal Communication:


• Importance:
• Multimedia has transformed interpersonal communication by providing
multiple channels for expression, including text, images, videos, and
audio. It enriches communication by catering to diverse communication
styles and preferences.
• Visual and auditory elements in multimedia communication enhance
comprehension, engagement, and emotional resonance, enabling
individuals to convey complex ideas, emotions, and intentions more
effectively.
• Multimedia communication fosters empathy, understanding, and
connection among individuals by facilitating non-verbal cues, such as
facial expressions, tone of voice, and body language, which are essential
for building rapport and trust.
• However, the overreliance on multimedia communication, particularly
in digital environments, can also pose challenges such as
misinterpretation, distraction, and depersonalization. It is important to
strike a balance between multimedia-mediated communication and
face-to-face interactions to maintain healthy interpersonal relationships.

In general, multimedia plays a pivotal role in enhancing communication, collaboration, and


connectivity in various contexts, from social media platforms and online collaboration tools to
personal messaging applications and interpersonal communication. Its versatility and richness
enable individuals and organizations to express themselves, engage with others, and build
relationships in meaningful ways.

1.3.2. Multimedia in Education and Training

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:

i. E-learning Platforms and Digital Classrooms:


• E-learning platforms and digital classrooms leverage multimedia to deliver
educational content remotely, making learning accessible to a wide audience
regardless of geographical location or time constraints.
• Multimedia enhances the effectiveness of online learning by providing interactive
learning materials, including videos, animations, quizzes, and presentations, which
engage learners and facilitate comprehension.
• With multimedia, instructors can create dynamic and personalized learning
experiences, catering to diverse learning styles and preferences. Visual aids, audio
narration, and interactive exercises help reinforce key concepts and improve
retention.
• E-learning platforms foster collaboration and interaction among students and
instructors through multimedia features such as discussion forums, live chats, and
video conferencing, promoting active learning and peer-to-peer support.
ii. Interactive Multimedia Tutorials and Simulations:
• Interactive multimedia tutorials and simulations offer hands-on learning
experiences that simulate real-world scenarios, enabling learners to apply
theoretical knowledge in practical contexts.
• Multimedia tutorials combine text, images, videos, and interactive elements to
guide learners through step-by-step instructions, demonstrations, and exercises,
facilitating self-paced learning and skill acquisition.
• Simulations immerse learners in dynamic environments where they can
experiment, make decisions, and observe the consequences in a risk-free setting.
Multimedia simulations are particularly effective for training in technical skills,
problem-solving, and decision-making.
• Interactive multimedia tutorials and simulations cater to different learning
preferences and abilities, allowing learners to engage with content at their own
pace, revisit concepts as needed, and receive immediate feedback on their
performance.
iii. Virtual Laboratories and Immersive Learning Environments:
• Virtual laboratories and immersive learning environments replicate physical
laboratories and real-world settings using multimedia technologies, allowing
learners to conduct experiments, explore concepts, and practice skills in a virtual
space.
• Multimedia elements such as 3D models, animations, and simulations provide a
realistic and engaging learning experience, enhancing understanding and retention
of scientific principles and procedures.
Tinsae D. @ 2024 Multimedia System and Development
• Virtual laboratories offer benefits such as accessibility, scalability, and safety,
allowing learners to access laboratory resources anytime, anywhere, without the
need for expensive equipment or physical space.
• Immersive learning environments, such as virtual reality (VR) and augmented
reality (AR) simulations, transport learners to interactive and interactive
environments, fostering experiential learning and deeper engagement with content.
iv. Role of Multimedia in Skills Development and Vocational Training:
• Multimedia plays a crucial role in skills development and vocational training by
providing multimedia-rich resources, including instructional videos, simulations,
demonstrations, and case studies, that facilitate the acquisition of practical skills
and competencies.
• Multimedia enables trainers to demonstrate complex procedures, techniques, and
workflows visually, making training more accessible and comprehensible for
learners. It allows for repetition, practice, and self-assessment, which are essential
for skill mastery.
• Interactive multimedia modules and assessments provide immediate feedback and
performance tracking, allowing learners to monitor their progress and identify areas
for improvement. Multimedia also supports adaptive learning strategies, tailoring
content and pacing to individual learner needs.
• In vocational training, multimedia enhances the effectiveness of on-the-job
training, apprenticeships, and certification programs, preparing learners for real-
world challenges and career advancement opportunities.

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.

1.3.3. Multimedia for Marketing and Advertisement

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

Tinsae D. @ 2024 Multimedia System and Development


advertising campaigns, empowering brands to connect with consumers in meaningful ways and
drive business success in today's competitive landscape.

i. Use of Multimedia in Advertising Campaigns:


• Multimedia is integral to advertising campaigns, as it allows marketers to create
visually compelling and engaging content that captures the audience's attention and
conveys brand messages effectively.
• Multimedia elements such as images, videos, animations, and audio enhance the
storytelling capabilities of advertisements, enabling brands to evoke emotions,
showcase product features, and communicate brand values.
• Whether it's a television commercial, digital banner ad, or social media campaign,
multimedia content grabs the audience's interest and encourages them to engage
with the brand, leading to increased brand awareness and recall.
ii. Interactive Multimedia Advertisements:
• Interactive multimedia advertisements invite audience participation and
engagement, transforming passive viewers into active participants in the
advertising experience.
• Interactive elements such as clickable buttons, hotspots, quizzes, games, and polls
encourage users to interact with the ad, explore product features, and discover more
about the brand.
• By allowing users to interact with the content, multimedia advertisements create
memorable experiences that leave a lasting impression and foster a deeper
connection with the brand.
iii. Product Demonstrations and Virtual Tours:
• Multimedia enables marketers to showcase product demonstrations and virtual
tours, providing potential customers with immersive experiences that simulate real-
world interactions with products or services.
• Through videos, 360-degree panoramas, virtual reality (VR), and augmented reality
(AR), multimedia allows customers to explore products from different angles,
visualize features, and understand how they work in context.
• Product demonstrations and virtual tours help alleviate doubts and uncertainties,
providing customers with valuable insights that aid in their purchase decision-
making process.
iv. Personalized Marketing through Multimedia Channels:
• Multimedia channels offer opportunities for personalized marketing, where brands
can tailor content to the preferences, interests, and behaviors of individual
consumers.
• Through data-driven insights and analytics, marketers can deliver personalized
multimedia messages across various channels, including email, social media,
websites, and mobile apps.
• Personalized multimedia content, such as personalized videos, dynamic ads, and
targeted messages, enhances relevance and engagement, driving higher conversion
rates and customer loyalty.

Tinsae D. @ 2024 Multimedia System and Development


In general, multimedia is a powerful tool in marketing and advertising, enabling brands to create
impactful campaigns that resonate with their target audience. From traditional advertising formats
to interactive and personalized experiences, multimedia enhances the effectiveness of marketing
efforts, driving brand awareness, engagement, and ultimately, conversions. By leveraging
multimedia channels and technologies, marketers can connect with consumers in meaningful ways
and drive business growth in today's competitive marketplace.

1.3.4. Multimedia in Entertainment

Multimedia has revolutionized the landscape of entertainment, offering immersive and


engaging experiences across various platforms. From blockbuster movies and television shows
to interactive video games and streaming services, multimedia content enriches our leisure
time with a diverse array of visual, auditory, and interactive elements. Through stunning
visuals, captivating soundtracks, and compelling storytelling, multimedia transports audiences
to fantastical worlds, evokes powerful emotions, and sparks imagination. Video games
leverage multimedia technology to provide interactive experiences that blur the lines between
reality and fiction, allowing players to become active participants in dynamic virtual
environments. Streaming platforms deliver on-demand access to a vast library of multimedia
content, catering to individual tastes and preferences. In essence, multimedia in entertainment
has transcended traditional boundaries, offering endless possibilities for exploration, creativity,
and enjoyment in the digital age.

i. Role of Multimedia in Gaming Industry:


• The gaming industry heavily relies on multimedia technology to deliver immersive
and interactive experiences to players worldwide.
• Multimedia elements such as high-definition graphics, realistic sound effects, and
dynamic animations enhance the visual appeal and gameplay mechanics of video
games.
• From console titles to mobile apps, multimedia technology enables developers to
create expansive virtual worlds, engaging narratives, and compelling characters
that captivate players' attention and imagination.
ii. Streaming Services and Multimedia Content Consumption:
• Streaming services have transformed the way audiences consume multimedia
content, offering on-demand access to a vast library of movies, TV shows, music,
and live events.
• Multimedia streaming platforms leverage advanced compression algorithms and
high-speed internet connectivity to deliver high-quality audiovisual content to
viewers across multiple devices.
• Through personalized recommendations and curated playlists, streaming services
cater to individual preferences, allowing users to discover and enjoy multimedia
content tailored to their tastes and interests.
iii. Augmented Reality (AR) and Virtual Reality (VR) Experiences:
• Augmented reality (AR) and virtual reality (VR) technologies push the boundaries
of entertainment by blending the physical and digital worlds or immersing users in
entirely virtual environments.
Tinsae D. @ 2024 Multimedia System and Development
• AR experiences overlay digital content onto the real world, enhancing live events,
theme park attractions, and interactive exhibits with multimedia elements such as
3D models, animations, and interactive overlays.
• VR experiences transport users to immersive digital environments, enabling them
to explore virtual worlds, interact with virtual objects, and participate in simulated
experiences such as gaming, storytelling, and educational simulations.
iv. Multimedia in Cinema and Digital Storytelling:
• Multimedia plays a central role in cinema and digital storytelling, enabling
filmmakers to craft visually stunning narratives that resonate with audiences on an
emotional level.
• Through cinematic techniques such as cinematography, visual effects, and sound
design, multimedia enhances the storytelling experience, immersing viewers in
compelling narratives and transporting them to different time periods, cultures, and
realities.
• Digital storytelling platforms leverage multimedia technology to create interactive
narratives, web series, and immersive experiences that engage audiences through
multiple sensory channels, blurring the lines between traditional media formats and
interactive entertainment.

Unit 2: Multimedia Components


Introduction to multimedia Components
Multimedia components constitute the building blocks of dynamic digital content, offering a rich
tapestry of textual, visual, and auditory elements. Textual content lays the groundwork for
communication, providing context, information, and structure within multimedia presentations. It
serves as a vehicle for conveying messages, guiding user interactions, and facilitating
comprehension. Meanwhile, visual elements such as graphics and images elevate the aesthetic
appeal of multimedia, offering vivid representations of concepts, scenarios, and emotions.
Graphics enhance storytelling by providing illustrations, diagrams, and charts, while images evoke
visceral reactions and establish connections with viewers. Complementing visuals, audio
components infuse multimedia with depth and immersion, harnessing the power of sound effects,
music, and narration to evoke emotions, set moods, and enhance storytelling.

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.

Tinsae D. @ 2024 Multimedia System and Development


2.1. Graphics and Images in Multimedia

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.

2.1.1. Use of graphics and images

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

Tinsae D. @ 2024 Multimedia System and Development


emotional resonance of visuals, communicators can foster deeper engagement and empathy
among their audience.
4. Establishing Brand Identity and Recognition: In branding and marketing, graphics and
images play a crucial role in establishing brand identity and recognition. Visual elements
such as logos, color schemes, typography, and imagery help convey brand values,
personality, and positioning to consumers. Consistent use of visual branding across
different channels and touchpoints reinforces brand recognition and builds brand loyalty
over time. For example, the iconic Apple logo instantly evokes associations with
innovation, simplicity, and premium quality, thanks to its minimalist design and ubiquitous
presence in Apple's marketing materials.
5. Facilitating Multicultural Communication: Graphics and images have the potential to
transcend language barriers and facilitate multicultural communication. Visual symbols,
icons, and metaphors can convey universal concepts and messages that are easily
understood by audiences from diverse cultural backgrounds. Additionally, the use of
culturally relevant imagery and visual cues can help connect with specific target
demographics and resonate with their values and preferences. By leveraging visual
communication strategies that are inclusive and culturally sensitive, communicators can
reach a wider audience and foster cross-cultural understanding and appreciation.

2.1.2. Overview of image editing software

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

2.1.3. Integration of graphics and images into Multimedia projects

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:

1. Design Software (e.g., Adobe Illustrator, CorelDRAW):


• Design software is essential for creating vector graphics, such as logos, icons, and
illustrations, that can be scaled to any size without losing quality.
• These programs offer tools for drawing shapes, lines, and curves, as well as for
manipulating text and creating complex artwork.
• Vector graphics created in design software can be easily imported into other
multimedia projects and manipulated further as needed.
2. Illustration Software (e.g., Adobe Photoshop, Procreate):
• Illustration software allows for the creation of raster graphics, which are
composed of individual pixels and are suitable for detailed artwork, digital
painting, and photo manipulation.
• These programs provide tools for drawing, painting, blending, and adding textures
to create realistic or stylized images.
• Illustration software is often used to enhance photographs, create digital paintings,
or add visual effects to multimedia projects.
3. Photo Editing Software (e.g., Adobe Photoshop, GIMP):
• Photo editing software is specifically designed for manipulating and enhancing
photographs.
• These programs offer a wide range of tools for adjusting colors, contrast,
exposure, and sharpness, as well as for retouching imperfections and removing
unwanted elements.
• Photo editing software is indispensable for improving the quality and aesthetics of
images used in multimedia projects, whether they are photographs taken by the
creator or stock images sourced from libraries.
Tinsae D. @ 2024 Multimedia System and Development
When integrating graphics and images into multimedia projects, creators often follow a
workflow that involves:

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

2.2. Audio in Multimedia

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:

• Enhancing Immersion: Audio adds depth and immersion to multimedia content by


creating ambiance, setting the mood, and evoking emotions. For example, background
music can enhance the atmosphere of a video or presentation, while sound effects can
make interactive experiences more realistic and interactive.
• Narration and Voiceovers: Narration and voiceovers are commonly used in multimedia
projects such as videos, presentations, and animations to provide explanations, guidance,
or storytelling. A well-produced narration can clarify complex concepts, maintain
audience engagement, and convey the intended message effectively.
• Music and Soundtracks: Music and soundtracks contribute to the mood and tone of
multimedia projects, influencing the audience's emotions and perception. The choice of
music genre, tempo, and instrumentation can significantly impact the viewer's
experience. Additionally, original scores or licensed music tracks can help establish the
identity and branding of a multimedia project.
• Sound Effects: Sound effects are used to enhance realism, create atmosphere, and
emphasize actions or events in multimedia content. They range from simple ambient
sounds like footsteps or birds chirping to complex effects like explosions or futuristic

Tinsae D. @ 2024 Multimedia System and Development


sounds in sci-fi projects. Sound effects add depth and dynamism to multimedia
experiences, making them more immersive and engaging.
• Accessibility: Audio also plays a critical role in making multimedia content accessible to
individuals with visual impairments or disabilities. Audio descriptions, closed captions,
and transcripts provide alternative ways for users to perceive and understand multimedia
content, ensuring inclusivity and compliance with accessibility standards.
• Technical Considerations: When incorporating audio into multimedia projects, creators
need to consider technical aspects such as audio quality, format compatibility, and file
size optimization. Choosing the right audio formats, bitrates, and compression techniques
ensures optimal playback quality and performance across different devices and platforms.
• Synchronization: Synchronizing audio with other multimedia elements, such as video,
animation, or interactive elements, is essential for maintaining coherence and delivering a
seamless user experience. Precise timing and coordination between audio cues and visual
elements enhance the effectiveness and impact of multimedia content.

2.2.1. Understanding the importance 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:

1. Enhancing Engagement and Retention: Incorporating audio into multimedia content


helps capture and maintain audience attention. Well-designed audio elements, such as
background music, narration, or sound effects, can evoke emotions, create atmosphere, and
enhance storytelling. Engaged audiences are more likely to remember and connect with the
content, leading to improved retention and comprehension of key messages.
2. Conveying Information: Audio serves as a powerful tool for conveying information in
multimedia presentations and videos. Narration, voiceovers, and dialogue provide
additional context, explanations, and insights that complement visual elements. In
educational or instructional content, audio can clarify complex concepts, guide learners
through processes, and reinforce key points, catering to different learning styles and
preferences.
3. Setting the Mood and Tone: The choice of audio elements, such as music tracks or sound
effects, significantly influences the mood and tone of multimedia content. Background
music can establish the ambiance, evoke specific emotions, and enhance the overall
storytelling experience. For example, suspenseful music builds tension in a thriller film,
while upbeat music creates a sense of excitement in a promotional video.
4. Creating Immersive Experiences: Audio plays a crucial role in creating immersive and
realistic experiences in interactive applications, such as video games, virtual reality (VR),
and augmented reality (AR). Realistic sound effects, spatial audio techniques, and dynamic
audio responses enhance the sense of presence and immersion, making users feel more
connected to the virtual environment or interactive elements.
5. Improving Accessibility: Audio contributes to making multimedia content accessible to
individuals with visual impairments or disabilities. Features such as audio descriptions,

Tinsae D. @ 2024 Multimedia System and Development


closed captions, and screen readers enable users to perceive and interact with multimedia
content effectively, ensuring inclusivity and compliance with accessibility standards.

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:

1. Audio Editing Tools:


• Trimming: Precise adjustment of the start and end points of audio clips to eliminate
unwanted portions or silence.
• Time Stretching and Pitch Shifting: Altering the duration (time stretching) or
pitch (pitch shifting) of audio clips without affecting their original tempo or pitch.
• Fades and Crossfades: Gradual increase or decrease in audio volume at the
beginning or end of a clip, or where two clips overlap to ensure smooth transitions.
• Normalization: Adjusting the amplitude of audio to maximize its volume without
clipping or distortion, typically used to achieve consistent levels across multiple
tracks.
• Noise Reduction: Removing unwanted background noise or hum from recordings
to improve audio quality.
• Audio Restoration: Repairing damaged or deteriorated audio recordings through
processes like de-clicking, de-humming, or de-noising.
2. Mixing Tools:
• Equalization (EQ): Adjusting the frequency balance of audio by boosting or
cutting specific frequency ranges to enhance clarity and tonal balance.
• Compression: Reducing the dynamic range of audio by attenuating loud sounds
and amplifying soft sounds, resulting in a more consistent volume level.
• Reverb and Delay: Adding spatial effects to audio by simulating the reflections of
sound in different environments (reverb) or creating echoes (delay), enhancing
depth and dimensionality.
• Panning: Placement of audio signals within the stereo or surround sound field,
allowing for the distribution of sound across the left-right spectrum for
spatialization.
• Automation: Recording and editing changes to various parameters (e.g., volume,
panning, effects) over time to create dynamic mixes and performances.
• Mix Buses and Sends: Routing multiple audio tracks to a common bus or auxiliary
channel, enabling centralized processing and effects application.
• Mixing Console Emulation: Simulating the workflow and sonic characteristics of
analog mixing consoles, providing a familiar interface and warmth to digital mixes.
3. Additional Tools:
• Virtual Instruments: Synthesizers, samplers, and drum machines integrated
within the DAW for creating musical elements.
Tinsae D. @ 2024 Multimedia System and Development
• MIDI Editing: Manipulation of MIDI data to edit note pitches, durations,
velocities, and other musical parameters.
• Score Editing: Arranging and editing musical scores or MIDI sequences within a
notation environment.
• Timecode and Synchronization: Aligning audio and video tracks, or
synchronizing multiple audio tracks using SMPTE timecode or other
synchronization methods.

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.

2.3. Video in Multimedia

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.

Tinsae D. @ 2024 Multimedia System and Development


• DaVinci Resolve: Known for its powerful color grading capabilities, DaVinci Resolve also
provides advanced editing features, audio tools, and visual effects.
• HitFilm Express: Combines professional-grade editing with robust compositing and
visual effects capabilities, making it suitable for filmmakers and YouTubers seeking
dynamic effects and animations.
• iMovie: Apple's entry-level video editing software featuring a user-friendly interface and
guided workflows, ideal for beginners and casual users.
• Adobe Premiere Elements: Simplified version of Premiere Pro with essential editing
features such as trimming, cropping, and adding titles and transitions, tailored to novice
editors.
• Other Options: There are numerous other video editing software options available,
ranging from professional-grade tools like Avid Media Composer to free and open-source
options like Shotcut and Blender.
• Common Features: Regardless of the software chosen, common features include timeline-
based editing, audio editing tools, support for various file formats, and the ability to export
videos in different resolutions and formats.
• Considerations: When selecting video editing software, factors to consider include
budget, desired features, ease of use, platform compatibility, and workflow integration with
other tools or software suites.
• Community and Support: Many video editing software platforms offer online
communities, tutorials, and technical support to assist users in learning and mastering the
software.
• Trial Versions: Before committing to a particular software, it's often beneficial to explore
trial versions or free versions to determine if the software meets your specific needs and
preferences.

2.4. Integration of multimedia components

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:

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.

Tinsae D. @ 2024 Multimedia System and Development


Animation Software:

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:

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.

Unit 3: Image Editing Basics


3.1. Introduction to Image Editing
Image editing is the process of altering or enhancing digital images to improve their appearance,
correct imperfections, or achieve a specific artistic effect. It plays a crucial role in various fields
such as photography, graphic design, advertising, and web development. Image editing
encompasses a wide range of techniques and tools, from basic adjustments like cropping and
resizing to advanced retouching and compositing.

Basic Image Editing Techniques:

1. Cropping and Resizing: Cropping involves removing unwanted parts of an image to


improve composition or focus on a specific subject. Resizing allows changing the
dimensions of an image, making it smaller for web use or larger for printing.
2. Color Adjustment: Adjusting brightness, contrast, saturation, and color balance can
enhance the overall look of an image. These adjustments help correct exposure issues,
improve color accuracy, and make images more vibrant.

Tinsae D. @ 2024 Multimedia System and Development


3. Sharpening and Noise Reduction: Sharpening enhances the clarity and detail of an image,
while noise reduction reduces unwanted graininess or pixelation. These techniques are
commonly used to improve the sharpness and quality of digital photos.
4. Rotation and Straightening: Rotating an image allows for correcting its orientation, while
straightening helps aligning crooked horizons or vertical lines. These adjustments
contribute to better composition and visual balance.

Advanced Image Editing Techniques:

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.

Workflow and Best Practices:

1. Non-Destructive Editing: Performing edits non-destructively preserves the original image


data, allowing for reversible changes and edits. This is achieved through techniques like
adjustment layers and smart objects.
2. Organization and File Management: Keeping images organized and properly labeled
helps maintain an efficient editing workflow. Folder structures, naming conventions, and
metadata management are essential for managing large collections of images.
3. Backup and Versioning: Regularly backing up edited images and maintaining version
history ensures data safety and allows for reverting to previous edits if needed.
4. Consistency and Style: Establishing a consistent editing style or workflow can help
maintain visual coherence across a series of images or projects. This includes using presets,
templates, or style guides to streamline editing processes.

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

Tinsae D. @ 2024 Multimedia System and Development


Different image file formats serve various purposes and have distinct characteristics that make
them suitable for specific use cases. Here's an explanation of some common image file formats:

i. JPEG (Joint Photographic Experts Group):


• JPEG is one of the most widely used image formats for digital photography and
web images.
• It uses lossy compression, meaning that some image data is discarded to reduce file
size. This compression can result in a smaller file size but may also lead to a loss
of image quality, especially when compressed heavily.
• JPEG supports millions of colors and is suitable for photographs and complex
images with gradients and fine details.
• It does not support transparency or animation.
ii. PNG (Portable Network Graphics):
• PNG is a lossless image format that supports high-quality compression and
transparency.
• It is commonly used for images with text, logos, or graphics with sharp edges, as it
preserves the clarity of these elements without introducing artifacts.
• PNG files can be interlaced, allowing images to load progressively in web
browsers.
• PNG is widely used for web graphics, digital art, and images that require
transparent backgrounds.
iii. TIFF (Tagged Image File Format):
• TIFF is a flexible and widely supported image format commonly used in
professional photography, printing, and graphic design.
• It supports lossless compression, preserving all image data without sacrificing
quality. It also supports layers, transparency, and multiple color spaces.
• TIFF files can be quite large compared to other formats, making them less suitable
for web use but ideal for high-quality prints and archival purposes.
• TIFF files are often used for storing raw or uncompressed image data before final
processing or printing.
iv. GIF (Graphics Interchange Format):
• GIF is a widely used image format for simple animations, logos, and graphics with
limited color palettes.
• It supports lossless compression and allows for transparency and animation through
frame-based sequencing.
• GIF images are limited to 256 colors, making them less suitable for photographs or
images with complex color gradients.
• GIFs are commonly used for web animations, avatars, and small graphics due to
their small file size and support for animation.
v. BMP (Bitmap):
• BMP is a standard Windows image format that stores uncompressed image data
pixel by pixel.
• It supports high-quality images with millions of colors but results in large file sizes.
• BMP files do not support compression, layers, or transparency, making them less
versatile compared to other formats.
Tinsae D. @ 2024 Multimedia System and Development
• BMP is primarily used for storing raw image data or for compatibility with legacy
systems and applications.
vi. RAW:
• RAW is not a standard image format but rather a generic term for unprocessed
image data captured by digital cameras.
• RAW files contain all the image data captured by the camera's sensor without any
processing or compression applied.
• RAW files offer maximum flexibility for editing and post-processing, allowing
photographers to adjust exposure, white balance, and other settings without loss of
quality.
• Each camera manufacturer has its own proprietary RAW format (e.g., CR2 for
Canon, NEF for Nikon), but there are also standardized RAW formats like Adobe's
DNG (Digital Negative).
vii. WebP:
• WebP is a modern image format developed by Google, designed to provide
superior compression and smaller file sizes compared to JPEG and PNG.
• It supports both lossy and lossless compression, making it versatile for different use
cases.
• WebP images can include transparency and animation, making them suitable for
web graphics and animations.
• While not as widely supported as other formats, WebP is gaining popularity for its
ability to deliver high-quality images with faster loading times.
viii. SVG (Scalable Vector Graphics):
• SVG is an XML-based vector image format that supports scalable graphics and
interactive elements.
• Unlike raster formats like JPEG and PNG, SVG images are resolution-independent
and can be scaled to any size without loss of quality.
• SVG supports transparency, gradients, and animation, making it suitable for web
graphics, icons, logos, and interactive charts.
• SVG files can be edited with text editors or vector graphics software like Adobe
Illustrator and Inkscape.
ix. PSD (Adobe Photoshop Document):
• PSD is the native file format used by Adobe Photoshop, preserving all layers,
masks, and editing history.
• It is commonly used for storing and exchanging editable image files between
Photoshop users.
• PSD files support advanced editing features such as adjustment layers, smart
objects, and non-destructive editing, making them ideal for complex design
projects.
• While primarily used for editing purposes, PSD files can be exported to other
formats like JPEG or PNG for final delivery.
x. HEIF (High-Efficiency Image Format):
• HEIF is a modern image format developed by the MPEG group, designed to offer
better compression and image quality compared to JPEG.

Tinsae D. @ 2024 Multimedia System and Development


• It supports both lossy and lossless compression, as well as advanced features like
image sequences, multiple images in a single file, and dynamic range
improvements.
• HEIF files typically have smaller file sizes than equivalent JPEG files, making them
suitable for storing and sharing high-quality images on mobile devices and the web.
• While not as widely supported as other formats, HEIF is gaining traction, especially
on newer mobile devices and operating systems.

Adobe Photoshop
(Practical Part)

Unit 4: Video Editing Basics


4.1. Video Editing
Adobe Premiere Pro is a powerful video editing software that provides professionals and
enthusiasts with the tools they need to create stunning and polished videos. With its intuitive
interface and comprehensive feature set, Premiere Pro offers a seamless editing experience that
allows users to bring their creative vision to life. From basic editing tasks like cutting and trimming
to advanced techniques such as color grading and motion graphics, Premiere Pro empowers users
to achieve professional-grade results with ease. Its timeline-based editing approach enables precise
control over every aspect of the video, while its integration with other Adobe Creative Cloud
applications like After Effects and Photoshop allows for seamless collaboration and workflow
efficiency.

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.

4.2. Understanding different Video files


Video file formats vary in terms of compression methods, quality, compatibility, and intended
use. Here's a detailed discussion of some common video file formats:

i. MP4 (MPEG-4 Part 14):


• MP4 is one of the most widely used video file formats, known for its versatility
and compatibility across various devices and platforms.
• It uses the MPEG-4 video compression standard, which provides a good balance
between file size and quality.

Tinsae D. @ 2024 Multimedia System and Development


• MP4 files can contain video, audio, subtitles, and metadata, making them suitable
for a wide range of multimedia applications, including streaming, broadcasting,
and online distribution.
• MP4 supports high-definition (HD) and ultra-high-definition (UHD) video
resolutions, as well as advanced features like chapters, menus, and 3D graphics.
ii. AVI (Audio Video Interleave):
• AVI is an older video file format developed by Microsoft, commonly used for
storing video and audio data on Windows-based systems.
• It uses various video and audio codecs to encode data, which can lead to
compatibility issues with some media players and devices.
• AVI files support high-quality video playback and editing, making them popular
among filmmakers and video editors.
• Despite its widespread use, AVI has limitations in terms of file size and
compression efficiency compared to newer formats like MP4.
iii. MOV (QuickTime Movie):
• MOV is a multimedia container format developed by Apple, commonly
associated with the QuickTime multimedia framework.
• It supports multiple tracks for video, audio, subtitles, and other media elements,
making it suitable for complex multimedia projects.
• MOV files can use various video and audio codecs, including Apple's proprietary
codecs like ProRes and Animation.
• MOV is widely used in professional video editing and post-production
workflows, as well as for distributing high-quality videos on macOS and iOS
devices.
iv. WMV (Windows Media Video):
• WMV is a video file format developed by Microsoft, optimized for streaming and
playback on Windows-based devices.
• It uses Microsoft's proprietary codecs like Windows Media Video 9 to compress
video data, resulting in relatively small file sizes.
• WMV files are commonly used for web streaming, video conferencing, and
digital signage applications.
• While WMV offers good compression efficiency and playback performance on
Windows platforms, it may have limited compatibility with non-Microsoft
devices and software.
v. FLV (Flash Video):
• FLV is a video file format used for delivering video content over the internet
using Adobe Flash Player.
• It uses the H.264 video codec for compression, which provides high-quality video
playback with relatively small file sizes.
• FLV files support streaming and progressive download methods, making them
suitable for online video platforms, social media, and web-based applications.
• Despite its popularity in the past, FLV has been largely replaced by newer formats
like MP4 and WebM due to the decline of Adobe Flash Player and the rise of
HTML5 video standards.
vi. WebM:
Tinsae D. @ 2024 Multimedia System and Development
• WebM is an open and royalty-free video file format developed by Google,
designed for web streaming and online distribution.
• It uses the VP8 or VP9 video codec for compression, offering high-quality video
playback with efficient compression.
• WebM files are supported by most modern web browsers and platforms, making
them ideal for delivering video content on the web without the need for plugins or
proprietary codecs.
• WebM is commonly used for web video streaming, HTML5 video players, and
web-based applications that prioritize open standards and interoperability.
vii. MKV (Matroska Video):
• MKV is a versatile and open-source multimedia container format known for its
ability to store multiple audio, video, and subtitle tracks in a single file.
• It supports a wide range of video and audio codecs, making it suitable for high-
quality video playback and distribution.
• MKV files are commonly used for storing digital copies of movies, TV shows,
and other multimedia content, especially in the enthusiast and piracy
communities.
• Despite its popularity, MKV files may not be supported by all media players and
devices, requiring users to install additional codecs or software for playback.
viii. MPG/MPEG (Moving Picture Experts Group):
• MPG/MPEG is a family of video file formats developed by the Moving Picture
Experts Group, known for their high compression efficiency and compatibility.
• MPEG-1 and MPEG-2 are older formats commonly used for storing video content
on DVDs, VCDs, and early digital television broadcasts.
• MPEG-4 is a newer format that includes advanced features like support for high-
definition video, streaming media, and digital rights management (DRM).
• While MPG/MPEG files offer good compression and compatibility, they may not
support advanced features like interactivity, subtitles, or multiple audio tracks
found in newer formats.
ix. DivX/Xvid:
• DivX and Xvid are popular video codecs based on the MPEG-4 compression
standard, known for their ability to achieve high compression ratios without
significant loss of quality.
• DivX and Xvid files are commonly used for compressing and distributing movies,
TV shows, and other video content over the internet.
• While DivX and Xvid offer excellent compression efficiency, they may require
users to install additional codecs or software for playback, especially on non-
Windows platforms.
x. OGG (Ogg Video):
• OGG is a multimedia container format developed by the Xiph.Org Foundation,
known for its open and royalty-free nature.
• OGG files can contain video, audio, and metadata, making them suitable for
storing and streaming multimedia content over the internet.
• The Theora video codec is commonly used with OGG containers, offering good
compression efficiency and quality for web-based video playback.
Tinsae D. @ 2024 Multimedia System and Development
• OGG files are supported by most modern web browsers and media players,
making them ideal for web-based video distribution and streaming.
xi. H.265/HEVC (High-Efficiency Video Coding):
• H.265/HEVC is a video compression standard developed by the Joint
Collaborative Team on Video Coding (JCT-VC), known for its ability to achieve
higher compression efficiency than previous standards like H.264.
• It offers significant improvements in video quality and compression efficiency,
making it ideal for delivering high-definition and ultra-high-definition video
content over the internet.
• H.265/HEVC files are commonly used for streaming, broadcasting, and
distributing video content on platforms that support the standard, including
streaming services like Netflix and YouTube.
• While H.265/HEVC offers superior compression efficiency, it may require more
computational resources for encoding and decoding, limiting its compatibility
with older hardware and software.

Basic steps for editing videos using Adobe Premium Pro


1. Importing Footage:
• Open Adobe Premiere Pro and create a new project.
• Go to the "File" menu and select "Import" to import your video footage and any
additional media assets (such as audio files or images) into your project.
2. Organizing Clips:
• In the "Project" panel, organize your imported clips into bins or folders for easy
access.
• Drag and drop clips from the "Project" panel into the "Timeline" panel to begin
editing.
3. Editing Clips:
• Use the "Selection Tool" (shortcut: V) to select and move clips on the timeline.
• Trim clips by dragging the edges of the clip in the timeline or by using keyboard
shortcuts (e.g., "C" for the razor tool to cut clips).
• Use the "Ripple Edit Tool" (shortcut: B) to trim clips while automatically
adjusting the rest of the timeline.
4. Adding Transitions:
• Go to the "Effects" panel and search for transitions like "Dissolve" or
"Crossfade."
• Drag the desired transition between two clips on the timeline to apply it.
5. Applying Effects:
• Select a clip on the timeline and go to the "Effects Controls" panel.
• Browse effects categories like "Color Correction" or "Video Effects" and drag
desired effects onto the clip to apply them.
• Adjust effect parameters in the "Effects Controls" panel to customize the effect.
6. Adding Titles and Graphics:

Tinsae D. @ 2024 Multimedia System and Development


• Go to the "Graphics" workspace or select "Graphics" from the "Window" menu to
open the "Essential Graphics" panel.
• Browse premade title templates or create custom titles and graphics using the
tools in the "Essential Graphics" panel.
• Drag titles or graphics from the "Essential Graphics" panel onto the timeline
above the desired clip.
7. Audio Editing:
• Import audio files into your project and drag them onto the timeline.
• Use the "Razor Tool" (shortcut: C) to cut and trim audio clips.
• Adjust audio levels using the "Audio Track Mixer" panel or by dragging the audio
levels in the timeline.
8. Color Correction and Grading:
• Go to the "Color" workspace or select "Color" from the "Window" menu to open
the "Lumetri Color" panel.
• Use the controls in the "Lumetri Color" panel to adjust exposure, contrast, color
temperature, and other color settings.
• Apply presets or create custom looks using adjustment layers and creative LUTs
(Look-Up Tables).
9. Exporting Your Project:
• Once you're satisfied with your edits, go to the "File" menu and select "Export" >
"Media" to open the Export Settings dialog.
• Choose your desired export settings, including format, codec, resolution, and
bitrate.
• Click "Export" to render your video and save it to your desired location.
10. Saving Your Project:
• Remember to save your project regularly by going to the "File" menu and
selecting "Save" or "Save As."
• Adobe Premiere Pro automatically creates backup project files (with the .prproj
extension) in case of unexpected crashes or errors.

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.

Adobe Premium Pro (Practical session)

Tinsae D. @ 2024 Multimedia System and Development


Summary Questions

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?

Tinsae D. @ 2024 Multimedia System and Development


References
• Kogent Learning Solutions Inc, Web Technologies : HTML, JAVASCRIPT, PHP,
JAVA, JSP, XML and AJAX, Blackbook, Dreamtech Press, Second Edition, ISBN:
9788177228496.
• Mesay Daniel (2023). Fundamentals of database. Technical and Vocational Training
Institute (TVTI), KOICA developed Text Book.
• Misikir Solomon (2024). Web designe and development I. FDRE Technical and
Vocational Training Institute. KOICA developed Text Book.
• OpenAI. (n.d.). ChatGPT: Conversational AI Model. Retrieved [Month, Day, Year], from
https://openai.com/chatgpt
• RamezElmasri and Shamkant B, Navathe (2022): Fundamentals of database system, 3rd
edition, Pearson Education.
• William Sullivan (2017): SQL Programming & Database Management For Absolute
Beginners SQL Server, Structured Query Language Fundamentals: "Learn - By Doing"
Approach And Master SQL, CreateSpace Independent Publishing.

You might also like