0% found this document useful (0 votes)
41 views350 pages

IT School - Manuali

This training manual, supported by the UK Government’s Conflict, Stability and Security Fund, covers web development topics including HTML, CSS, JavaScript, MySQL, and PHP. It provides a comprehensive guide with detailed sections on each technology, including syntax, elements, and practical exercises. The manual is structured into four parts, each focusing on a specific technology, and is designed to enhance local capacity in web development skills.

Uploaded by

64khqqn8js
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)
41 views350 pages

IT School - Manuali

This training manual, supported by the UK Government’s Conflict, Stability and Security Fund, covers web development topics including HTML, CSS, JavaScript, MySQL, and PHP. It provides a comprehensive guide with detailed sections on each technology, including syntax, elements, and practical exercises. The manual is structured into four parts, each focusing on a specific technology, and is designed to enhance local capacity in web development skills.

Uploaded by

64khqqn8js
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/ 350

This manual is supported by the UK Government’s Conflict, Stability and Security Fund through the Project “Amplifying Loca

TRAINING MANUAL
for
HTML, CSS, JS, MySQL, PHP.

October 2021
Table of Contents

Part I - HTML ............................................................................................................................................... 18


Introduction ............................................................................................................................................ 18
History – where did it come from ....................................................................................................... 18
Editors ................................................................................................................................................. 19
HTML Elements ................................................................................................................................... 19
Nested HTML Elements ....................................................................................................................... 19
Empty HTML Elements ........................................................................................................................ 20
HTML is Not Case Sensitive ................................................................................................................. 20
HTML Attributes .................................................................................................................................. 20
HTML Tables............................................................................................................................................ 22
Table Cells ........................................................................................................................................... 22
Table Rows .......................................................................................................................................... 23
Table Headers ..................................................................................................................................... 23
Exercises:............................................................................................................................................. 24
HTML forms............................................................................................................................................. 24
The <form> Element .......................................................................................................................... 25
The <input> Element ........................................................................................................................ 26
Text Fields ........................................................................................................................................... 26
The <label> Element....................................................................................................................... 26
Radio Buttons ...................................................................................................................................... 27
Checkboxes ......................................................................................................................................... 27
The submit Button .............................................................................................................................. 28
The Name Attribute for <input> ...................................................................................................... 28
Exercises:............................................................................................................................................. 28
HTML form Attribute.............................................................................................................................. 29
The action Attribute ......................................................................................................................... 29
The target Attribute ............................................................................................................................ 29

Page 2 of 349
The method Attribute ......................................................................................................................... 30
The autocomplete Attribute............................................................................................................ 30
The novalidate Attribute ..................................................................................................................... 31
HTML <form> Elements .......................................................................................................................... 31
The HTML <form> Elements ............................................................................................................... 31
The <input> Element ........................................................................................................................... 31
The <label> Element ........................................................................................................................... 31
The <select> Element .......................................................................................................................... 32
Visible Values ...................................................................................................................................... 32
Allow Multiple Selections.................................................................................................................... 33
The <textarea> Element .................................................................................................................. 33
The <button> Element ...................................................................................................................... 34
The <fieldset> and <legend> Elements ....................................................................................... 34
The <datalist> Element .................................................................................................................. 35
Exercises:............................................................................................................................................. 35
HTML input Type .................................................................................................................................. 36
HTML input Types ............................................................................................................................. 36
Input Type "text" ............................................................................................................................. 37
Input Type "password" .................................................................................................................... 37
Input Type "submit" ......................................................................................................................... 37
Input Type "reset" ........................................................................................................................... 39
Input Type Radio ................................................................................................................................. 40
Input Type "checkbox" .................................................................................................................... 40
Input Type "button" ......................................................................................................................... 40
Input Type "color" ........................................................................................................................... 41
Input Type "date" ............................................................................................................................. 41
Input Type "datetime-local" ....................................................................................................... 42
Input Type "email" ........................................................................................................................... 42
Input Type "file" ............................................................................................................................. 43
Input Type "hidden" ......................................................................................................................... 43
Input Type "number" ......................................................................................................................... 44
Input Restrictions ................................................................................................................................ 44
Input Type "range" ........................................................................................................................... 45

Page 3 of 349
Input Type "search" ......................................................................................................................... 45
Input Type "tel" ............................................................................................................................... 45
Input Type "time" ............................................................................................................................. 45
HTML Input Attributes ............................................................................................................................ 46
The value Attribute ........................................................................................................................... 46
The readonly Attribute .................................................................................................................... 46
The disabled Attribute .................................................................................................................... 46
The size Attribute ............................................................................................................................. 46
The maxlength Attribute .................................................................................................................. 47
The min and max Attributes ............................................................................................................... 47
The multiple Attribute .................................................................................................................... 48
The pattern Attribute....................................................................................................................... 48
The placeholder Attribute .............................................................................................................. 48
The required Attribute .................................................................................................................... 49
The step Attribute ............................................................................................................................. 49
The height and width Attributes .................................................................................................... 50
The list Attribute ............................................................................................................................. 50
The autocomplete Attribute............................................................................................................ 50
Exercises:............................................................................................................................................. 51
Part II - CSS .................................................................................................................................................. 52
Introduction ............................................................................................................................................ 52
What is CSS? ........................................................................................................................................ 52
Why Use CSS? ..................................................................................................................................... 52
CSS Syntax ............................................................................................................................................... 53
CSS Selectors ........................................................................................................................................... 53
The CSS element Selector ................................................................................................................. 54
The CSS id Selector ............................................................................................................................ 54
The CSS class Selector ...................................................................................................................... 54
The CSS Universal Selector.................................................................................................................. 55
The CSS Grouping Selector.................................................................................................................. 55
All CSS Simple Selectors ...................................................................................................................... 56
How To Add CSS ...................................................................................................................................... 56
Three Ways to Insert CSS .................................................................................................................... 56

Page 4 of 349
External CSS ........................................................................................................................................ 56
Internal CSS ......................................................................................................................................... 57
Inline CSS ............................................................................................................................................. 58
Multiple Style Sheets .......................................................................................................................... 58
Cascading Order .................................................................................................................................. 59
CSS Colors................................................................................................................................................ 60
CSS Color Names ................................................................................................................................. 60
CSS Background Color ......................................................................................................................... 60
CSS Text Color ..................................................................................................................................... 61
CSS Border Color ................................................................................................................................. 61
CSS Backgrounds ................................................................................................................................. 62
CSS background-color ......................................................................................................................... 62
CSSBorders .............................................................................................................................................. 62
CSS Border Style .................................................................................................................................. 62
CSS Margins............................................................................................................................................. 63
margin - Individual Sides ................................................................................................................... 64
Margin - Shorthand Property .............................................................................................................. 64
The auto Value ................................................................................................................................... 65
The inherit Value ............................................................................................................................ 66
CSS padding .......................................................................................................................................... 66
padding - Individual Sides ................................................................................................................. 67
padding - Shorthand Property .......................................................................................................... 67
CSS Height and Width ............................................................................................................................. 68
CSS Setting height and width.......................................................................................................... 68
CSS height and width Values .......................................................................................................... 68
CSS height and width Examples...................................................................................................... 69
Setting max-width ............................................................................................................................ 69
Padding and Element width .............................................................................................................. 71
CSS Box Model ........................................................................................................................................ 72
The CSS Box Model ............................................................................................................................. 72
Width and Height of an Element ........................................................................................................ 73
What is Responsive Web Design? ....................................................................................................... 74
Designing For The Best Experience For All Users ................................................................................ 74

Page 5 of 349
What is The Viewport?........................................................................................................................ 74
Setting The Viewport .......................................................................................................................... 75
Size Content to The Viewport ............................................................................................................. 75
What is a Grid-View?........................................................................................................................... 76
Building a Responsive Grid-View ........................................................................................................ 77
What is a Media Query? ......................................................................................................................... 82
Add a Breakpoint ................................................................................................................................ 82
Always Design for Mobile First ........................................................................................................... 83
Another Breakpoint ............................................................................................................................ 87
Typical Device Breakpoints ................................................................................................................. 93
Orientation: Portrait / Landscape ....................................................................................................... 95
Hide Elements With Media Queries.................................................................................................... 96
Change Font Size With Media Queries ............................................................................................... 97
CSS Transitions ........................................................................................................................................ 97
How to Use CSS Transitions? .............................................................................................................. 97
Change Several Property Values ......................................................................................................... 99
Specify the Speed Curve of the Transition ........................................................................................ 100
Delay the Transition Effect ................................................................................................................ 101
Transition + Transformation ............................................................................................................. 101
Bootstrap 4............................................................................................................................................ 103
What is Bootstrap? ........................................................................................................................... 103
What is Responsive Web Design? ..................................................................................................... 103
Bootstrap 3 vs. Bootstrap 4 .................................................................................................................. 103
Why Use Bootstrap? ......................................................................................................................... 104
Where to Get Bootstrap 4? ............................................................................................................... 104
Bootstrap 4 CDN................................................................................................................................ 104
Downloading Bootstrap 4 ................................................................................................................. 105
Create First Web Page With Bootstrap 4 .......................................................................................... 105
Two Basic Bootstrap 4 Pages ............................................................................................................ 106
Bootstrap 4 Grid System ....................................................................................................................... 108
Grid Classes ....................................................................................................................................... 108
Basic Structure of a Bootstrap 4 Grid................................................................................................ 109
Three Equal Columns ........................................................................................................................ 109

Page 6 of 349
Responsive Columns ......................................................................................................................... 110
Two Unequal Responsive Columns ................................................................................................... 110
Classes, tables, buttons and other .................................................................................................... 111
Part III - JavaScript..................................................................................................................................... 112
JavaScript Can Change HTML Content .............................................................................................. 112
JavaScript Can Change HTML Styles (CSS) ........................................................................................ 112
JavaScript Can Hide HTML Elements................................................................................................. 112
JavaScript Can Show HTML Elements ............................................................................................... 113
JavaScript Variables .............................................................................................................................. 113
Variables............................................................................................................................................ 113
Much Like Algebra............................................................................................................................. 114
JavaScript Identifiers ......................................................................................................................... 115
The Assignment Operator ................................................................................................................. 116
JavaScript Data Types........................................................................................................................ 116
Declaring (Creating) JavaScript Variables ......................................................................................... 117
One Statement, Many Variables ....................................................................................................... 118
Value = undefined ............................................................................................................................. 118
Re-Declaring JavaScript Variables ..................................................................................................... 119
JavaScript Arithmetic ........................................................................................................................ 119
JavaScript Strings .................................................................................................................................. 121
String Length ..................................................................................................................................... 121
Escape Character............................................................................................................................... 121
Breaking Long Code Lines ................................................................................................................. 122
Strings Can be Objects ...................................................................................................................... 123
JavaScript Operators ............................................................................................................................. 125
JavaScript Arithmetic Operators ....................................................................................................... 125
JavaScript Assignment Operators ..................................................................................................... 126
JavaScript String Operators ............................................................................................................... 126
Adding Strings and Numbers ............................................................................................................ 127
JavaScript Comparison Operators..................................................................................................... 127
JavaScript Logical Operators ............................................................................................................. 128
JavaScript Type Operators ................................................................................................................ 129
JavaScript Bitwise Operators ............................................................................................................ 129

Page 7 of 349
JavaScript Arrays ................................................................................................................................... 131
What is an Array? .............................................................................................................................. 131
Creating an Array .............................................................................................................................. 132
Using the JavaScript Keyword new ................................................................................................... 133
Accessing Array Elements ................................................................................................................. 133
Changing an Array Element............................................................................................................... 134
Access the Full Array ......................................................................................................................... 134
Arrays are Objects ............................................................................................................................. 134
Array Elements Can Be Objects......................................................................................................... 134
Array Properties and Methods.......................................................................................................... 135
The length Property .......................................................................................................................... 135
Accessing the First Array Element..................................................................................................... 135
Accessing the Last Array Element ..................................................................................................... 135
Looping Array Elements .................................................................................................................... 135
Adding Array Elements ..................................................................................................................... 136
Associative Arrays ............................................................................................................................. 137
The Difference Between Arrays and Objects .................................................................................... 137
When to Use Arrays. When to use Objects. ..................................................................................... 137
JavaScript new Array() ...................................................................................................................... 138
How to Recognize an Array ............................................................................................................... 138
JavaScript Functions .............................................................................................................................. 140
JavaScript Function Syntax ................................................................................................................ 141
Function Invocation .......................................................................................................................... 141
Function Return ................................................................................................................................ 141
Why Functions?................................................................................................................................. 142
The () Operator Invokes the Function ............................................................................................... 143
Functions Used as Variable Values ................................................................................................... 144
Local Variables .................................................................................................................................. 145
JavaScript Conditions ............................................................................................................................ 147
Conditional Statements .................................................................................................................... 147
The if Statement................................................................................................................................ 147
The else Statement ........................................................................................................................... 148
The else if Statement ........................................................................................................................ 149

Page 8 of 349
JavaScript Switch Statement ................................................................................................................. 150
The JavaScript Switch Statement ...................................................................................................... 151
The break Keyword ........................................................................................................................... 152
The default Keyword ......................................................................................................................... 153
Common Code Blocks ....................................................................................................................... 155
Switching Details ............................................................................................................................... 156
JavaScript For Loop ............................................................................................................................... 156
JavaScript Loops ................................................................................................................................ 156
Different Kinds of Loops.................................................................................................................... 157
The For Loop ..................................................................................................................................... 158
Loop Scope ........................................................................................................................................ 160
JavaScript While Loop ....................................................................................................................... 162
The While Loop ................................................................................................................................. 162
The Do While Loop ............................................................................................................................ 163
Comparing For and While ................................................................................................................. 164
JavaScript Objects ................................................................................................................................. 166
JavaScript Objects ............................................................................................................................. 167
Object Definition ............................................................................................................................... 167
Object Properties .............................................................................................................................. 169
Accessing Object Properties.............................................................................................................. 169
Object Methods ................................................................................................................................ 172
The this Keyword .............................................................................................................................. 172
Accessing Object Methods ................................................................................................................ 173
Do Not Declare Strings, Numbers, and Booleans as Objects!........................................................... 175
JavaScript HTML DOM .......................................................................................................................... 175
The HTML DOM (Document Object Model) ..................................................................................... 176
What is the DOM?............................................................................................................................. 176
JavaScript - HTML DOM Methods ..................................................................................................... 177
The DOM Programming Interface ..................................................................................................... 177
The getElementById Method ............................................................................................................ 178
The innerHTML Property................................................................................................................... 178
The HTML DOM Document Object ................................................................................................... 178
Finding HTML Elements .................................................................................................................... 178

Page 9 of 349
Changing HTML Elements ................................................................................................................. 179
Adding and Deleting Elements .......................................................................................................... 179
Adding Events Handlers .................................................................................................................... 180
Finding HTML Objects ....................................................................................................................... 180
JavaScript HTML DOM Elements....................................................................................................... 182
Finding HTML Elements .................................................................................................................... 182
Finding HTML Element by Id ............................................................................................................. 183
Finding HTML Elements by Tag Name .............................................................................................. 184
Finding HTML Elements by Class Name ............................................................................................ 185
Finding HTML Elements by CSS Selectors ......................................................................................... 186
Finding HTML Elements by HTML Object Collections ....................................................................... 187
JavaScript HTML DOM - Changing HTML .............................................................................................. 188
Changing HTML Content ................................................................................................................... 188
Changing the Value of an Attribute .................................................................................................. 189
Dynamic HTML content .................................................................................................................... 190
document.write() .............................................................................................................................. 190
JavaScript Forms ................................................................................................................................... 191
JavaScript Form Validation................................................................................................................ 191
JavaScript Can Validate Numeric Input ............................................................................................. 192
Automatic HTML Form Validation .................................................................................................... 194
Data Validation.................................................................................................................................. 194
HTML Constraint Validation .............................................................................................................. 195
Constraint Validation HTML Input Attributes ................................................................................... 195
Constraint Validation CSS Pseudo Selectors ..................................................................................... 195
Part IV - Introduction to MySQL................................................................................................................ 197
What is MySQL? .................................................................................................................................... 197
Who Uses MySQL? ............................................................................................................................ 197
Show Data On Your Web Site............................................................................................................ 197
What is RDBMS? ............................................................................................................................... 197
What is a Database Table? ................................................................................................................ 198
What is a Relational Database? ........................................................................................................ 198
What is SQL? ..................................................................................................................................... 199
How to Use SQL................................................................................................................................. 199

Page 10 of 349
Semicolon after SQL Statements?..................................................................................................... 200
MySQL Data Types ................................................................................................................................ 200
String Data Types .............................................................................................................................. 201
Numeric Data Types .......................................................................................................................... 202
Date and Time Data Types ................................................................................................................ 203
MySQL Database ................................................................................................................................... 203
The MySQL CREATE DATABASE Statement ....................................................................................... 204
CREATE DATABASE Example ............................................................................................................. 204
The MySQL DROP DATABASE Statement .............................................................................................. 204
DROP DATABASE Example ................................................................................................................ 204
The MySQL CREATE TABLE Statement .................................................................................................. 204
MySQL CREATE TABLE Example ........................................................................................................ 205
Create Table Using Another Table .................................................................................................... 205
The MySQL DROP TABLE Statement ..................................................................................................... 206
Syntax ................................................................................................................................................ 206
MySQL DROP TABLE Example ........................................................................................................... 206
MySQL TRUNCATE TABLE...................................................................................................................... 206
MySQL ALTER TABLE Statement ........................................................................................................... 207
ALTER TABLE - ADD Column .............................................................................................................. 207
ALTER TABLE - DROP COLUMN ......................................................................................................... 207
ALTER TABLE - MODIFY COLUMN ..................................................................................................... 207
MySQL ALTER TABLE Example........................................................................................................... 208
Change Data Type Example............................................................................................................... 208
DROP COLUMN Example................................................................................................................... 209
MySQL Constraints ................................................................................................................................ 209
Create Constraints ............................................................................................................................ 209
MySQL Constraints ............................................................................................................................ 210
MySQL Statements................................................................................................................................ 210
The MySQL SELECT Statement .......................................................................................................... 210
SELECT Syntax ................................................................................................................................... 210
The MySQL SELECT DISTINCT Statement .......................................................................................... 210
SELECT DISTINCT Syntax.................................................................................................................... 211
The MySQL WHERE Clause ................................................................................................................ 211

Page 11 of 349
WHERE Syntax ................................................................................................................................... 211
Operators in The WHERE Clause ....................................................................................................... 211
The MySQL ORDER BY Keyword ........................................................................................................ 212
ORDER BY Syntax .............................................................................................................................. 212
ORDER BY Several Columns Example 2 ............................................................................................. 212
The MySQL INSERT INTO Statement ................................................................................................. 212
INSERT INTO Syntax .......................................................................................................................... 212
What is a NULL Value? ...................................................................................................................... 213
How to Test for NULL Values?........................................................................................................... 213
IS NULL Syntax................................................................................................................................... 213
IS NOT NULL Syntax........................................................................................................................... 213
The IS NULL Operator........................................................................................................................ 214
The IS NOT NULL Operator................................................................................................................ 214
The MySQL UPDATE Statement ........................................................................................................ 214
UPDATE Syntax.................................................................................................................................. 214
UPDATE Table ................................................................................................................................... 215
UPDATE Multiple Records ................................................................................................................. 215
The MySQL DELETE Statement ......................................................................................................... 217
SQL DELETE Example ......................................................................................................................... 217
Delete All Records ............................................................................................................................. 218
The MySQL LIMIT Clause ................................................................................................................... 218
Demo Database ................................................................................................................................. 218
MySQL LIMIT Examples ..................................................................................................................... 219
ADD a WHERE CLAUSE ...................................................................................................................... 219
The MySQL GROUP BY Statement ........................................................................................................ 219
GROUP BY Syntax .............................................................................................................................. 220
Demo Database ................................................................................................................................. 220
MySQL GROUP BY Examples ............................................................................................................. 220
MySQL Operators .................................................................................................................................. 221
The MySQL AND, OR and NOT Operators ......................................................................................... 221
Demo Database ................................................................................................................................. 223
SQL LIKE Examples ............................................................................................................................ 224
MySQL Wildcard Characters ................................................................................................................. 225

Page 12 of 349
Wildcard Characters in MySQL ......................................................................................................... 226
Demo Database ................................................................................................................................. 226
Using the % Wildcard ........................................................................................................................ 228
Using the _ Wildcard ......................................................................................................................... 228
The MySQL IN Operator ........................................................................................................................ 229
IN Syntax ........................................................................................................................................... 229
Demo Database ................................................................................................................................. 229
IN Operator Examples ....................................................................................................................... 230
The MySQL BETWEEN Operator ........................................................................................................... 231
BETWEEN Syntax ............................................................................................................................... 231
Demo Database ................................................................................................................................. 231
BETWEEN Example ............................................................................................................................ 231
NOT BETWEEN Example .................................................................................................................... 232
BETWEEN with IN Example ............................................................................................................... 232
BETWEEN Text Values Example ........................................................................................................ 232
NOT BETWEEN Text Values Example ................................................................................................ 233
Sample Table ..................................................................................................................................... 233
BETWEEN Dates Example.................................................................................................................. 233
MySQL Arithmetic Operators ................................................................................................................ 234
MySQL Bitwise Operators ..................................................................................................................... 234
MySQL Comparison Operators ............................................................................................................. 234
MySQL Compound Operators ............................................................................................................... 235
MySQL Logical Operators ...................................................................................................................... 235
MySQL Joins .......................................................................................................................................... 236
MySQL Joining Tables........................................................................................................................ 236
Supported Types of Joins in MySQL .................................................................................................. 237
MySQL INNER JOIN Keyword ................................................................................................................ 237
INNER JOIN Syntax ............................................................................................................................ 237
Demo Database ................................................................................................................................. 238
MySQL INNER JOIN Example ............................................................................................................. 238
JOIN Three Tables ............................................................................................................................. 239
MySQL LEFT JOIN Keyword ................................................................................................................... 239
LEFT JOIN Syntax ............................................................................................................................... 239

Page 13 of 349
Demo Database ................................................................................................................................. 239
MySQL LEFT JOIN Example ................................................................................................................ 240
MySQL RIGHT JOIN Keyword ................................................................................................................ 240
RIGHT JOIN Syntax ............................................................................................................................ 241
Demo Database ................................................................................................................................. 241
MySQL RIGHT JOIN Example ............................................................................................................. 241
SQL CROSS JOIN Keyword ..................................................................................................................... 242
CROSS JOIN Syntax ............................................................................................................................ 242
Demo Database ................................................................................................................................. 242
MySQL CROSS JOIN Example............................................................................................................. 243
MySQL Functions .................................................................................................................................. 243
MySQL Stored Procedures .................................................................................................................... 249
MySQL stored procedures introduction ........................................................................................... 249
MySQL stored procedures advantages ............................................................................................. 250
MySQL stored procedures disadvantages ........................................................................................ 251
MySQL Delimiter ................................................................................................................................... 251
Using MySQL DELIMITER for stored procedures .............................................................................. 252
MySQL CREATE PROCEDURE statement ............................................................................................... 252
Executing a stored procedure ........................................................................................................... 253
MySQL DROP PROCEDURE statement .................................................................................................. 253
MySQL DROP PROCEDURE examples ................................................................................................ 254
MySQL stored procedure parameters .................................................................................................. 255
IN parameters ................................................................................................................................... 255
OUT parameters ................................................................................................................................ 255
INOUT parameters ............................................................................................................................ 255
Defining a parameter ........................................................................................................................ 255
MySQL stored procedure parameter examples ................................................................................ 255
Declaring variables ................................................................................................................................ 258
Assigning variables ............................................................................................................................ 258
Variable scopes ................................................................................................................................. 259
Putting it all together ........................................................................................................................ 259
MySQL simple IF-THEN statement ........................................................................................................ 260
MySQL IF-THEN-ELSE statement ........................................................................................................... 263

Page 14 of 349
MySQL IF-THEN-ELSEIF-ELSE statement ............................................................................................... 263
CASE statement..................................................................................................................................... 265
Simple CASE statement example ...................................................................................................... 265
HomeWorks .......................................................................................................................................... 267
MySQL Create Table [20 exercises with solution]............................................................................. 267
MySQL Insert Rows into the Table [14 exercises with solution] ....................................................... 272
MySQL Update Table [ 9 exercises with solution] ............................................................................ 275
MySQL Alter Table [15 exercises with solution] ............................................................................... 276
Basic SELECT statement [19 exercises with solution] ....................................................................... 278
MySQL Restricting and Sorting data: [11 exercises with solution] ................................................... 280
Aggregate Functions and Group by [14 exercises with solution] ..................................................... 281
MySQL Subquery [22 exercises with solution].................................................................................. 283
MySQL Joins [13 exercises with solution] ......................................................................................... 286
Date and Time functions [21 exercises with solution] ...................................................................... 288
References ................................................................................................................................................ 290
XAMPP................................................................................................................................................... 290
What is XAMPP?................................................................................................................................ 290
How to download and install? .......................................................................................................... 291
Managing XAMPP applications with XAMP manager ....................................................................... 291
Serving a site on Apache ................................................................................................................... 292
Hosting a database............................................................................................................................ 292
Part V - Introduction to PHP ..................................................................................................................... 294
PHP Case Sensitivity .............................................................................................................................. 294
PHP Comments ..................................................................................................................................... 295
PHP Variables ........................................................................................................................................ 296
PHP Data Types ..................................................................................................................................... 296
Operator and Expression ...................................................................................................................... 298
PHP Arithmetic Operators .................................................................................................................... 298
PHP Assignment Operators ................................................................................................................... 299
PHP Comparison Operators .................................................................................................................. 300
PHP Increment / Decrement Operators ............................................................................................... 302
PHP Logical Operators........................................................................................................................... 302
PHP Conditional Statements ................................................................................................................. 304

Page 15 of 349
PHP Conditional Statements ............................................................................................................. 305
PHP Switch Statement ...................................................................................................................... 305
PHP Loops ............................................................................................................................................. 307
PHP while Loop ................................................................................................................................. 307
PHP do while Loop ............................................................................................................................ 308
PHP for Loop ..................................................................................................................................... 309
PHP Break and Continue ................................................................................................................... 315
PHP Functions ....................................................................................................................................... 316
PHP Functions Argument .................................................................................................................. 317
PHP Arrays............................................................................................................................................. 319
PHP - The count() Function ............................................................................................................... 319
PHP Indexed Arrays ............................................................................................................................... 320
PHP Associative Arrays.......................................................................................................................... 320
PHP - Multidimensional Arrays ......................................................................................................... 321
PHP - Sort Functions For Arrays ............................................................................................................ 322
Sort Array in Ascending Order - sort() .................................................................................................. 322
Sort Array in Descending Order - rsort() ............................................................................................... 323
PHP - ADVANCED ...................................................................................................................................... 326
PHP Include Files ................................................................................................................................... 326
< ....................................................................................................................................................... 327
< ........................................................................................................................................................ 328
PHP File Handling .................................................................................................................................. 328
PHP - OOP ................................................................................................................................................. 329
PHP - What are Classes and Objects? ................................................................................................... 329
Define a Class .................................................................................................................................... 330
PHP OOP - Constructor ......................................................................................................................... 331
PHP OOP - Destructor ........................................................................................................................... 332
PHP OOP - Inheritance .......................................................................................................................... 333
PHP MySQL Database ........................................................................................................................... 336
What is MySQL? ................................................................................................................................ 336
PHP MySQL Database ........................................................................................................................... 337
Open a Connection to MySQL ........................................................................................................... 337
Create a MySQL Database Using MySQLi and PDO .......................................................................... 338

Page 16 of 349
PHP MySQL Create Table .................................................................................................................. 338
PHP MySQL Insert Data ..................................................................................................................... 340
PHP MySQL Get Last Inserted ID ....................................................................................................... 341
PHP MySQL Insert Multiple Records .................................................................................... 342
PHP MySQL Select Data ........................................................................................................................ 343
PHP MySQL Use The WHERE Clause ..................................................................................................... 344
PHP MySQL Use The ORDER BY Clause ................................................................................................. 345
PHP MySQL Delete Data ....................................................................................................................... 346
PHP MySQL Update Data ...................................................................................................................... 348
PHP MySQL Limit Data Selections ......................................................................................................... 349

Page 17 of 349
Part I - HTML

Introduction

History – where did it come from


As one can see from the W3C quote, HTML is defined as a markup language. A markup language is simply
a way of annotating a document in such a way as to make the annotations distinct from the text being
annotated. Markup languages such as HTML, Tex, XML, and XHTML allow users to control how text and
visual elements will be laid out and displayed. The term comes from the days of print, when editors would
write instructions on manuscript pages that might be revision instructions to the author or copy editor.
What is HTML?
 HTML stands for Hyper Text Markup Language
 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
 HTML elements label pieces of content such as "this is a heading", "this is a paragraph",
"this is a link", etc.

An example of a simple HTML document:


<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>

</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph</p>

</body>
</html>
Example 1

HTML is used by writing tags. What are tags actually? Tags are predefined words that are like keywords
which defines that how web browser will format and display the content.
So what are those tags used on the Example. In short words, are described as:
 The <!DOCTYPE html> declaration defines that this document is an HTML5 document.
 The <html> element is the root element of an HTML page.

Page 18 of 349
 The <head> element contains meta information about the HTML page.
 The <title> element specifies a title for the HTML page (which is shown in the browser's title bar
or in the page's tab)
 The <body> element defines the document's body, and is a container for all the visible contents,
such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
 The <h1> element defines a large heading
 The <p> element defines a paragraph

Editors
In HTML, it can be used a lot of different editors. It is more than enough to use any text editor, starting by
Notepad. Editors that can be used for writing HTML code are: Notepad++, Sublime Text, Atom, Visual
Studio Code. As an example, we talk about VS Code as a powerful tool for writing not just HTML code, but
any language code known these days.

HTML Elements
The HTML element is everything from the start tag to the end tag:
<tagname>Content goes here...</tagname>

Examples of some HTML elements:


<h1>My First Heading</h1>
<p>My first paragraph</p>

But, some HTML elements have no content (like the <br> element). These elements are called empty
elements. Empty elements do not have an end tag!

Nested HTML Elements


HTML elements can be nested (this means that elements can contain other elements).
All HTML documents consist of nested HTML elements.
The following example contains four HTML elements (<html>, <body>, <h1>, and <p>).
Refer to Example 1 to see nested HTML elements.
The <html> element is the root element and it defines the whole HTML document.
It has a start tag <html> and an end tag <html>.
Then, inside the <html> element there is a <body> element.
The <body> element defines the document's body.

Page 19 of 349
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>

It has a start tag </body> and an end tag </body>. Then, inside the </body> element there are two other
elements: <h1>and <p>.
Never Skip the End Tag. Some HTML elements will display correctly, even if you forget the end tag:
<html>
<body>
<p>This is a paragraph
<p>This is a paragraph

</body>
</html>
Example 2

However, never rely on this! Unexpected results and errors may occur if you forget the end tag!

Empty HTML Elements


HTML elements with no content are called empty elements.
The <br> tag defines a line break, and is an empty element without a closing tag, for example <br>
element is only for breaking into new line of the content.
<p>This is a <br> paragraph with a line break.</p>

HTML is Not Case Sensitive


HTML tags are not case sensitive: <P> means the same as <p>.
The HTML standard does not require lowercase tags, but W3C recommends lowercase in HTML, and
demands lowercase for stricter document types like XHTML.
For all HTML tag references please refer to the W3C.

HTML Attributes
HTML attributes provide additional information about HTML elements.
What HTML attributes offer:
 All HTML elements can have attributes
 Attributes provide additional information about elements

Page 20 of 349
 Attributes are always specified in the start tag
 Attributes usually come in name/value pairs like: name="value"

Some of the attributes most used are:


1. Href attribute
The <a> tag defines a hyperlink. The href attribute specifies the URL of the page the link goes to:
<a href="https://www.w3schools.com">Visit W3Schools</a>

2. The src Attribute


The <img> tag is used to embed an image in an HTML page. The src attribute specifies the path to the
image to be displayed:
<img src="img_example.jpg">

There are two ways to specify the URL in the src attribute:
 Absolute URL - Links to an external image that is hosted on another website. Example:
src="https://www.w3schools.com/images/img_girl.jpg" .
 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 relative to the current page.
Example: src="img_girl.jpg". If the URL begins with a slash, it will be relative to the domain.
Example: src="/images/img_girl.jpg".
But, it is almost always best to use relative URLs. They will not break if you change domain.
3. The width and height Attributes
The <img> tag should also contain the width and height attributes, which specifies the width and height
of the image (in pixels):
<img src="img_girl.jpg" width="500" height="600">

4. The style Attribute


The style attribute is used to add styles to an element, such as color, font, size, and more.
<p style="color:red;">This is a red paragraph.</p>

Of course, there are other attributes, but we will talk on next modules more about all attributes.
Exercise 1: What is an Id attribute?
Exercise 2: Write a simple HTML code which besides the main elements of the HTML like head and body,
also have four paragraphs filled with some text of your choice?

Page 21 of 349
HTML Tables

HTML tables allow web developers to arrange data into rows and columns.
Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Centro comercial Moctezuma Francisco Chang Mexico
Ernst Handel Roland Mendel Austria
Island Trading Helen Bennett UK
Laughing Bacchus Winecellars Yoshi Tannamuri Canada
Magazzini Alimentari Riuniti Giovanni Rovelli Italy

The source code of the table:


<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>

Table Cells
Each table cell is defined by a <td> and a </td> tag, where td stands for table data.
Everything between <td> and </td> are the content of the table cell.

Page 22 of 349
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>

Table Rows
Each table row starts with a <tr> and ends with a </tr> tag, where tr stands for table row.
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>

Table Headers
Sometimes you want your cells to be headers, in those cases use the <th>tag instead of the <td> tag:
<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

By default, the text in <th> elements are bold and centered, but you can change that with CSS.
Finally, the table tags are:
Tag Description

Page 23 of 349
</table> Defines a table
<th> Defines a header cell in a table
<tr> Defines a row in a table
<td> Defines a cell in a table
<caption> Defines a table caption
<colgroup> Specifies a group of one or more columns in a table for formatting
<col> Specifies column properties for each column within a <colgroup> element
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table

Exercises:
1. Add a table row with two table headers.
The two table headers should have the value "Name" and "Age".

<table>

<tr>
<td>Jill Smith</td>
<td>50</td>
</tr>
</table>

Solution:
<tr>
<td>Filan Fisteku</td>
<td>31</td>
</tr>

HTML forms

An HTML form is used to collect user input. The user input is most often sent to a server for processing.
For example, let’s see two labels, inputs of type text and a button, which we see almost everyday on the
applications:

Page 24 of 349
Figure 1.

The source code of Figure 1 is shown below


<!DOCTYPE html>
<html>
<body>

<h2>HTML Forms</h2>

<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="Filan"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Fisteku"><br><br>
<input type="submit" value="Submit">
</form>

<p>If you click the "Submit" button, the form-data will be sent to a page called
"/action_page.php".</p>

</body>
</html>

The <form> Element


The HTML <form> element is used to create an HTML form for user input:
<form>
.
form elements
.
</form>

The <form> element is a container for different types of input elements, such as: text fields, checkboxes,
radio buttons, submit buttons, etc.

Page 25 of 349
The <input> Element
The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on the type attribute.
Here are some examples:

Type Description
<input type="text"> Displays a single-line text input field
<input type="radio"> Displays a radio button (for selecting one of many choices)
<input type="checkbox"> Displays a checkbox (for selecting zero or more of many choices)
<input type="submit"> Displays a submit button (for submitting the form)
<input type="button"> Displays a clickable button

Text Fields
The <input type="text"> defines a single-line input field for text input.
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>

This HTML code gives the result same as in Figure 1.


Keep in mind that the form itself is not visible. Also note that the default width of an input field is 20
characters.

The <label> Element


Notice the use of the <label>element in the Example 1.
The <label> tag defines a label for many form elements.
The <label> element is useful for screen-reader users, because the screen-reader will read out
loud the label when the user focus on the input element.
The <label> element also help users who have difficulty clicking on very small regions (such as
radio buttons or checkboxes) - because when the user clicks the text within the <label> element,
it toggles the radio button/checkbox.
The for attribute of the <label> tag should be equal to the id attribute of the <input> element to bind
them together.

Page 26 of 349
Radio Buttons
The <input type="radio"> defines a radio button.
Radio buttons let a user select ONE of a limited number of choices.
<p>Choose your favorite Web language:</p>

<form>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
</form>

This is how the HTML code above will be displayed in a browser:


Choose your favorite Web language:

HTML
CSS
JavaScript

Checkboxes
The <input type="checkbox"> defines a checkbox.
Checkboxes let a user select ZERO or MORE options of a limited number of choices.
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>

This is how the HTML code above will be displayed in a browser:

Page 27 of 349
I have a bike
I have a car
I have a boat

The submit Button


The <input type="submit"> defines a button for submitting the form data to a form-handler.
The form-handler is typically a file on the server with a script for processing input data.
The form-handler is specified in the form's action attribute.
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="Filan"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Fisteku"><br><br>
<input type="submit" value="Submit">
</form>

The result of this HTML code is like in Figure 1

The Name Attribute for <input>


Notice that each input field must have a name attribute to be submitted.
If the name attribute is omitted, the value of the input field will not be sent at all.
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" value="John"><br><br>
<input type="submit" value="Submit">
</form>

Exercises:
1. In the form below, add an input field with the type "button" and the value "OK".
<form>
< >
</form>

Solution:

Page 28 of 349
<form>
<input type="button" value="OK">
</form>

2. In the form below, add two radio buttons, both with the name "fav_language".
<form>
< value="html"> HTML
< value="css"> CSS
</form>

Solution:
<form>
<input type="radio" name="fav_language" value="html"> HTML
<input type="radio" name="fav_language" value="css"> CSS
</form>

HTML form Attribute

This chapter describes the different attributes for the HTML<form> element.

The action Attribute


The action attribute defines the action to be performed when the form is submitted.
Usually, the form data is sent to a file on the server when the user clicks on the submit button.
In the example below, the form data is sent to a file called "action_page.php". This file contains a server-
side script that handles the form data:
<form action="/action_page.php">
<label for="fname">First name: </label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name: </label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>

Tip: If the action attribute is omitted, the action is set to the current page.

The target Attribute


The target attribute specifies where to display the response that is received after submitting the form.

Page 29 of 349
The target attribute can have one of the following values:
Value Description
_blank The response is displayed in a new window or tab
_self The response is displayed in the current window
_parent The response is displayed in the parent frame
_top The response is displayed in the full body of the window
framename The response is displayed in a named iframe

The default value is _self which means that the response will open in the current window.
<form action="/action_page.php" target="_blank

The method Attribute


The method attribute specifies the HTTP method to be used when submitting the form data.
The form-data can be sent as URL variables (with method="get") or as HTTP post transaction (with
method="post").
The default HTTP method when submitting form data is GET.
<form.action="/action_page.php".method="get">
<form.action="/action_page.php".method="post">

Notes on GET:
- Appends the form data to the URL, in name/value pairs
- NEVER use GET to send sensitive data! (the submitted form data is visible in the URL!)
- The length of a URL is limited (2048 characters)
- Useful for form submissions where a user wants to bookmark the result
- GET is good for non-secure data, like query strings in Google
Notes on POST:
- Appends the form data inside the body of the HTTP request (the submitted form data is not shown
in the URL)
- POST has no size limitations, and can be used to send large amounts of data.
- Form submissions with POST cannot be bookmarked

The autocomplete Attribute


The autocomplete attribute specifies whether a form should have autocomplete on or off.
When autocomplete is on, the browser automatically complete values based on values that the user has
entered before.
<form action="/action_page.php" autocomplete="on">

Page 30 of 349
The novalidate Attribute
The novalidate attribute is a boolean attribute.
When present, it specifies that the form-data (input) should not be validated when submitted.
<form action="/action_page.php" novalidate>

HTML <form> Elements

The HTML <form> Elements


The HTML <form> element can contain one or more of the following form elements:
<input>
<label>
<select>
<textarea>
<button>
<fieldset>
<legend>
<datalist>
<output>
<option>
<optgroup>

The <input> Element


One of the most used form element is the <input> element.
The <input> element can be displayed in several ways, depending on the type attribute.
<label for="fname">First name: </label>
<input type="text" id="fname" name="fname">

The <label> Element


The <label> element defines a label for several form elements.
- The <label> element is useful for screen-reader users, because the screen-reader will read out
loud the label when the user focus on the input element.
- The <label> element also help users who have difficulty clicking on very small regions (such as
radio buttons or checkboxes) - because when the user clicks the text within the <label> element,
it toggles the radio button/checkbox.

Page 31 of 349
The for attribute of the <label> tag should be equal to the id attribute of the <input> element to bind
them together.

The <select> Element


The <select> element defines a drop-down list:
<label for="cars">Choose a car:</label>
<select id="cars" name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

The <option> elements defines an option that can be selected.


By default, the first item in the drop-down list is selected.
To define a pre-selected option, add the selected attribute to the option:
<option value="fiat" selected>Fiat</option>

Visible Values
Use the size attribute to specify the number of visible values:

Page 32 of 349
<label for="cars">Choose a car:</label>
<select id="cars" name="cars" size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

Allow Multiple Selections


Use the multiple attribute to allow the user to select more than one value:
<label for="cars">Choose a car:</label>
<select id="cars" name="cars" size="4" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

The <textarea> Element


The <textarea> element defines a multi-line input field (a text area):
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>

The rows attribute specifies the visible number of lines in a text area.
The cols attribute specifies the visible width of a text area.
This is how the HTML code above will be displayed in a browser:

Page 33 of 349
You can also define the size of the text area by using CSS:
<textarea name="message" style="width:200px; height:600px;">
The cat was playing in the garden.
</textarea>

The <button> Element


The <button> element defines a clickable button:
<button type="button" onclick="alert('Hello World!')">Click Me!<button>

This is how the HTML code above will be displayed in a browser:

The <fieldset> and <legend> Elements


The <fieldset> element is used to group related data in a form.
The <legend> element defines a caption for the <fieldset> element.
<form action="/action_page.php">
<fieldset>
<legend>Personalia:</legend>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name: </label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>

This is how the HTML code above will be displayed in a browser:

Page 34 of 349
The <datalist> Element
The <datalist> element specifies a list of pre-defined options for an <input> element.
Users will see a drop-down list of the pre-defined options as they input data.
The list attribute of the <input> element, must refer to the id attribute of the <datalist> element.
<form action="/action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>

Exercises:
1. In the form below, add an empty drop down list with the name "cars".
<form action="/action_page.php">
< >
</ >
</form>

Solution:
<form action="/action_page.php">
<select name="cars">
</select>
</form>

2. In the form below, add a text area with the name "note".
<form action="/action_page.php">
< >
</ >
</form>

Solution:
<form action="/action_page.php">
<textarea name="note">
</textarea>
</form>

Page 35 of 349
HTML input Type

This chapter describes the different types for the HTML <input> element.

HTML input Types


Here are the different input types you can use in HTML:
<input type="button">
<input type="checkbox">
<input type="color">
<input type="date">
<input type="datetime-local">
<input type="email">
<input type="file">
<input type="hidden">
<input type="image">
<input type="month">
<input type="number">
<input type="password">
<input type="radio">
<input type="range">
<input type="reset">
<input type="search">
<input type="submit">
<input type="tel">
<input type="text">
<input type="time">
<input type="url">
<input type="week">

The default value of the type attribute is "text".

Page 36 of 349
Input Type "text"
The <input type="text"> defines a single-line text input field:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>

This is how the HTML code above will be displayed in a browser:

Input Type "password"


The <input type="password"> defines a password field:
<form>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd" name="pwd">
</form>

This is how the HTML code above will be displayed in a browser:

Input Type "submit"


The <input type="submit"> defines a button for submitting form data to a form-handler.

Page 37 of 349
The form-handler is typically a server page with a script for processing input data.
The form-handler is specified in the form's action attribute:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>

This is how the HTML code above will be displayed in a browser:

Page 38 of 349
If you omit the submit button's value attribute, the button will get a default text:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit">
</form>

Input Type "reset"


The <input type="reset"> defines a reset button that will reset all form values to their default values:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
<input type="reset">
</form>

This is how the HTML code above will be displayed in a browser:

If you change the input values and then click the "Reset" button, the form-data will be reset to the default
values.

Page 39 of 349
Input Type Radio
The <input type="radio"> defines a radio button.

Radio buttons let a user select ONLY ONE of a limited number of choices:
<p>Choose your favorite Web language:</p>

<form>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
</form>

This is how the HTML code above will be displayed in a browser:

HTML
CSS
JavaScript

Input Type "checkbox"


The <input type="checkbox"> defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.
<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>

This is how the HTML code above will be displayed in a browser:

I have a bike
I have a car
I have a boat

Input Type "button"


The <input type="button"> defines a button:

Page 40 of 349
<input type="button" onclick="alert('Hello World!')" value="Click Me!">

Input Type "color"


The <input type="color"> is used for input fields that should contain a color.

Depending on browser support, a color picker can show up in the input field.
<form>
<label for="favcolor">Select your favorite color:</label>
<input type="color" id="favcolor" name="favcolor">
</form>

Input Type "date"


The <input type="date"> is used for input fields that should contain a date.

Page 41 of 349
Depending on browser support, a date picker can show up in the input field.
<form>
<label for="birthday">Birthday:</label>
<input type="date" id="birthday" name="birthday">
</form>

You can also use the min and max attributes to add restrictions to dates:
<form>
<label for="datemax">Enter a date before 1980-01-01:</label>
<input type="date" id="datemax" name="datemax" max="1979-12-31"><br><br>
<label for="datemin">Enter a date after 2000-01-01:</label>
<input type="date" id="datemin" name="datemin" min="2000-01-02">
</form>

Input Type "datetime-local"


The <input type="datetime-local"> specifies a date and time input field, with no time zone.
Depending on browser support, a date picker can show up in the input field.
<form>
<label for="birthdaytime">Birthday (date and time):</label>
<input type="datetime-local" id="birthdaytime" name="birthdaytime">
</form>

Input Type "email"


The <input type="email"> is used for input fields that should contain an e-mail address.
Depending on browser support, the e-mail address can be automatically validated when submitted.

Page 42 of 349
Some smartphones recognize the email type, and add ".com" to the keyboard to match email input.
<form>
<label for="email">Enter your email:</label>
<input type="email" id="email" name="email">
</form>

Input Type "file"


The <input type="file"> defines a file-select field and a "Browse" button for file uploads.
<form>
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
</form>

Input Type "hidden"


The <input type="hidden"> defines a hidden input field (not visible to a user).
A hidden field let web developers include data that cannot be seen or modified by users when a form is
submitted.
A hidden field often stores what database record that needs to be updated when the form is submitted.
Note: While the value is not displayed to the user in the page's content, it is visible (and can be edited)
using any browser's developer tools or "View Source" functionality. Do not use hidden inputs as a form of
security!

Page 43 of 349
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<input type="hidden" id="custId" name="custId" value="3487">
<input type="submit" value="Submit">
</form>

Input Type "number"


The <input type="number"> defines a numeric input field.
You can also set restrictions on what numbers are accepted.
The following example displays a numeric input field, where you can enter a value from 1 to 5:
<form>
<label for="quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
</form>

Input Restrictions
Here is a list of some common input restrictions:
Attribute Description
checked Specifies that an input field should be pre-selected when the page loads (for
type="checkbox" or type="radio")
disabled Specifies that an input field should be disabled
max Specifies the maximum value for an input field
maxlength Specifies the maximum number of character for an input field
min Specifies the minimum value for an input field
pattern Specifies a regular expression to check the input value against
readonly Specifies that an input field is read only (cannot be changed)
required Specifies that an input field is required (must be filled out)
size Specifies the width (in characters) of an input field
step Specifies the legal number intervals for an input field
value Specifies the default value for an input field

The following example displays a numeric input field, where you can enter a value from 0 to 100, in steps
of 10. The default value is 30:
<form>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="0" max="100"
step="10" value="30">

Page 44 of 349
</form>

Input Type "range"


The <input type="range"> defines a control for entering a number whose exact value is not important
(like a slider control). Default range is 0 to 100. However, you can set restrictions on what numbers are
accepted with the min, max, and step attributes:
<form>
<label for="vol">Volume (between 0 and 50):</label>
<input type="range" id="vol" name="vol" min="0" max="50">
</form>

Input Type "search"


The <input type="search"> is used for search fields (a search field behaves like a regular text field).
<form>
<label for="gsearch">Search Google:</label>
<input type="search" id="gsearch" name="gsearch">
</form>

Input Type "tel"


The <input type="tel"> is used for input fields that should contain a telephone number.
<form>
<label for="phone">Enter your phone number:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{2}-[0-
9]{3}">
</form>

Input Type "time"


The <input type="time"> allows the user to select a time (no time zone).
Depending on browser support, a time picker can show up in the input field.
<form>
<label for="appt">Select a time:</label>
<input type="time" id="appt" name="appt">
</form>

Page 45 of 349
HTML Input Attributes

The value Attribute


The input value attribute specifies an initial value for an input field:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>

The readonly Attribute


The input readonly attribute specifies that an input field is read-only.
A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text
from it).
The value of a read-only input field will be sent when submitting the form!
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John" readonly><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>

The disabled Attribute


The input disabled attribute specifies that an input field should be disabled.
A disabled input field is unusable and un-clickable.
The value of a disabled input field will not be sent when submitting the form!
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John" disabled><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe">
</form>

The size Attribute


The input size attribute specifies the visible width, in characters, of an input field.

Page 46 of 349
The default value for size is 20.
Note: The size attribute works with the following input types: text, search, tel, url, email, and
password.
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" size="50"><br>
<label for="pin">PIN:</label><br>
<input type="text" id="pin" name="pin" size="4">
</form>

The maxlength Attribute


The input maxlength attribute specifies the maximum number of characters allowed in an input field.
Note: When a maxlength is set, the input field will not accept more than the specified number of
characters. However, this attribute does not provide any feedback. So, if you want to alert the user, you
must write JavaScript code.
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" size="50"><br>
<label for="pin">PIN:</label><br>
<input type="text" id="pin" name="pin" maxlength="4" size="4">
</form>

The min and max Attributes


The input min and max attributes specify the minimum and maximum values for an input field.
The min and max attributes work with the following input types: number, range, date, datetime-local,
month, time and week.

Page 47 of 349
Tip: Use the max and min attributes together to create a range of legal values.
<form>
<label for="datemax">Enter a date before 1980-01-01:</label>
<input type="date" id="datemax" name="datemax" max="1979-12-31"><br><br>

<label for="datemin">Enter a date after 2000-01-01:</label>


<input type="date" id="datemin" name="datemin" min="2000-01-02"><br><br>

<label for="quantity">Quantity (between 1 and 5):</label>


<input type="number" id="quantity" name="quantity" min="1" max="5">
</form>

The multiple Attribute


The input multiple attribute specifies that the user is allowed to enter more than one value in an input
field.
The multiple attribute works with the following input types: email, and file.
<form>
<label for="files">Select files:</label>
<input type="file" id="files" name="files" multiple>
</form>

The pattern Attribute


The input pattern attribute specifies a regular expression that the input field's value is checked against,
when the form is submitted.
The pattern attribute works with the following input types: text, date, search, url, tel, email, and
password.
<form>
<label for="country_code">Country code:</label>
<input type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}" title="Three letter country code">
</form>

The placeholder Attribute


The input placeholder attribute specifies a short hint that describes the expected value of an input field
(a sample value or a short description of the expected format).
The short hint is displayed in the input field before the user enters a value.

Page 48 of 349
The placeholder attribute works with the following input types: text, search, url, tel, email, and
password.
<form>
<label for="phone">Enter a phone number:</label>
<input type="tel" id="phone" name="phone"
placeholder="123-45-678"
pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}">
</form>

The required Attribute


The input required attribute specifies that an input field must be filled out before submitting the form.
The required attribute works with the following input types: text, search, url, tel, email, password,
date pickers, number, checkbox, radio, and file.
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</form>

The step Attribute


The input step attribute specifies the legal number intervals for an input field.
Example: if step="3", legal numbers could be -3, 0, 3, 6, etc.
Tip: This attribute can be used together with the max and min attributes to create a range of legal values.
The step attribute works with the following input types: number, range, date, datetime-local, month,
time and week.
<form>
<label for="points">Points:</label>
<input type="number" id="points" name="points" step="3">
</form>

Note: Input restrictions are not foolproof, and JavaScript provides many ways to add illegal input. To safely
restrict input, it must also be checked by the receiver (the server)!

Page 49 of 349
The height and width Attributes
The input height and width attributes specify the height and width of an <input type="image">
element.
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="image" src="img_submit.gif" alt="Submit" width="48"
height="48">
</form>

The list Attribute


The input list attribute refers to a <datalist> element that contains pre-defined options for an <input>
element.
<form>
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>

The autocomplete Attribute


The input autocomplete attribute specifies whether a form or an input field should have autocomplete
on or off.
The autocomplete allows the browser to predict the value. When a user starts to type in a field, the
browser should display options to fill in the field, based on earlier typed values.
The autocomplete attribute works with <form> and the following <input> types: text, search, url, tel,
email, password, datepickers, range, and color.

Page 50 of 349
<form action="/action_page.php" autocomplete="on">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" autocomplete="off"><br><br>
<input type="submit" value="Submit">
</form>

Exercises:
1. In the input field below, add placeholder that says "Your name here".
<form action="/action_page.php">
<input type="text">
</form>

Solution:
<form action="/action_page.php">
<input type="text" placeholder="Your name here">
</form>

2. Set the max numbers of characters allowed in the input field to 40.
<form action="/action_page.php">
<input type="text" >
</form>

Solution:
<form action="/action_page.php">
<input type="text" maxlength="40">
</form>

3. Set the input field to be read only (meaning that the value cannot be changed)
<form action="/action_page.php">
<input type="text" >
</form>

Solution:
<form action="/action_page.php">
<input type="text" readonly>
</form>

Page 51 of 349
Part II - CSS

Introduction

CSS is the language we use to style a Web page.

What is CSS?
- CSS stands for Cascading Style Sheets.
- CSS describes how HTML elements are to be displayed on screen, paper, or in other media.
- CSS saves a lot of work. It can control the layout of multiple web pages all at once.
- External stylesheets are stored in CSS files.

Why Use CSS?


CSS is used to define styles for your web pages, including the design, layout and variations in display for
different devices and screen sizes.
<!DOCTYPE html>
<html>
<head>
<style>
Body {
background-color: lightblue;
}

h1 {
color: white;
text-align: center;
}

p {
font-family: verdana;
font-size: 20px;
}
</style>
</head>
<body>

<h1>My First CSS Example</h1>


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

</body>

Page 52 of 349
</html>

CSS Syntax

A CSS rule consists of a selector and a declaration block.

The selector points to the HTML element you want to style.


The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly
braces.
p {
color: red;
text-align: center;
}

Explanation of example is:


- p is a selector in CSS (it points to the HTML element you want to style: <p>).
- color is a property, and red is the property value.
- text-align is a property, and center is the property value.

CSS Selectors

CSS selectors are used to "find" (or select) the HTML elements you want to style.
We can divide CSS selectors into five categories:
- Simple selectors (select elements based on name, id, class).
- Combinator selectors (select elements based on a specific relationship between them).
- Pseudo-class selectors (select elements based on a certain state).
- Pseudo-elements selectors (select and style a part of an element).
- Attribute selectors (select elements based on an attribute or attribute value).

Page 53 of 349
The CSS element Selector
The element selector selects HTML elements based on the element name.
p {
text-align: center;
color: red;
}

The CSS id Selector


The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is used to select one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of the element.
#para1 {
text-align: center;
color: red;
}

The CSS class Selector


The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
.center {
text-align: center;
color: red;
}

You can also specify that only specific HTML elements should be affected by a class.
p.center.{
text-align: center;
color: red;
}

HTML elements can also refer to more than one class.


<p class="center large">This paragraph refers to two classes.</p>

Note: A class name cannot start with a number!

Page 54 of 349
The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.
* {
text-align: center;
color: blue;
}

The CSS Grouping Selector


The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}

p {
text-align: center;
color: red;
}

It will be better to group the selectors, to minimize the code.

Page 55 of 349
To group selectors, separate each selector with a comma.
h1, h2, p {
text-align: center;
color: red;
}

All CSS Simple Selectors


Selector Example Example description
#id #firstname Selects the element with id="firstname"
.class .intro Selects all elements with class="intro"
element.class p.intro Selects only <p> elements with class="intro"
* * Selects all elements
element p Selects all <p> elements
element,element,.. div, p Selects all <div> elements and all <p> elements

How To Add CSS

When a browser reads a style sheet, it will format the HTML document according to the information in
the style sheet.

Three Ways to Insert CSS


There are three ways of inserting a style sheet:
- External CSS
- Internal CSS
- Inline CSS

External CSS
With an external style sheet, you can change the look of an entire website by changing just one file!
Each HTML page must include a reference to the external style sheet file inside the <link> element, inside
the head section.

Page 56 of 349
Example:
External styles are defined within the <link> element, inside the <head> section of an HTML page.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>

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

</body>
</html>

An external style sheet can be written in any text editor, and must be saved with a .css extension.
The external .css file should not contain any HTML tags.
Here is how the "mystyle.css" file looks:
"mystyle.css"
body {
background-color: lightblue;
}

h1{
color: navy;
margin-left: 20px;
}

Note: Do not add a space between the property value and the unit (such as margin-left: 20 px;). The
correct way is: margin-left: 20px;

Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.
The internal style is defined inside the <style> element, inside the head section.

Page 57 of 349
<!DOCTYPE html>
<html>
<head>
<style>
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>

Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain any
CSS property.
<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;text-align:center;">This is a heading</h1>


<p style="color:red;">This is a paragraph.</p>

</body>
</html>

Multiple Style Sheets


If some properties have been defined for the same selector (element) in different style sheets, the value
from the last read style sheet will be used.
Assume that an external style sheet has the following style for the <h1> element:
h1 {
color: navy;

Page 58 of 349
}

Then, assume that an internal style sheet also has the following style for the <h1> element:
h1 {
color: orange;
}

If the internal style is defined after the link to the external style sheet, the <h1> elements will be "orange".
Example:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
color: orange;
}
</style>
</head>

However, if the internal style is defined before the link to the external style sheet, the <h1> elements will
be "navy".
Example:
<head>
<style>
h1 {
color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

Cascading Order
What style will be used when there is more than one style specified for an HTML element?
All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where number
one has the highest priority:
1. Inline style (inside an HTML element)
2. External and internal style sheets (in the head section)
3. Browser default
So, an inline style has the highest priority, and will override external and internal styles and browser
defaults.

Page 59 of 349
CSS Colors

Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.

CSS Color Names


In CSS, a color can be specified by using a predefined color name:

Tomato

Orange

DodgerBlue

MediumSeaGreen

Gray

SlateBlue

Violet

CSS Background Color


You can set the background color for HTML elements:

Hello World

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
aliquip ex ea commodo consequat.

Page 60 of 349
<h1 style="background-color:DodgerBlue;">Hello World</h1>
<p style="background-color:Tomato;">Lorem ipsum...</p>

CSS Text Color


You can set the color of text:
Hello World

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit
lobortis nisl ut aliquip ex ea commodo consequat.

<h1 style="color:Tomato;">Hello World</h1>


<p style="color:DodgerBlue;">Lorem ipsum...</p>
<p style="color:MediumSeaGreen;">Ut wisi enim...</p>

CSS Border Color


You can set the color of borders:
<h1 style="border:2px solid Tomato;">Hello World</h1>
<h1 style="border:2px solid DodgerBlue;">Hello World</h1>
<h1 style="border:2px solid Violet;">Hello World</h1>
CSS Color Values

In CSS, colors can also be specified using RGB values, HEX values, HSL values, RGBA values, and HSLA
values.
Same as color name "Tomato":rgb(255, 99, 71)

#ff6347

hsl(9, 100%, 64%)

%, 0.5)

Page 61 of 349
<h1 style="background-color:rgb(255, 99, 71);">...</h1>
<h1 style="background-color:#ff6347;">...</h1>
<h1 style="background-color:hsl(9, 100%, 64%);">...</h1>

<h1 style="background-color:rgba(255, 99, 71, 0.5);">...</h1>


<h1 style="background-color:hsla(9, 100%, 64%, 0.5);">...</h1>

CSS Backgrounds
The CSS background properties are used to add background effects for elements.
In these chapters, you will learn about the following CSS background properties:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
- background (shorthand property)

CSS background-color
The background-color property specifies the background color of an element.
Body {
background-color: lightblue;
}

With CSS, a color is most often specified by:


- a valid color name - like "red"
- a HEX value - like "#ff0000"
- an RGB value - like "rgb(255,0,0)"

CSSBorders

The CSS border properties allow you to specify the style, width, and color of an element's border.

CSS Border Style


The border-style property specifies what kind of border to display.
The following values are allowed:
- dotted - Defines a dotted border
- dashed - Defines a dashed border

Page 62 of 349
- solid - Defines a solid border
- double - Defines a double border
- groove - Defines a 3D grooved border. The effect depends on the border-color value
- ridge - Defines a 3D ridged border. The effect depends on the border-color value
- inset - Defines a 3D inset border. The effect depends on the border-color value
- outset - Defines a 3D outset border. The effect depends on the border-color value
- none - Defines no border
- hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right border, bottom
border, and the left border).
p.dotted {border-style: dotted;}
p.dashed {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.none {border-style: none;}
p.hidden {border-style: hidden;
p.mix {border-style: dotted dashed solid double;}

CSS Margins

Margins are used to create space around elements, outside of any defined borders.
The CSS margin properties are used to create space around elements, outside of any defined borders.

Page 63 of 349
With CSS, you have full control over the margins. There are properties for setting the margin for each side
of an element (top, right, bottom, and left).

margin - Individual Sides


CSS has properties for specifying the margin for each side of an element:
- margin-top
- margin-right
- margin-bottom
- margin-left

All the margin properties can have the following values:


- auto - the browser calculates the margin
- length - specifies a margin in px, pt, cm, etc.
- % - specifies a margin in % of the width of the containing element
- inherit - specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.


p {
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}

Margin - Shorthand Property


To shorten the code, it is possible to specify all the margin properties in one property.
The margin property is a shorthand property for the following individual margin properties:
- margin-top
- margin-right
- margin-bottom
- margin-left

So, here is how it works.


If the margin property has four values:
- margin: 25px 50px 75px 100px;
o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px

Page 64 of 349
p {
margin: 25px 50px 75px 100px;
}

If the margin property has three values:


- margin: 25px 50px 75px;
o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px
p {
margin: 25px 50px 75px;
}

If the margin property has two values:


- margin: 25px 50px;
o top and bottom margins are 25px
o right and left margins are 50px
p {
margin: 25px 50px;
}

If the margin property has one value:


- margin: 25px;
o all four margins are 25px
p {
margin: 25px;
}

The auto Value


You can set the margin property to auto to horizontally center the element within its container.
The element will then take up the specified width, and the remaining space will be split equally between
the left and right margins.

Page 65 of 349
div {
width: 300px;
margin: auto;
border: 1px solid red;
}

The inherit Value


This example lets the left margin of the <p class="ex1"> element be inherited from the parent element
(<div>):
div {
border: 1px solid red;
margin-left: 100px;
}

p.ex1 {
margin-left: inherit;
}

CSS padding

padding is used to create space around an element's content, inside of any defined borders.

<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 70px;
border: 1px solid #4CAF50;
}
</style>
</head>
<body>

<h2>CSS Padding</h2>
<div>This element has a padding of 70px.</div>

</body>
</html>

Page 66 of 349
And the result:

The CSS padding properties are used to generate space around an element's content, inside of any
defined borders.
With CSS, you have full control over the padding. There are properties for setting the padding for each
side of an element (top, right, bottom, and left).

padding - Individual Sides


CSS has properties for specifying the padding for each side of an element:
- padding-top
- padding-right
- padding-bottom
- padding-left

All the padding properties can have the following values:


 length - specifies a padding in px, pt, cm, etc.
 % - specifies a padding in % of the width of the containing element
 inherit - specifies that the padding should be inherited from the parent element

Note: Negative values are not allowed.


div {
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}

padding - Shorthand Property


To shorten the code, it is possible to specify all the padding properties in one property.
The padding property is a shorthand property for the following individual padding properties:
- padding-top
- padding-right

Page 67 of 349
- padding-bottom
- padding-left
So, here is how it works:
If the padding property has four values.
- padding: 25px 50px 75px 100px;
o top padding is 25px
o right padding is 50px
o bottom padding is 75px
o left padding is 100px

CSS Height and Width

The CSS height and width properties are used to set the height and width of an element.
The CSS max-width property is used to set the maximum width of an element.

CSS Setting height and width


The height and width properties are used to set the height and width of an element.
The height and width properties do not include padding, borders, or margins. It sets the height/width
of the area inside the padding, border, and margin of the element.

CSS height and width Values


The height and width properties may have the following values:
- auto - This is default. The browser calculates the height and width
- length - Defines the height/width in px, cm etc.
- % - Defines the height/width in percent of the containing block
- initial - Sets the height/width to its default value
- inherit - The height/width will be inherited from its parent value

Page 68 of 349
CSS height and width Examples
div {
height: 200px;
width: 50%;
background-color: powderblue;
}

div {
height: 100px;
width: 500px;
background-color: powderblue;
}

Note: Remember that the height and width properties do not include padding, borders, or margins!
They set the height/width of the area inside the padding, border, and margin of the element!

Setting max-width
The max-width property is used to set the maximum width of an element. The max-width can be specified
in length values, like px, cm, etc., or in percent (%) of the containing block, or set to none (this is default.
Means that there is no maximum width).
The problem with the <div> above occurs when the browser window is smaller than the width of the
element (500px). The browser then adds a horizontal scrollbar to the page. Using max-width instead, in
this situation, will improve the browser's handling of small windows.

This element has a height of 100 pixels and a max-width of 500 pixels.

Note: If you for some reason use both the width property and the max-width property on the same
element, and the value of the width property is larger than the max-width property; the max-width
property will be used (and the width property will be ignored).
Example:
This <div> element has a height of 100 pixels and a max-width of 500 pixels.

Page 69 of 349
div {
max-width: 500px;
height: 100px;
background-color: powderblue;
}

Example:
Use the padding shorthand property with four values.
div {
padding: 25px 50px 75px 100px;
}

If the padding property has three values.


- padding: 25px 50px 75px;
o top padding is 25px
o right and left paddings are 50px
o bottom padding is 75px

Example:
Use the padding shorthand property with three values.
div {
padding: 25px 50px 75px;
}

If the padding property has two values.


- padding: 25px 50px;
o top and bottom paddings are 25px
o right and left paddings are 50px

Example:
Use the padding shorthand property with two values.
div {
padding: 25px 50px;
}

If the padding property has one value:


- padding: 25px;
o all four paddings are 25px

Page 70 of 349
Example:
Use the padding shorthand property with one value.
div {
padding: 25px;
}

Padding and Element width


The CSS width property specifies the width of the element's content area. The content area is the portion
inside the padding, border, and margin of an element (the box model).

So, if an element has a specified width, the padding added to that element will be added to the total
width of the element. This is often an undesirable result.
Example:
Here, the <div> element is given a width of 300px. However, the actual width of the <div> element will
be 350px (300px + 25px of left padding + 25px of right padding).
div {
width: 300px;
padding: 25px;
}

To keep the width at 300px, no matter the amount of padding, you can use the box-sizing property.
This causes the element to maintain its actual width; if you increase the padding, the available content
space will decrease.

Page 71 of 349
Example:
Use the box-sizing property to keep the width at 300px, no matter the amount of padding.
div {
width: 300px;
padding: 25px;
box-sizing: border-box;
}

CSS Box Model

All HTML elements can be considered as boxes.

The CSS Box Model


In CSS, the term "box model" is used when talking about design and layout. The CSS box model is
essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and
the actual content.
The image below illustrates the box model:

Explanation of the different parts:


- Content - The content of the box, where text and images appear
- Padding - Clears an area around the content. The padding is transparent
- Border - A border that goes around the padding and content
- Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between elements.

Page 72 of 349
Example:
Demonstration of the box model.
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}

Width and Height of an Element


In order to set the width and height of an element correctly in all browsers, you need to know how the
box model works.
Important: When you set the width and height properties of an element with CSS, you just set the width
and height of the content area. To calculate the full size of an element, you must also add padding,
borders and margins.

Example:
This <div> element will have a total width of 350px:
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}

Here is the calculation:


320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px
The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left border + right border + left
margin + right margin

The total height of an element should be calculated like this:


Total element height = height + top padding + bottom padding + top border + bottom border
+ top margin + bottom margin

Page 73 of 349
What is Responsive Web Design?
Responsive web design makes your web page look good on all devices.
- Responsive web design uses only HTML and CSS.
- Responsive web design is not a program or a JavaScript.

Designing For The Best Experience For All Users


Web pages can be viewed using many different devices: desktops, tablets, and phones. Your web page
should look good, and be easy to use, regardless of the device.
Web pages should not leave out information to fit smaller devices, but rather adapt its content to fit any
device:

It is called responsive web design when you use CSS and HTML to resize, hide, shrink, enlarge, or move
the content to make it look good on any screen.

What is The Viewport?


The viewport is the user's visible area of a web page. The viewport varies with the device and will be
smaller on a mobile phone than on a computer screen.
Before tablets and mobile phones, web pages were designed only for computer screens, and it was
common for web pages to have a static design and a fixed size. Then, when we started surfing the internet
using tablets and mobile phones, fixed size web pages were too large to fit the viewport. To fix this,
browsers on those devices scaled down the entire web page to fit the screen. This was not perfect!! But
a quick fix.

Page 74 of 349
Setting The Viewport
HTML5 introduced a method to let web designers take control over the viewport, through the <meta> tag.
You should include the following <meta> viewport element in all your web pages:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

This gives the browser instructions on how to control the page's dimensions and scaling.
The width=device-width part sets the width of the page to follow the screen-width of the device (which
will vary depending on the device).
The initial-scale=1.0 part sets the initial zoom level when the page is first loaded by the browser.
Here is an example of a web page without the viewport meta tag, and the same web page with the
viewport meta tag:

Size Content to The Viewport


Users are used to scroll websites vertically on both desktop and mobile devices - but not horizontally!
So, if the user is forced to scroll horizontally, or zoom out, to see the whole web page it results in a poor
user experience.
Some additional rules to follow:
1. Do NOT use large fixed width elements - For example, if an image is displayed at a width wider
than the viewport it can cause the viewport to scroll horizontally. Remember to adjust this
content to fit within the width of the viewport.

Page 75 of 349
2. Do NOT let the content rely on a particular viewport width to render well - Since screen
dimensions and width in CSS pixels vary widely between devices, content should not rely on a
particular viewport width to render well.
3. Use CSS media queries to apply different styling for small and large screens - Setting large absolute
CSS widths for page elements will cause the element to be too wide for the viewport on a smaller
device. Instead, consider using relative width values, such as width: 100%. Also, be careful of using
large absolute positioning values. It may cause the element to fall outside the viewport on small
devices.

What is a Grid-View?
Many web pages are based on a grid-view, which means that the page is divided into columns:

Using a grid-view is very helpful when designing web pages. It makes it easier to place elements on the
page.

A responsive grid-view often has 12 columns, and has a total width of 100%, and will shrink and expand
as you resize the browser window.

Page 76 of 349
Building a Responsive Grid-View
Lets start building a responsive grid-view. First ensure that all HTML elements have the box-sizing
property set to border-box. This makes sure that the padding and border are included in the total width
and height of the elements.
Add the following code in your CSS:
* {
box-sizing: border-box;
}

*[see more about box-sizing]


The following example shows a simple responsive web page, with two columns:

Example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}

.header {
border: 1px solid red;
padding: 15px;
}

.menu {
width: 25%;
float: left;
padding: 15px;
border: 1px solid red;
}

.main {
width: 75%;
float: left;
padding: 15px;
border: 1px solid red;

Page 77 of 349
}
</style>
</head>
<body>

<div class="header">
<h1>Chania</h1>
</div>

<div class="menu">
<ul>
<li>The Flight</li>
<li>The City</li>
<li>The Island</li>
<li>The Food</li>
</ul>
</div>

<div class="main">
<h1>The City</h1>
<p>Chania is the capital of the Chania region on the island of Crete. The city
can be divided in two parts, the old town and the modern city.</p>
<p>Resize the browser window to see how the content respond to the resizing.</p>
</div>

</body>
</html>

The example above is fine if the web page only contains two columns. However, we want to use a
responsive grid-view with 12 columns, to have more control over the web page.
First we must calculate the percentage for one column: 100% / 12 columns = 8.33%. Then we make one
class for each of the 12 columns, class="col-" and a number defining how many columns the section should
span.

Page 78 of 349
CSS:
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-1 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}

All these columns should be floating to the left, and have a padding of 15px.
CSS:
[class*="col-"] {
float: left;
padding: 15px;
border: 1px solid red;
}

Each row should be wrapped in a <div>. The number of columns inside a row should always add up to 12.
HTML:
<div class="row">
<div class="col-3">...</div> <!-- 25% -->
<div class="col-9">...</div> <!-- 75% -->
</div>

The columns inside a row are all floating to the left, and are therefore taken out of the flow of the page,
and other elements will be placed as if the columns do not exist. To prevent this, we will add a style that
clears the flow:
CSS:
.row::after {
content: "";
clear: both;
display: table;
}

We also want to add some styles and colors to make it look better.
Example:
html {
font-family: "Lucida Sans", sans-serif;
}

Page 79 of 349
.header {
background-color: #9933cc;
color: #ffffff;
padding: 15px;
}

.menu ul {
list-style-type: none;
margin: 0;
padding: 0;
}

.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #33b5e5;
color: #ffffff;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.menu li:hover {
background-color: #0099cc;
}

The full solution is:


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}

.row::after {
content: "";
clear: both;
display: table;
}

[class*="col-"] {
float: left;
padding: 15px;
}

.col-1 {width: 8.33%;}


.col-2 {width: 16.66%;}

Page 80 of 349
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}

html {
font-family: "Lucida Sans", sans-serif;
}

.header {
background-color: #9933cc;
color: #ffffff;
padding: 15px;
}

.menu ul {
list-style-type: none;
margin: 0;
padding: 0;
}

.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #33b5e5;
color: #ffffff;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.menu li:hover {
background-color: #0099cc;
}
</style>
</head>
<body>

<div class="header">
<h1>Chania</h1>
</div>

Page 81 of 349
<div class="row">
<div class="col-3 menu">
<ul>
<li>The Flight</li>
<li>The City</li>
<li>The Island</li>
<li>The Food</li>
</ul>
</div>

<div class="col-9">
<h1>The City</h1>
<p>Chania is the capital of the Chania region on the island of Crete. The city can
be divided in two parts, the old town and the modern city.</p>
<p>Resize the browser window to see how the content respond to the resizing.</p>
</div>
</div>

</body>
</html>

What is a Media Query?

Media query is a CSS technique introduced in CSS3.


It uses the @media rule to include a block of CSS properties only if a certain condition is true.
Example:
If the browser window is 600px or smaller, the background color will be lightblue:
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}

Add a Breakpoint
Earlier we made a web page with rows and columns, and it was responsive, but it did not look good on a
small screen. Media queries can help with that. We can add a breakpoint where certain parts of the design
will behave differently on each side of the breakpoint.

Page 82 of 349
Use a media query to add a breakpoint at 768px.
Example:
When the screen (browser window) gets smaller than 768px, each column should have a width of 100%:
/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}

@media only screen and (max-width: 768px) {


/* For mobile phones: */
[class*="col-"] {
width: 100%;
}
}

Always Design for Mobile First


Mobile First means designing for mobile before designing for desktop or any other device (This will make
the page display faster on smaller devices). This means that we must make some changes in our CSS.
Instead of changing styles when the width gets smaller than 768px, we should change the design when
the width gets larger than 768px. This will make our design Mobile First.

Page 83 of 349
Example:
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}

@media only screen and (min-width: 768px) {


/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}

The full example:


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
{
box-sizing: border-box;
}

.row::after {
content: "";
clear: both;
display: table;
}

[class*="col-"] {
float: left;
padding: 15px;
}

html {
font-family: "Lucida Sans", sans-serif;
}

Page 84 of 349
.header {
background-color: #9933cc;
color: #ffffff;
padding: 15px;
}

.menu ul {
list-style-type: none;
margin: 0;
padding: 0;
}

.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #33b5e5;
color: #ffffff;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.menu li:hover {
background-color: #0099cc;
}

.aside {
background-color: #33b5e5;
padding: 15px;
color: #ffffff;
text-align: center;
font-size: 14px;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.footer {
background-color: #0099cc;
color: #ffffff;
text-align: center;
font-size: 12px;
padding: 15px;
}

/* For mobile phones: */


[class*="col-"] {
width: 100%;

Page 85 of 349
}

@media only screen and (min-width: 768px) {


/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}
</style>
</head>
<body>

<div class="header">
<h1>Chania</h1>
</div>

<div class="row">
<div class="col-3 menu">
<ul>
<li>The Flight</li>
<li>The City</li>
<li>The Island</li>
<li>The Food</li>
</ul>
</div>

<div class="col-6">
<h1>The City</h1>
<p>Chania is the capital of the Chania region on the island of Crete. The city can
be divided in two parts, the old town and the modern city.</p>
</div>

<div class="col-3 right">


div class="aside">
<h2>What?</h2>
<p>Chania is a city on the island of Crete.</p>

Page 86 of 349
<h2>Where?</h2>
<p>Crete is a Greek island in the Mediterranean Sea.</p>
<h2>How?</h2>
<p>You can reach Chania airport from all over Europe.</p>
</div>
</div>
</div>

<div class="footer">
<p>Resize the browser window to see how the content respond to the resizing.</p>
</div>

</body>
</html>

Another Breakpoint
You can add as many breakpoints as you like. We will also insert a breakpoint between tablets and mobile
phones.
Desktop:

Page 87 of 349
Tablet:

Phone:

We do this by adding one more media query (at 600px), and a set of new classes for devices larger than
600px (but smaller than 768px).

Page 88 of 349
Example:
Note that the two sets of classes are almost identical, the only difference is the name (col- and col-s-):
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}

@media only screen and (min-width: 600px) {


/* For tablets: */
.col-s-1 {width: 8.33%;}
.col-s-2 {width: 16.66%;}
.col-s-3 {width: 25%;}
.col-s-4 {width: 33.33%;}
.col-s-5 {width: 41.66%;}
.col-s-6 {width: 50%;}
.col-s-7 {width: 58.33%;}
.col-s-8 {width: 66.66%;}
.col-s-9 {width: 75%;}
.col-s-10 {width: 83.33%;}
.col-s-11 {width: 91.66%;}
.col-s-12 {width: 100%;}
}

@media only screen and (min-width: 768px) {


/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}

It might seem odd that we have two sets of identical classes, but it gives us the opportunity in HTML, to
decide what will happen with the columns at each breakpoint.
HTML Example:
For desktop:
The first and the third section will both span 3 columns each. The middle section will span
6 columns.

Page 89 of 349
For tablets:
The first section will span 3 columns, the second will span 9, and the third section will be
displayed below the first two sections, and it will span 12 columns:
<div class="row">
<div class="col-3 col-s-3">...</div>
<div class="col-6 col-s-9">...</div>
<div class="col-3 col-s-12">...</div>
</div>

Full example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
{
box-sizing: border-box;
}

.row::after {
content: "";
clear: both;
display: table;
}

[class*="col-"] {
float: left;
padding: 15px;
}

html {
font-family: "Lucida Sans", sans-serif;
}

.header {
background-color: #9933cc;
color: #ffffff;
padding: 15px;
}

.menu ul {
list-style-type: none;
margin: 0;

Page 90 of 349
padding: 0;
}

.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #33b5e5;
color: #ffffff;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.menu li:hover {
background-color: #0099cc;
}

.aside {
background-color: #33b5e5;
padding: 15px;
color: #ffffff;
text-align: center;
font-size: 14px;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
}

.footer {
background-color: #0099cc;
color: #ffffff;
text-align: center;
font-size: 12px;
padding: 15px;
}

/* For mobile phones: */


[class*="col-"] {
width: 100%;
}

@media only screen and (min-width: 600px) {


/* For tablets: */
.col-s-1 {width: 8.33%;}
.col-s-2 {width: 16.66%;}
.col-s-3 {width: 25%;}
.col-s-4 {width: 33.33%;}
.col-s-5 {width: 41.66%;}
.col-s-6 {width: 50%;}

Page 91 of 349
.col-s-7 {width: 58.33%;}
.col-s-8 {width: 66.66%;}
.col-s-9 {width: 75%;}
.col-s-10 {width: 83.33%;}
.col-s-11 {width: 91.66%;}
.col-s-12 {width: 100%;}
}
@media only screen and (min-width: 768px) {
/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}
</style>
</head>
<body>

<div class="header">
<h1>Chania</h1>
</div>

<div class="row">
<div class="col-3 col-s-3 menu">
<ul>
<li>The Flight</li>
<li>The City</li>
<li>The Island</li>
<li>The Food</li>
</ul>
</div>

<div class="col-6 col-s-9">


<h1>The City</h1>
<p>Chania is the capital of the Chania region on the island of Crete. The city can
be divided in two parts, the old town and the modern city.</p>
</div>

Page 92 of 349
<div class="col-3 col-s-12">
<div class="aside">
<h2>What?</h2>
<p>Chania is a city on the island of Crete.</p>
<h2>Where?</h2>
<p>Crete is a Greek island in the Mediterranean Sea.</p>
<h2>How?</h2>
<p>You can reach Chania airport from all over Europe.</p>
</div>
</div>
</div>

<div class="footer">
<p>Resize the browser window to see how the content respond to the resizing.</p>
</div>

</body>
</html>

Typical Device Breakpoints


There are tons of screens and devices with different heights and widths, so it is hard to create an exact
breakpoint for each device. To keep things simple you could target five groups:
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {...}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {...}

/* Medium devices (landscape tablets, 768px and up) */


@media only screen and (min-width: 768px) {...}

/* Large devices (laptops/desktops, 992px and up) */


@media only screen and (min-width: 992px) {...}

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {...}

Example:
<!DOCTYPE html>
<html>

Page 93 of 349
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.example {
padding: 20px;
color: white;
}
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
.example {background: red;}
}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {
.example {background: green;}
}

/* Medium devices (landscape tablets, 768px and up) */


@media only screen and (min-width: 768px) {
.example {background: blue;}
}

/* Large devices (laptops/desktops, 992px and up) */


@media only screen and (min-width: 992px) {
.example {background: orange;}
}

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
.example {background: pink;}
}
</style>
</head>
<body>

<h2>Typical Media Query Breakpoints</h2>


<p class="example">Resize the browser window to see how the background color of this
paragraph changes on different screen sizes.</p>

</body>
</html>

Page 94 of 349
Orientation: Portrait / Landscape
Media queries can also be used to change layout of a page depending on the orientation of the browser.
You can have a set of CSS properties that will only apply when the browser window is wider than its height,
a so called "Landscape" orientation.
Example:
The web page will have a lightblue background if the orientation is in landscape mode:
@media only screen and (orientation: landscape) {
body {
background-color: lightblue;
}
}

Solution:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
background-color: lightgreen;
}

@media only screen and (orientation: landscape) {


body {
background-color: lightblue;
}
}
</style>
</head>
<body>

<p>Resize the browser window. When the width of this document is larger than the
height, the background color is "lightblue", otherwise it is "lightgreen".</p>

</body>
</html>

Page 95 of 349
Hide Elements With Media Queries
Another common use of media queries, is to hide elements on different screen sizes:
/* If the screen size is 600px wide or less, hide the element */
@media only screen and (max-width: 600px) {
div.example {
display: none;
}
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
div.example {
background-color: yellow;
padding: 20px;
}

@media screen and (max-width: 600px) {


div.example {
display: none;
}
}
</style>
</head>
<body>

<h2>Hide elements on different screen sizes</h2>

<div class="example">Example DIV.</div>

<p>When the browser's width is 600px wide or less, hide the div element. Resize the
browser window to see the effect.</p>

</body>
</html>

Page 96 of 349
Change Font Size With Media Queries
You can also use media queries to change the font size of an element on different screen sizes.
Example:
/* If the screen size is 601px or more, set the font-size of <div> to 80px */
@media only screen and (min-width: 601px) {
div.example {
font-size: 80px;
}
}

/* If the screen size is 600px or less, set the font-size of <div> to 30px */
@media only screen and (max-width: 600px) {
div.example {
font-size: 30px;
}
}

CSS Transitions

CSS transitions allows you to change property values smoothly, over a given duration. Mouse over the
element below to see a CSS transition effect.
In this part you will learn about the following properties:
- transition
- transition-delay
- transition-duration
- transition-property
- transition-timing-function

How to Use CSS Transitions?


To create a transition effect, you must specify two things:
- the CSS property you want to add an effect to
- the duration of the effect
Note: If the duration part is not specified, the transition will have no effect, because the default value is
0.
The following example shows a 100px * 100px red <div> element. The <div> element has also specified
a transition effect for the width property, with a duration of 2 seconds:

Page 97 of 349
Example:
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}

The transition effect will start when the specified CSS property (width) changes value.
Now, let us specify a new value for the width property when a user mouses over the <div> element.
Example:
div:hover {
width: 300px;
}

<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}

#div1 {transition-timing-function: linear;}


#div2 {transition-timing-function: ease;}
#div3 {transition-timing-function: ease-in;}
#div4 {transition-timing-function: ease-out;}
#div5 {transition-timing-function: ease-in-out;}

div:hover {
width: 300px;
}
</style>
</head>
<body>

<h1>The transition-timing-function Property</h1>

<p>Hover over the div elements below, to see the different speed curves:</p>

<div id="div1">linear</div><br>

Page 98 of 349
<div id="div2">ease</div><br>
<div id="div3">ease-in</div><br>
<div id="div4">ease-out</div><br>
<div id="div5">ease-in-out</div><br>

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier
versions.</p>

</body>
</html>

Notice that when the cursor mouses out of the element, it will gradually change back to its original style.

Change Several Property Values


The following example adds a transition effect for both the width and height property, with a duration of
2 seconds for the width and 4 seconds for the height:
div {
transition: width 2s, height 4s;
}

<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s, height 4s;
}

div:hover {
width: 300px;
height: 300px;
}
</style>
</head>
<body>

<h1>The transition Property</h1>

<p>Hover over the div element below, to see the transition effect:</p>

Page 99 of 349
<div></div>

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier
versions.</p>

</body>
</html>

Specify the Speed Curve of the Transition


The transition-timing-function property specifies the speed curve of the transition effect.
The transition-timing-function property can have the following values:
- ease - specifies a transition effect with a slow start, then fast, then end slowly (this is default)
- linear - specifies a transition effect with the same speed from start to end
- ease-in - specifies a transition effect with a slow start
- ease-out - specifies a transition effect with a slow end
- ease-in-out - specifies a transition effect with a slow start and end
- cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function
The following example shows some of the different speed curves that can be used:
#div1 {transition-timing-function: linear;}
#div2 {transition-timing-function: ease;}
#div3 {transition-timing-function: ease-in;}
#div4 {transition-timing-function: ease-out;}
#div5 {transition-timing-function: ease-in-out;}

Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}

#div1 {transition-timing-function: linear;}


#div2 {transition-timing-function: ease;}
#div3 {transition-timing-function: ease-in;}
#div4 {transition-timing-function: ease-out;}
#div5 {transition-timing-function: ease-in-out;}

Page 100 of 349


div:hover {
width: 300px;
}
</style>
</head>
<body>

<h1>The transition-timing-function Property</h1>

<p>Hover over the div elements below, to see the different speed curves:</p>

<div id="div1">linear</div><br>
<div id="div2">ease</div><br>
<div id="div3">ease-in</div><br>
<div id="div4">ease-out</div><br>
<div id="div5">ease-in-out</div><br>

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier
versions.</p>

</body>
</html>

Delay the Transition Effect


The transition-delay property specifies a delay (in seconds) for the transition effect.
The following example has a 1 second delay before starting:
Div {
transition-delay: 1s;
}

Transition + Transformation
The following example adds a transition effect to the transformation:
div {
transition: width 2s, height 2s, transform 2s;
}

Page 101 of 349


<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s, height 2s, transform 2s;
}

div:hover {
width: 300px;
height: 300px;
transform: rotate(180deg);
}
</style>
</head>
<body>

<h1>Transition + Transform</h1>

<p>Hover over the div element below:</p>

<div></div>

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier
versions.</p>

</body>
</html>

Page 102 of 349


Bootstrap 4

What is Bootstrap?
- Bootstrap is a free front-end framework for faster and easier web development
- Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables,
navigation, modals, image carousels and many other, as well as optional JavaScript plugins
- Bootstrap also gives you the ability to easily create responsive designs

What is Responsive Web Design?


Responsive web design is about creating web sites which automatically adjust themselves to look good
on all devices, from small phones to large desktops.
Bootstrap 4 Example:
<div class="jumbotron text-center">
<h1>My First Bootstrap Page</h1>
<p>Resize this responsive page to see the effect!</p>
</div>

<div class="container">
<div class="row">
<div class="col-sm-4">
<h3>Column 1</h3>
<p>Lorem ipsum dolor..</p>
</div>
<div class="col-sm-4">
<h3>Column 2</h3>
<p>Lorem ipsum dolor..</p>
</div>
<div class="col-sm-4">
<h3>Column 3</h3>
<p>Lorem ipsum dolor..</p>
</div>
</div>
</div>

Bootstrap 3 vs. Bootstrap 4

Bootstrap 4 is the newest version of Bootstrap; with new components, faster stylesheet and more
responsiveness. Bootstrap 4 supports the latest, stable releases of all major browsers and platforms.
However, Internet Explorer 9 and down is not supported.

Page 103 of 349


Why Use Bootstrap?
Advantages of Bootstrap:
- Easy to use: Anybody with just basic knowledge of HTML and CSS can start using Bootstrap
- Responsive features: Bootstrap's responsive CSS adjusts to phones, tablets, and desktops
- Mobile-first approach: In Bootstrap, mobile-first styles are part of the core framework
- Browser compatibility: Bootstrap 4 is compatible with all modern browsers (Chrome, Firefox,
Internet Explorer 10+, Edge, Safari, and Opera)

Where to Get Bootstrap 4?


There are two ways to start using Bootstrap 4 on your own web site.
You can:
- Include Bootstrap 4 from a CDN
- Download Bootstrap 4 from getbootstrap.com

Bootstrap 4 CDN
If you don't want to download and host Bootstrap 4 yourself, you can include it from a CDN (Content
Delivery Network). MaxCDN provides CDN support for Bootstrap's CSS and JavaScript. You must also
include jQuery.
MaxCDN:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/c
ss/bootstrap.min.css">

<!-- jQuery library -->


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
></script>

<!-- Popper JS -->


<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/poppe
r.min.js"></script>

<!-- Latest compiled JavaScript -->


<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.
js"></script>

One advantage of using the Bootstrap 4 CDN:


Many users already have downloaded Bootstrap 4 from MaxCDN when visiting another site. As a result,
it will be loaded from cache when they visit your site, which leads to faster loading time. Also, most CDN's

Page 104 of 349


will make sure that once a user requests a file from it, it will be served from the server closest to them,
which also leads to faster loading time.
jQuery and Popper?
Bootstrap 4 use jQuery and Popper.js for JavaScript components (like modals, tooltips, popovers etc).
However, if you just use the CSS part of Bootstrap, you don't need them.

Downloading Bootstrap 4
If you want to download and host Bootstrap 4 yourself, go to https://getbootstrap.com/, and follow the
instructions there.

Create First Web Page With Bootstrap 4


1. Add the HTML5 doctype
Bootstrap 4 uses HTML elements and CSS properties that require the HTML5 doctype. Always include the
HTML5 doctype at the beginning of the page, along with the lang attribute and the correct character set:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
</html>

2. Bootstrap 4 is mobile-first
Bootstrap 4 is designed to be responsive to mobile devices. Mobile-first styles are part of the core
framework.
To ensure proper rendering and touch zooming, add the following <meta> tag inside the <head> element:
<meta name="viewport" content="width=device-width, initial-scale=1">

The width=device-width part sets the width of the page to follow the screen-width of the device (which
will vary depending on the device).
The initial-scale=1 part sets the initial zoom level when the page is first loaded by the browser.
3. Containers
Bootstrap 4 also requires a containing element to wrap site contents. There are two container classes to
choose from:
1. The .container class provides a responsive fixed width container
2. The .container-fluid class provides a full width container, spanning the entire width of the
viewport

Page 105 of 349


Two Basic Bootstrap 4 Pages
The following example shows the code for a basic Bootstrap 4 page (with a responsive fixed width
container).

Page 106 of 349


Container Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 4 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2
/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.j
s"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/pop
per.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.mi
n.js"></script>
</head>
<body>

<div class="container">
<h1>My First Bootstrap Page</h1>
<p>This is some text.</p>
</div>

</body>
</html>

The following example shows the code for a basic Bootstrap 4 page (with a full width container).
Container Fluid Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 4 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2
/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.j
s"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/pop
per.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.mi
n.js"></script>
</head>
<body>

<div class="container-fluid">
<h1>My First Bootstrap Page</h1>
<p>This is some text.</p>
</div>

Page 107 of 349


</body>
</html>

Bootstrap 4 Grid System

Bootstrap's grid system is built with flexbox and allows up to 12 columns across the page. If you do not
want to use all 12 columns individually, you can group the columns together to create wider columns:

span span span span span span span span span span span span
1 1 1 1 1 1 1 1 1 1 1 1

span 4 span 4 span 4

span 4 span 8

span 6 span 6

span 12

The grid system is responsive, and the columns will re-arrange automatically depending on the screen
size. Make sure that the sum adds up to 12 or fewer (it is not required that you use all 12 available
columns).

Grid Classes
The Bootstrap 4 grid system has five classes:
- .col- (extra small devices - screen width less than 576px)
- .col-sm- (small devices - screen width equal to or greater than 576px)
- .col-md- (medium devices - screen width equal to or greater than 768px)
- .col-lg- (large devices - screen width equal to or greater than 992px)
- .col-xl- (xlarge devices - screen width equal to or greater than 1200px)

The classes above can be combined to create more dynamic and flexible layouts.
Tip: Each class scales up, so if you wish to set the same widths for sm and md, you only need to specify sm.

Page 108 of 349


Basic Structure of a Bootstrap 4 Grid
The following is a basic structure of a Bootstrap 4 grid:
<!-- Control the column width, and how they should appear on different devices
-->
<div class="row">
<div class="col-*-*"></div>
<div class="col-*-*"></div>
</div>
<div class="row">
<div class="col-*-*"></div>
<div class="col-*-*"></div>
<div class="col-*-*"></div>
</div>

<!-- Or let Bootstrap automatically handle the layout -->


<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>

First example: create a row (<div class="row">). Then, add the desired number of columns (tags with
appropriate .col-*-* classes). The first star (*) represents the responsiveness: sm, md, lg or xl, while the
second star represents a number, which should add up to 12 for each row.
Second example: instead of adding a number to each col, let bootstrap handle the layout, to create equal
width columns: two "col" elements = 50% width to each col. Three cols = 33.33% width to each col.
Four cols = 25% width, etc. You can also use .col-sm|md|lg|xl to make the columns responsive.
Below we have collected some examples of basic Bootstrap 4 grid layouts.

Three Equal Columns

Page 109 of 349


The following example shows how to create three equal-width columns, on all devices and screen widths.
Example:
<div class="row">
<div class="col">.col</div>
<div class="col">.col</div>
<div class="col">.col</div>
</div>

Responsive Columns

The following example shows how to create four equal-width columns starting at tablets and scaling to
extra large desktops. On mobile phones or screens that are less than 576px wide, the columns will
automatically stack on top of each other.
Example:
<div class="row">
<div class="col-sm-3">.col-sm-3</div>
<div class="col-sm-3">.col-sm-3</div>
<div class="col-sm-3">.col-sm-3</div>
<div class="col-sm-3">.col-sm-3</div>
</div>

Two Unequal Responsive Columns

The following example shows how to get two various-width columns starting at tablets and scaling to large
extra desktops.
Example:
<div class="row">
<div class="col-sm-4">.col-sm-4</div>
<div class="col-sm-8">.col-sm-8</div>
</div>

Page 110 of 349


Classes, tables, buttons and other
For more details on the Bootstrap you have to focus on the official documentation or the online resources
like:
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://www.w3schools.com/bootstrap4/default.asp

Page 111 of 349


Part III - JavaScript

JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().
The example below "finds" an HTML element (with id="demo"), and changes the element content
(innerHTML) to "Hello JavaScript".
Example:
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick="document.getElementById('demo').innerHTML = 'He
llo JavaScript!'">Click Me!</button>

JavaScript accepts both double and single quotes.


Example:
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick="document.getElementById('demo').innerHTML = 'He
llo JavaScript!'">Click Me!</button>

JavaScript Can Change HTML Styles (CSS)


Changing the style of an HTML element, is a variant of changing an HTML attribute.
Example:
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize=
'35px'">Click Me!</button>

JavaScript Can Hide HTML Elements


Hiding HTML elements can be done by changing the display style.
Example:
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click
Me!</button>

Page 112 of 349


JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the display style:
Example:
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click
Me!</button>

Carefull:
JavaScript and Java are completely different languages, both in concept and design.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.

JavaScript Variables

There are 3 ways to declare a JavaScript variable:


 Using var
 Using let
 Using const
In this section we are going to use var.

Variables
Variables are containers for storing data (values).
In this example, x, y, and z, are variables, declared with the var keyword:
Example:
<!DOCTYPE html>
<html>

Page 113 of 349


<body>

<h2>JavaScript Variables</h2>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>

From the example above, you can expect:


 x stores the value 5
 y stores the value 6
 z stores the value 11

Much Like Algebra


In this example, price1, price2, and total, are variables:
Example:
<!DOCTYPE html>
<html>
<body>

Page 114 of 349


<h2>JavaScript Variables</h2>

<p id="demo"></p>

<script>
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script>

</body>
</html>

In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total = price1 + price2).
From the example above, you can calculate the total to be 11.
JavaScript variables are containers for storing data values.

JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
 Names can contain letters, digits, underscores, and dollar signs.
 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

Page 115 of 349


JavaScript identifiers are case-sensitive.

The Assignment Operator


In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
This is different from algebra. The following does not make sense in algebra:
x = x + 5
In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.
(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
The "equal to" operator is written like == in JavaScript.

JavaScript Data Types


JavaScript variables can hold numbers like 100 and text values like "John Doe".
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>Strings are written with quotes.</p>


<p>Numbers are written without quotes.</p>

<p id="demo"></p>

<script>

Page 116 of 349


var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script>
</body>
</html>

Declaring (Creating) JavaScript Variables


Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var keyword:
var carName;
After the declaration, the variable has no value (technically it has the value of undefined).
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
var carName = "Volvo";
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with id="demo":
Example:
<p id="demo"></p>

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

It's a good programming practice to declare all variables at the beginning of a script.

Page 117 of 349


One Statement, Many Variables
You can declare many variables in one statement.
Start the statement with var and separate the variables by comma:
var person = "John Doe", carName = "Volvo", price = 200;

A declaration can span multiple lines:

var person = "John Doe",


carName = "Volvo",
price = 200;

Value = undefined
In computer programs, variables are often declared without a value. The value can be something that has
to be calculated, or something that will be provided later, like user input.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this statement:
Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>A variable declared without a value will have the value undefined.</p>

<p id="demo"></p>

<script>
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>

Page 118 of 349


</html>

Re-Declaring JavaScript Variables


If you re-declare a JavaScript variable, it will not lose its value.
The variable carName will still have the value "Volvo" after the execution of these statements:
Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>If you re-declare a JavaScript variable, it will not lose its value.</p>

<p id="demo"></p>

<script>
var carName = "Volvo";
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
Example:
<h2>JavaScript Variables</h2>

Page 119 of 349


<p>The result of adding 5 + 2 + 3:</p>

<p id="demo"></p>

<script>
var x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

You can also add strings, but strings will be concatenated:


Example:
<h2>JavaScript Variables</h2>

<p>The result of adding "John" + " " + "Doe":</p>

<p id="demo"></p>

<script>
var x = "John" + " " + "Doe";
document.getElementById("demo").innerHTML = x;
</script>

Also try this:


Example:
var x = "5" + 2 + 3;

If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
Now try this:
var x = 2 + 3 + "5";

JavaScript strings are used for storing and manipulating text.

Page 120 of 349


JavaScript Strings

A JavaScript string is zero or more characters written inside quotes.


Example
let text = "John Doe";
You can use single or double quotes:
Example
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

String Length
To find the length of a string, use the built-in length property:
Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text.length; // Will return 26

Escape Character
Because strings must be written within quotes, JavaScript will misunderstand this string:
let text = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".


The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:

The sequence \" inserts a double quote in a string:

Page 121 of 349


Example
let text = "We are the so-called \"Vikings\" from the north.";
The sequence \' inserts a single quote in a string:
Example
let text= 'It\'s alright.';

The sequence \\ inserts a backslash in a string:


Example
let text = "The character \\ is called backslash.";
Six other escape sequences are valid in JavaScript:

Breaking Long Code Lines


For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
You can also break up a code line within a text string with a single backslash:
Example
document.getElementById("demo").innerHTML = "Hello \
Dolly!";

Page 122 of 349


The \ method is not the preferred method. It might not have universal support.
Some browsers do not allow spaces behind the \ character.
A safer way to break up a string, is to use string addition:
Example
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
You cannot break up a code line with a backslash:
Example
document.getElementById("demo").innerHTML = \
"Hello Dolly!";

Strings Can be Objects


Normally, JavaScript strings are primitive values, created from literals:

let firstName = "John";

But strings can also be defined as objects with the keyword new:
let firstName = new String("John");
Example
let x = "John";
let y = new String("John");

// typeof x will return string


// typeof y will return object
Don't create strings as objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:
When using the == operator, equal strings are equal:
Example
let x = "John";
let y = new String("John");

// (x == y) is true because x and y have equal values


When using the === operator, equal values may not be equal, because the === operator expects equality
in both data type and value.
Example

Page 123 of 349


let x = "John";
let y = new String("John");

// (x === y) is false because x and y have different types (string and


object)
Or even worse. Objects cannot be compared:
Example
let x = new String("John");
let y = new String("John");

// (x == y) is false because x and y are objects

Example
let x = new String("John");
let y = new String("John");

// (x === y) is false because x and y are objects

Note the difference between (x==y) and (x===y).


Also note that comparing two JavaScript objects will always return false.

Exercise:
Use the length property to alert the length of txt.
let txt = "Hello World!";
let x = _________;
alert(x);

Solution:
let txt = "Hello World!";
let x = txt.length;
alert(x);
Exercise:
Concatenate the two strings to alert "Hello World!".
let str1 = "Hello ";
let str2 = "World!";

Page 124 of 349


alert( _______________);
Solution:
let str1 = "Hello ";
let str2 = "World!";
alert(str1 + str2);

JavaScript Operators

Example
Assign values to variables and add them together:
let x = 5; // assign the value 5 to x
let y = 2; // assign the value 2 to y
let z = x + y; // assign the value 7 to z (5 + 2)
The assignment operator (=) assigns a value to a variable.
Assignment:
let x = 10;
The addition operator (+) adds numbers:
Adding:
let x = 5;
let y = 2;
let z = x + y;
The multiplication operator (*) multiplies numbers.
Multiplying:
let x = 5;
let y = 2;
let z = x * y;

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic on numbers:

Operator Description

Page 125 of 349


+ Addition

- Subtraction

* Multiplication

** Exponentiation

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.

The addition assignment operator (+=) adds a value to a variable.


Assignment:
let x = 10;
x += 5;

JavaScript String Operators


The + operator can also be used to add (concatenate) strings.

Page 126 of 349


Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
The result of text3 will be:
John Doe
The += assignment operator can also be used to add (concatenate) strings:
Example
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be:
What a very nice day
When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers


Adding two numbers, will return the sum, but adding a number and a string will return a string:
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5
If you add a number and a string, the result will be a string!

JavaScript Comparison Operators

Operator Description

Page 127 of 349


== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

JavaScript Logical Operators

Operator Description

Page 128 of 349


&& logical and

|| logical or

! logical not

JavaScript Type Operators

Operator Description

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of an object type

JavaScript Bitwise Operators


Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to
a JavaScript number.

Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

Page 129 of 349


| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0001 0100 4

<< Zero fill left shift 5 << 1 0101 << 1 1010 10

>> Signed right shift 5 >> 1 0101 >> 1 0010 2

>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2

Exercise:
Alert the remainder when 15 is divided by 9.
alert(15 ___ 9);
Solution:
alert(15 % 9);

Exercise:
Use the correct assignment operator that will result in x being 15 (same as x = x + y).
x = 10;
y = 5;
x ____ y;
Solution:
x = 10;
y = 5;

Page 130 of 349


x += y;

JavaScript Arrays

JavaScript arrays are used to store multiple values in a single variable.


Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

What is an Array?
An array is a special variable, which can hold more than one value at a time.

Page 131 of 349


If you have a list of items (a list of car names, for example), storing the cars in single variables could look
like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3
cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index
number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
const array_name = [item1, item2, ...];
Example
const cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];
You can also create an array, and then provide the elements:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p id="demo"></p>

Page 132 of 349


<script>
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

Example
const cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same.
There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).

Accessing Array Elements


You access an array element by referring to the index number:
const cars = ["Saab", "Volvo", "BMW"];
let x = cars[0]; // x = "Saab"
Note: Array indexes start with 0.
[0] is the first element. [1] is the second element.

Page 133 of 349


Changing an Array Element
This statement changes the value of the first element in cars:
cars[0] = "Opel";
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array name:
Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;

Arrays are Objects


Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
const person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns John:
Object:
const person = {firstName:"John", lastName:"Doe", age:46};

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

Page 134 of 349


myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and methods:
cars.length // Returns the number of elements
cars.sort() // Sorts the array
Array methods are covered in the next chapters.

The length Property


The length property of an array returns the length of an array (the number of array elements).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // Returns 4
The length property is always one more than the highest array index.

Accessing the First Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0]; // Returns "Banana"

Accessing the Last Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length - 1]; // Returns "Mango"

Looping Array Elements


The safest way to loop through an array, is using a for loop:

Page 135 of 349


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
You can also use the Array.forEach() function:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

let text = "<ul>";


fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}

Adding Array Elements


The easiest way to add a new element to an array is using the push() method:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
WARNING !
Adding elements with high indexes can create undefined "holes" in an array:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits

Page 136 of 349


Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
Example
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"
WARNING !!
If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect results.
Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person.length; // Will return 0
person[0]; // Will return undefined

The Difference Between Arrays and Objects


In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.
Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


 JavaScript does not support associative arrays.
 You should use objects when you want the element names to be strings (text).
 You should use arrays when you want the element names to be numbers.

Page 137 of 349


JavaScript new Array()
JavaScript has a built in array constructor new Array().
But you can safely use [] instead.
These two different statements both create a new empty array named points:
const points = new Array();
const points = [];
These two different statements both create a new array containing 6 numbers:
const points = new Array(40, 100, 1, 5, 25, 10);
const points = [40, 100, 1, 5, 25, 10];
The new keyword can produce some unexpected results:
// Create an array with three elements:
const points = new Array(40, 100, 1);
// Create an array with two elements:
const points = new Array(40, 100);
// Create an array with one element ???
const points = new Array(40);
A Common Error
const points = [40];
is not the same as:
const points = New Array(40);
// Create an array with one element:
const points = [40];
// Create an array with 40 undefined elements:
const points = new Array(40);

How to Recognize an Array


A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns "object":
const fruits = ["Banana", "Orange", "Apple"];
typeof fruits; // returns object
The typeof operator returns object because a JavaScript array is an object.
Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():

Page 138 of 349


Array.isArray(fruits); // returns true
Solution 2:
The instanceof operator returns true if an object is created by a given constructor:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>The instanceof operator returns true when used on an array:</p>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple"];
document.getElementById("demo").innerHTML = fruits instanceof Array;
</script>

</body>
</html>

Exercise:
Get the value "Volvo" from the cars array.
const cars = ["Saab", "Volvo", "BMW"];
let x = ________;
Solution:
const cars = ["Saab", "Volvo", "BMW"];
let x = cars[1];

Exercise:

Page 139 of 349


Change the first item of cars to "Ford".
const cars = ["Volvo", "Jeep", "Mercedes"];
_______= "Ford";

Solution:
const cars = ["Volvo", "Jeep", "Mercedes"];
cars[0] = "Ford";

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.


A JavaScript function is executed when "something" invokes it (calls it).
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>

<script>
function myFunction(p1, p2) {
return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>

Page 140 of 349


</body>
</html>

JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
A Function is much the same as a Procedure or a Subroutine, in other programming languages.

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.

Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.

Page 141 of 349


Functions often compute a return value. The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation and returns the result:</p>

<p id="demo"></p>

<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
return a * b;
}
</script>

</body>
</html>

The result in x will be:


12

Why Functions?
You can reuse code: Define the code once, and use it many times.

Page 142 of 349


You can use the same code many times with different arguments, to produce different results.
Example
Convert Fahrenheit to Celsius:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function to convert from Fahrenheit to Celsius:</p>


<p id="demo"></p>

<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
</script>

</body>
</html>

The () Operator Invokes the Function


Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function
result.
Accessing a function without () will return the function object instead of the function result.
Example
<!DOCTYPE html>
<html>
<body>

Page 143 of 349


<h2>JavaScript Functions</h2>

<p>Accessing a function without () will return the function definition instead of the function result:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius;
</script>

</body>
</html>

Functions Used as Variable Values


Functions can be used the same way as you use variables, in all types of formulas, assignments, and
calculations.
Example
Instead of using a variable to store the return value of a function:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =

Page 144 of 349


"The temperature is " + toCelsius(77) + " Celsius";

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
</script>

</body>
</html>

Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>Outside myFunction() carName is undefined.</p>

<p id="demo1"></p>

<p id="demo2"></p>

<script>
myFunction();

function myFunction() {

Page 145 of 349


let carName = "Volvo";
document.getElementById("demo1").innerHTML =
typeof carName + " " + carName;
}

document.getElementById("demo2").innerHTML =
typeof carName;
</script>

</body>
</html>
Since local variables are only recognized inside their functions, variables with the same name can be used
in different functions.
Local variables are created when a function starts, and deleted when the function is completed.

Exercise:
Make the function return "Hello".
function myFunction() {
______ “______”;
}
document.getElementById("demo").innerHTML = myFunction();

Solution:
function myFunction() {
return “Hello”;;
}
document.getElementById("demo").innerHTML = myFunction();

Page 146 of 349


JavaScript Conditions

Conditional statements are used to perform different actions based on different conditions.

Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
 Use if to specify a block of code to be executed, if a specified condition is true
 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Example
Make a "Good day" greeting if the hour is less than 18:00:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if</h2>

<p>Display "Good day!" if the hour is less than 18:00:</p>

Page 147 of 349


<p id="demo">Good Evening!</p>

<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>

</body>
</html>

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if .. else</h2>

<p>A time-based greeting:</p>

<p id="demo"></p>

Page 148 of 349


<script>
const hour = new Date().getHours();
let greeting;

if (hour < 18) {


greeting = "Good day";
} else {
greeting = "Good evening";
}

document.getElementById("demo").innerHTML = greeting;
</script>

</body>
</html>

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a
"Good day" greeting, otherwise a "Good evening":
<!DOCTYPE html>
<html>

Page 149 of 349


<body>

<h2>JavaScript if .. else</h2>

<p>A time-based greeting:</p>

<p id="demo"></p>

<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>

</body>
</html>

JavaScript Switch Statement

The switch statement is used to perform different actions based on different conditions.

Page 150 of 349


The JavaScript Switch Statement
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.
Example
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript switch</h2>

<p id="demo"></p>

<script>
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";

Page 151 of 349


break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>

</body>
</html>

The break Keyword


When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution inside the switch block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
Note: If you omit the break statement, the next case will be executed even if the evaluation does not
match the case.

Page 152 of 349


The default Keyword
The default keyword specifies the code to run if there is no case match:
Example:
The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript switch</h2>

<p id="demo"></p>

<script>
let text;
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>

Page 153 of 349


</html>

The default case does not have to be the last case in a switch block:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript switch</h2>

<p id="demo"></p>

<script>
let text;
switch (new Date().getDay()) {
default:
text = "Looking forward to the Weekend";
break;
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Page 154 of 349


If default is not the last case in the switch block, remember to end the default case with a break.

Common Code Blocks


Sometimes you will want different switch cases to use the same code.
In this example case 4 and 5 share the same code block, and 0 and 6 share another code block:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript switch</h2>

<p id="demo"></p>

<script>
let text;
switch (new Date().getDay()) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}
document.getElementById("demo").innerHTML = text;
</script>

Page 155 of 349


</body>
</html>

Switching Details
If multiple cases matches a case value, the first case is selected.
If no matching cases are found, the program continues to the default label.
If no default label is found, the program continues to the statement(s) after the switch.

JavaScript For Loop

Loops can execute a block of code several times.

JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
Solution:

Page 156 of 349


<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

let text = "";


for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Different Kinds of Loops


JavaScript supports different kinds of loops:
 for - loops through a block of code a number of times
 for/in - loops through the properties of an object
 for/of - loops through the values of an iterable object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true

Page 157 of 349


The For Loop
The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (let i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p id="demo"></p>

<script>
let text = "";

for (let i = 0; i < 5; i++) {


text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Page 158 of 349


From the example above, you can read:
Statement 1 sets a variable before the loop starts (let i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Statement 1
Normally you will use statement 1 to initialize the variable used in the loop (let i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1 (separated by comma):
Example
for (let i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
And you can omit statement 1 (like when your values are set before the loop starts):
Example
let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
If you omit statement 2, you must provide a break inside the loop. Otherwise, the loop will never end.
This will crash your browser. Read about breaks in a later chapter of this tutorial.

Statement 3
Often statement 3 increments the value of the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is optional.
Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):

Page 159 of 349


Example
let i = 0;
let len = cars.length;
let text = "";
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}

Loop Scope
Using var in a loop:
Example
var i = 5;

for (var i = 0; i < 10; i++) {


// some code
}

// Here i is 10
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript let</h2>

<p id="demo"></p>

<script>
var i = 5;
for (var i = 0; i < 10; i++) {
// some statements
}
document.getElementById("demo").innerHTML = i;
</script>

Page 160 of 349


</body>
</html>

Using let in a loop:

Example
let i = 5;

for (let i = 0; i < 10; i++) {


// some code
}

// Here i is 5
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript let</h2>

<p id="demo"></p>

<script>
let i = 5;
for (let i = 0; i < 10; i++) {
// some statements
}
document.getElementById("demo").innerHTML = i;
</script>

</body>
</html>

Page 161 of 349


In the first example, using var, the variable declared in the loop redeclares the variable outside the loop.
In the second example, using let, the variable declared in the loop does not redeclare the variable outside
the loop.
When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.

JavaScript While Loop

Loops can execute a block of code as long as a specified condition is true.

The While Loop


The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
Example
In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less
than 10:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript While Loop</h2>

<p id="demo"></p>

<script>

Page 162 of 349


let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

If you forget to increase the variable used in the condition, the loop will never end. This will crash your
browser.

The Do While Loop


The do while loop is a variant of the while loop. This loop will execute the code block once, before checking
if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Example
The example below uses a do while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:
Example
<!DOCTYPE html>
<html>
<body>

Page 163 of 349


<h2>JavaScript Do While Loop</h2>

<p id="demo"></p>

<script>
let text = ""
let i = 0;

do {
text += "<br>The number is " + i;
i++;
}
while (i < 10);

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Do not forget to increase the variable used in the condition, otherwise the loop will never end!

Comparing For and While


If you have read the previous chapter, about the for loop, you will discover that a while loop is much the
same as a for loop, with statement 1 and statement 3 omitted.
The loop in this example uses a for loop to collect the car names from the cars array:
Example
<!DOCTYPE html>
<html>
<body>

Page 164 of 349


<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford"];

let i = 0;
let text = "";
for (;cars[i];) {
text += cars[i] + "<br>";
i++;
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

The loop in this example uses a while loop to collect the car names from the cars array:
Example
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford"];

Page 165 of 349


let i = 0;
let text = "";
while (cars[i]) {
text += cars[i] + "<br>";
i++;
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

JavaScript Objects

Real Life Objects, Properties, and Methods


In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

Object Properties Methods

Page 166 of 349


car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.

JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
let car = "Fiat";
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
const car = {type:"Fiat", model:"500", color:"white"};

The values are written as name:value pairs (name and value separated by a colon).
It is a common practice to declare objects with the const keyword.

Object Definition
You define (and create) a JavaScript object with an object literal:
Example
<!DOCTYPE html>
<html>

Page 167 of 349


<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// Display some data from the object:


document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Spaces and line breaks are not important. An object definition can span multiple lines:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:

Page 168 of 349


const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

// Display some data from the object:


document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Object Properties

The name:values pairs in JavaScript objects are called properties:

Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

Accessing Object Properties


You can access object properties in two ways:

Page 169 of 349


objectName.propertyName
or
objectName["propertyName"]
Example1
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};

// Display some data from the object:


document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>

</body>
</html>

Page 170 of 349


Example2
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};

// Display some data from the object:


document.getElementById("demo").innerHTML =
person["firstName"] + " " + person["lastName"];
</script>

</body>
</html>

Page 171 of 349


JavaScript objects are containers for named values called properties.

Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}

A method is a function stored as a property.


Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

The this Keyword


In a function definition, this refers to the "owner" of the function.

Page 172 of 349


In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.

Accessing Object Methods


You access an object method with the following syntax:
objectName.methodName()

Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a property value.</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:


document.getElementById("demo").innerHTML = person.fullName();

Page 173 of 349


</script>

</body>
</html>

If you access a method without the () parentheses, it will return the function definition:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>If you access an object method without (), it will return the function definition:</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:


document.getElementById("demo").innerHTML = person.fullName;
</script>

Page 174 of 349


</body>
</html>

Do Not Declare Strings, Numbers, and Booleans as Objects!


When a JavaScript variable is declared with the keyword "new", the variable is created as an object:
x = new String(); // Declares x as a String object
y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.

Exercise:
Alert "John" by extracting information from the person object.
const person = {
firstName: "John",
lastName: "Doe"
};
alert( ___________);

Solution:
Alert(person.firstName);

JavaScript HTML DOM

With the HTML DOM, JavaScript can access and change all the elements of an HTML document.

Page 175 of 349


The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

What is the DOM?


The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:

Page 176 of 349


 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

What is the HTML DOM?


The HTML DOM is a standard object model and programming interface for HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

JavaScript - HTML DOM Methods


HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or change.

The DOM Programming Interface


The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (like add or deleting an HTML element).

Example
The following example changes the content (the innerHTML) of the <p> element with id="demo":
<html>
<body>

<p id="demo"></p>

<script>

Page 177 of 349


document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
In the example above, getElementById is a method, while innerHTML is a property.

The getElementById Method


The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.

The innerHTML Property


The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The innerHTML property can be used to get or change any HTML element, including <html> and <body>.

The HTML DOM Document Object


The document object represents your web page.
If you want to access any element in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.

Finding HTML Elements

Method Description

Page 178 of 349


document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements

Property Description

element.innerHTML = new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML element

element.style.property = new style Change the style of an HTML element

Method Description

element.setAttribute(attribute, value) Change the attribute value of an HTML element

Adding and Deleting Elements

Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

Page 179 of 349


document.write(text) Write into the HTML output stream

Adding Events Handlers

Method Description

document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick


event

Finding HTML Objects


The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These
are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.

Property Description DOM

document.anchors Returns all <a> elements that have a name attribute 1

document.applets Deprecated 1

document.baseURI Returns the absolute base URI of the document 3

document.body Returns the <body> element 1

document.cookie Returns the document's cookie 1

Page 180 of 349


document.doctype Returns the document's doctype 3

document.documentElement Returns the <html> element 3

document.documentMode Returns the mode used by the browser 3

document.documentURI Returns the URI of the document 3

document.domain Returns the domain name of the document server 1

document.domConfig Obsolete. 3

document.embeds Returns all <embed> elements 3

document.forms Returns all <form> elements 1

document.head Returns the <head> element 3

document.images Returns all <img> elements 1

document.implementation Returns the DOM implementation 3

document.inputEncoding Returns the document's encoding (character set) 3

Page 181 of 349


document.lastModified Returns the date and time the document was updated 3

document.links Returns all <area> and <a> elements that have a href attribute 1

document.readyState Returns the (loading) status of the document 3

document.referrer Returns the URI of the referrer (the linking document) 1

document.scripts Returns all <script> elements 3

document.strictErrorChecking Returns if error checking is enforced 3

document.title Returns the <title> element 1

document.URL Returns the complete URL of the document 1

JavaScript HTML DOM Elements

This page teaches you how to find and access HTML elements in an HTML page.

Finding HTML Elements


Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are several ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections

Page 182 of 349


Finding HTML Element by Id
The easiest way to find an HTML element in the DOM, is by using the element id.
This example finds the element with id="intro":
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p id="intro">Finding HTML Elements by Id</p>


<p>This example demonstrates the <b>getElementsById</b> method.</p>

<p id="demo"></p>

<script>
const element = document.getElementById("intro");

document.getElementById("demo").innerHTML =
"The text from the intro paragraph is: " + element.innerHTML;

</script>

</body>
</html>

If the element is found, the method will return the element as an object (in myElement).
If the element is not found, myElement will contain null.

Page 183 of 349


Finding HTML Elements by Tag Name
This example finds all <p> elements:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Tag Name.</p>


<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>

<p id="demo"></p>

<script>
const element = document.getElementsByTagName("p");

document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: ' + element[0].i


nnerHTML;

</script>

</body>
</html>

This example finds the element with id="main", and then finds all <p> elements inside "main":
Example
<!DOCTYPE html>
<html>
<body>

Page 184 of 349


<h2>JavaScript HTML DOM</h2>

<div id="main">
<p>Finding HTML Elements by Tag Name</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
</div>

<p id="demo"></p>

<script>
const x = document.getElementById("main");
const y = x.getElementsByTagName("p");

document.getElementById("demo").innerHTML =
'The first paragraph (index 0) inside "main" is: ' + y[0].innerHTML;

</script>

</body>
</html>

Finding HTML Elements by Class Name


If you want to find all HTML elements with the same class name, use getElementsByClassName().
This example returns a list of all elements with class="intro".
Example
<!DOCTYPE html>
<html>
<body>

Page 185 of 349


<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Class Name.</p>


<p class="intro">Hello World!</p>
<p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>

<p id="demo"></p>

<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>

</body>
</html>

Finding HTML Elements by CSS Selectors


If you want to find all HTML elements that match a specified CSS selector (id, class names, types,
attributes, values of attributes, etc), use the querySelectorAll() method.
This example returns a list of all <p> elements with class="intro".
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Query Selector</p>


<p class="intro">Hello World!.</p>

Page 186 of 349


<p class="intro">This example demonstrates the <b>querySelectorAll</b> method.</p>

<p id="demo"></p>

<script>
const x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>

</body>
</html>

Finding HTML Elements by HTML Object Collections


This example finds the form element with id="frm1", in the forms collection, and displays all element
values:
Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>


<p>Finding HTML Elements Using <b>document.forms</b>.</p>

<form id="frm1" action="/action_page.php">


First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<input type="submit" value="Submit">
</form>

<p>These are the values of each element in the form:</p>

Page 187 of 349


<p id="demo"></p>

<script>
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

JavaScript HTML DOM - Changing HTML

The HTML DOM allows JavaScript to change the content of HTML elements.

Changing HTML Content


The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML = new HTML
This example changes the content of a <p> element:
Example
<html>
<body>

Page 188 of 349


<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

</body>
</html>
Example explained:
 The HTML document above contains a <p> element with id="p1"
 We use the HTML DOM to get the element with id="p1"
 A JavaScript changes the content (innerHTML) of that element to "New text!"
This example changes the content of an <h1> element:
Example
<!DOCTYPE html>
<html>
<body>

<h1 id="id01">Old Heading</h1>

<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>

</body>
</html>
Example explained:
 The HTML document above contains an <h1> element with id="id01"
 We use the HTML DOM to get the element with id="id01"
 A JavaScript changes the content (innerHTML) of that element to "New Heading"

Changing the Value of an Attribute


To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute = new value
This example changes the value of the src attribute of an <img> element:

Page 189 of 349


Example
<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>
Example explained:
 The HTML document above contains an <img> element with id="myImage"
 We use the HTML DOM to get the element with id="myImage"
 A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"

Dynamic HTML content


JavaScript can create dynamic HTML content:
Date : Mon Sep 27 2021 16:08:54 GMT+0200 (Central European Summer Time)
Example
<!DOCTYPE html>
<html>
<body>

<script>
document.getElementById("demo").innerHTML = "Date : " + Date(); </script>

</body>
</html>

document.write()
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example

Page 190 of 349


<!DOCTYPE html>
<html>
<body>

<p>Bla bla bla</p>

<script>
document.write(Date());
</script>

<p>Bla bla bla</p>

</body>
</html>
Never use document.write() after the document is loaded. It will overwrite the document.

JavaScript Forms

JavaScript Form Validation


HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from
being submitted:
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
The function can be called when the form is submitted:
HTML Form Example
<!DOCTYPE html>
<html>

Page 191 of 349


<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<h2>JavaScript Validation</h2>

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">


Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

JavaScript Can Validate Numeric Input


JavaScript is often used to validate numeric input:
<!DOCTYPE html>
<html>
<body>

Page 192 of 349


<h2>JavaScript Validation</h2>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
// Get the value of the input field with id="numb"
let x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Page 193 of 349


Automatic HTML Form Validation
HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from being submitted:
HTML Form Example
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>

</body>
</html>

Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Typical validation tasks are:
 has the user filled in all required fields?
 has the user entered a valid date?
 has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.

Page 194 of 349


Client side validation is performed by a web browser, before input is sent to a web server.

HTML Constraint Validation


HTML5 introduced a new HTML validation concept called constraint validation.
HTML constraint validation is based on:
 Constraint validation HTML Input Attributes
 Constraint validation CSS Pseudo Selectors
 Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes

Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

Constraint Validation CSS Pseudo Selectors

Selector Description

:disabled Selects input elements with the "disabled" attribute specified

:invalid Selects input elements with invalid values

Page 195 of 349


:optional Selects input elements with no "required" attribute specified

:required Selects input elements with the "required" attribute specified

:valid Selects input elements with valid values

Page 196 of 349


Part IV - Introduction to MySQL

What is MySQL?

 MySQL is a relational database management system


 MySQL is open-source
 MySQL is free
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, scalable, and easy to use
 MySQL is cross-platform
 MySQL is compliant with the ANSI SQL standard
 MySQL was first released in 1995
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

Who Uses MySQL?


 Huge websites like Facebook, Twitter, Airbnb, Booking.com, Uber, GitHub, YouTube, etc.
 Content Management Systems like WordPress, Drupal, Joomla!, Contao, etc.
 A very large number of web developers around the world

Show Data On Your Web Site


To build a web site that shows data from a database, you will need:
 An RDBMS database program (like MySQL)
 A server-side scripting language, like PHP
 To use SQL to get the data you want
 To use HTML / CSS to style the page

What is RDBMS?
RDBMS stands for Relational Database Management System.
RDBMS is a program used to maintain a relational database.
RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL Server, Oracle, and
Microsoft Access.
RDBMS uses SQL queries to access the data in the database.

Page 197 of 349


What is a Database Table?
A table is a collection of related data entries, and it consists of columns and rows.
A column holds specific information about every record in the table.
A record (or row) is each individual entry that exists in a table.
Look at a selection from the Northwind "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

The columns in the "Customers" table above are: CustomerID, CustomerName, ContactName, Address,
City, PostalCode and Country. The table has 5 records (rows).

What is a Relational Database?


A relational database defines database relationships in the form of tables. The tables are related to each
other - based on data common to each.
Look at the following three tables "Customers", "Orders", and "Shippers" from the Northwind database:
Customers Table
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

Page 198 of 349


4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

The relationship between the "Customers" table and the "Orders" table is the CustomerID column:
Orders Table
OrderID CustomerID EmployeeID OrderDate ShipperID

10278 5 8 1996-08-12 2

10280 5 2 1996-08-14 1

10308 2 7 1996-09-18 3

10355 4 6 1996-11-15 1

10365 3 3 1996-11-27 2

10383 4 8 1996-12-16 3

10384 5 3 1996-12-16 3

The relationship between the "Orders" table and the "Shippers" table is the ShipperID column:
Shippers Table
ShipperID ShipperName Phone

1 Speedy Express (503) 555-9831

2 United Package (503) 555-3199

3 Federal Shipping (503) 555-9931

What is SQL?
SQL is the standard language for dealing with Relational Databases.
SQL is used to insert, search, update, and delete database records.

How to Use SQL


The following SQL statement selects all the records in the "Customers" table:
Example

Page 199 of 349


SELECT * FROM Customers;

Keep in Mind That...


 SQL keywords are NOT case sensitive: select is the same as SELECT
In this tutorial we will write all SQL keywords in upper-case.

Semicolon after SQL Statements?


Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that allow more than
one SQL statement to be executed in the same call to the server.
In this tutorial, we will use semicolon at the end of each SQL statement.

Some of The Most Important SQL Commands


 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

MySQL Data Types

Each column in a database table is required to have a name and a data type.
An SQL developer must decide what type of data that will be stored inside each column when creating a
table. The data type is a guideline for SQL to understand what type of data is expected inside of each
column, and it also identifies how SQL will interact with the stored data.
In MySQL there are three main data types: string, numeric, and date and time.

Page 200 of 349


String Data Types
Data type Description

A FIXED length string (can contain letters, numbers, and special


CHAR(size) characters). The size parameter specifies the column length in characters
- can be from 0 to 255. Default is 1

A VARIABLE length string (can contain letters, numbers, and special


VARCHAR(size) characters). The size parameter specifies the maximum column length in
characters - can be from 0 to 65535

Equal to CHAR(), but stores binary byte strings. The size parameter
BINARY(size)
specifies the column length in bytes. Default is 1

Equal to VARCHAR(), but stores binary byte strings. The size parameter
VARBINARY(size)
specifies the maximum column length in bytes.

TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes

TINYTEXT Holds a string with a maximum length of 255 characters

TEXT(size) Holds a string with a maximum length of 65,535 bytes

BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters

MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data

LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters

For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of


LONGBLOB
data

A string object that can have only one value, chosen from a list of
possible values. You can list up to 65535 values in an ENUM list. If a value
ENUM(val1, val2, val3, ...)
is inserted that is not in the list, a blank value will be inserted. The values
are sorted in the order you enter them

A string object that can have 0 or more values, chosen from a list of
SET(val1, val2, val3, ...)
possible values. You can list up to 64 values in a SET list

Page 201 of 349


Numeric Data Types
Data type Description

A bit-value type. The number of bits per value is specified in size. The size
BIT(size)
parameter can hold a value from 1 to 64. The default value for size is 1.

A very small integer. Signed range is from -128 to 127. Unsigned range is
TINYINT(size) from 0 to 255. The size parameter specifies the maximum display width
(which is 255)

BOOL Zero is considered as false, nonzero values are considered as true.

BOOLEAN Equal to BOOL

A small integer. Signed range is from -32768 to 32767. Unsigned range is


SMALLINT(size) from 0 to 65535. The size parameter specifies the maximum display
width (which is 255)

A medium integer. Signed range is from -8388608 to 8388607. Unsigned


MEDIUMINT(size) range is from 0 to 16777215. The size parameter specifies the maximum
display width (which is 255)

A medium integer. Signed range is from -2147483648 to 2147483647.


INT(size) Unsigned range is from 0 to 4294967295. The size parameter specifies
the maximum display width (which is 255)

INTEGER(size) Equal to INT(size)

A large integer. Signed range is from -9223372036854775808 to


9223372036854775807. Unsigned range is from 0 to
BIGINT(size)
18446744073709551615. The size parameter specifies the maximum
display width (which is 255)

A floating point number. The total number of digits is specified in size.


The number of digits after the decimal point is specified in the d
FLOAT(size, d)
parameter. This syntax is deprecated in MySQL 8.0.17, and it will be
removed in future MySQL versions

A floating point number. MySQL uses the p value to determine whether


to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24,
FLOAT(p)
the data type becomes FLOAT(). If p is from 25 to 53, the data type
becomes DOUBLE()

A normal-size floating point number. The total number of digits is


DOUBLE(size, d) specified in size. The number of digits after the decimal point is specified
in the d parameter

Page 202 of 349


DOUBLE PRECISION(size, d)

An exact fixed-point number. The total number of digits is specified in


size. The number of digits after the decimal point is specified in the d
DECIMAL(size, d)
parameter. The maximum number for size is 65. The maximum number
for d is 30. The default value for size is 10. The default value for d is 0.

DEC(size, d) Equal to DECIMAL(size,d)

Note: All the numeric data types may have an extra option: UNSIGNED or ZEROFILL. If you add the
UNSIGNED option, MySQL disallows negative values for the column. If you add the ZEROFILL option,
MySQL automatically also adds the UNSIGNED attribute to the column.

Date and Time Data Types


Data type Description

A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01'


DATE
to '9999-12-31'

A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The


supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
DATETIME(fsp)
Adding DEFAULT and ON UPDATE in the column definition to get
automatic initialization and updating to the current date and time

A timestamp. TIMESTAMP values are stored as the number of seconds


since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD
hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC to
TIMESTAMP(fsp) '2038-01-09 03:14:07' UTC. Automatic initialization and updating to the
current date and time can be specified using DEFAULT
CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the
column definition

A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to


TIME(fsp)
'838:59:59'

A year in four-digit format. Values allowed in four-digit format: 1901 to


YEAR 2155, and 0000.
MySQL 8.0 does not support year in two-digit format.

MySQL Database

Page 203 of 349


The MySQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL database.
Syntax
CREATE DATABASE databasename;

CREATE DATABASE Example


The following SQL statement creates a database called "testDB":
Example
CREATE DATABASE testDB;
Tip: Make sure you have admin privilege before creating any database. Once a database is created, you
can check it in the list of databases with the following SQL command: SHOW DATABASES;

The MySQL DROP DATABASE Statement

The DROP DATABASE statement is used to drop an existing SQL database.


Syntax
DROP DATABASE databasename;
Note: Be careful before dropping a database. Deleting a database will result in loss of complete
information stored in the database!

DROP DATABASE Example


The following SQL statement drops the existing database "testDB":
Example
DROP DATABASE testDB;

The MySQL CREATE TABLE Statement

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

Page 204 of 349


Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).
Tip: For an overview of the available data types, go to our complete Data Types Reference.

MySQL CREATE TABLE Example


The following example creates a table called "Persons" that contains five columns: PersonID, LastName,
FirstName, Address, and City:
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The PersonID column is of type int and will hold an integer.
The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the
maximum length for these fields is 255 characters.
The empty "Persons" table will now look like this:

PersonID LastName FirstName Address City

Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement.

Create Table Using Another Table


A copy of an existing table can also be created using CREATE TABLE.
The new table gets the same column definitions. All columns or specific columns can be selected.

Page 205 of 349


If you create a new table using an existing table, the new table will be filled with the existing values from
the old table.
Syntax
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
The following SQL creates a new table called "TestTables" (which is a copy of the "Customers" table):
Example
CREATE TABLE TestTable AS
SELECT customername, contactname
FROM customers;

The MySQL DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a database.

Syntax
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of complete information stored
in the table!

MySQL DROP TABLE Example


The following SQL statement drops the existing table "Shippers":
Example
DROP TABLE Shippers;

MySQL TRUNCATE TABLE

The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.
Syntax
TRUNCATE TABLE table_name;

Page 206 of 349


MySQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

ALTER TABLE - ADD Column


To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;
The following SQL adds an "Email" column to the "Customers" table:
Example
ALTER TABLE Customers
ADD Email varchar(255);

ALTER TABLE - DROP COLUMN


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;
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;

ALTER TABLE - MODIFY COLUMN


To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;

Page 207 of 349


MySQL ALTER TABLE Example
Look at the "Persons" table:

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:
Example
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 look like this:

ID LastName FirstName Address City DateOfBirth

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

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:
Example
ALTER TABLE Persons
MODIFY COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or four-digit
format.

Page 208 of 349


DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
Example
ALTER TABLE Persons
DROP COLUMN DateOfBirth;
The "Persons" table will now look like this:

ID LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger

MySQL Constraints

SQL constraints are used to specify rules for data in a table.

Create Constraints
Constraints can be specified when the table is created with the CREATE TABLE statement, or after the
table is created with the ALTER TABLE statement.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

Page 209 of 349


MySQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data action, the
action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table level
constraints apply to the whole table.
The following constraints are commonly used in SQL:
 NOT NULL - Ensures that a column cannot have a NULL value
 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a
table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the database very quickly

MySQL Statements

The MySQL SELECT Statement


The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.

SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to
select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;

The MySQL SELECT DISTINCT Statement


The SELECT DISTINCT statement is used to return only distinct (different) values.

Page 210 of 349


Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...
FROM table_name;

The MySQL WHERE Clause


The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.

WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!

Operators in The WHERE Clause


The following operators can be used in the WHERE clause:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

Not equal. Note: In some versions of SQL this operator may be written as
<>
!=

Page 211 of 349


BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

Bottom of Form

The MySQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending
order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

ORDER BY Several Columns Example 2


The following SQL statement selects all customers from the "Customers" table, sorted ascending by the
"Country" and descending by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;

The MySQL INSERT INTO Statement


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

INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two ways:

Page 212 of 349


1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

2. If you are adding values for all the columns of the table, you do not need to specify the column names
in the SQL query. However, make sure the order of the values is in the same order as the columns in the
table. Here, the INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);

What is a NULL Value?


A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a
value to this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value
is one that has been left blank during record creation!

How to Test for NULL Values?

It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL Syntax


SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

Page 213 of 349


The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

The IS NOT NULL Operator


The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;

The MySQL UPDATE Statement


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

UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement.
The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all
records in the table will be updated!

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

Page 214 of 349


CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and
a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

UPDATE Multiple Records


It is the WHERE clause that determines how many records will be updated.

Page 215 of 349


The following SQL statement will update the PostalCode to 00000 for all records where country is
"Mexico":
Example
UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';
The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 00000 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 00000 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Example
UPDATE Customers
SET PostalCode = 00000;
The selection from the "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Alfred Schmidt Obere Str. 57 Frankfurt 00000 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 00000 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 00000 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London 00000 UK

Page 216 of 349


The MySQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The
WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in
the table will be deleted!

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

SQL DELETE Example


The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
The "Customers" table will now look like this:

CustomerID CustomerName ContactName Address City PostalCode Country

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Page 217 of 349


Antonio Moreno Antonio México
3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

Delete All Records


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_name;
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
Example
DELETE FROM Customers;
Top of Form

The MySQL LIMIT Clause


The LIMIT clause is used to specify the number of records to return.
The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records
can impact performance.
LIMIT Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Page 218 of 349


Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

MySQL LIMIT Examples


The following SQL statement selects the first three records from the "Customers" table:
Example
SELECT * FROM Customers
LIMIT 3;

ADD a WHERE CLAUSE


The following SQL statement selects the first three records from the "Customers" table, where the country
is "Germany":
Example
SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;

The MySQL GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary rows, like "find the
number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG())
to group the result-set by one or more columns.

Page 219 of 349


GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

MySQL GROUP BY Examples

Example
The following SQL statement lists the number of customers in each country:

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country;

Example

Page 220 of 349


The following SQL statement lists the number of customers in each country, sorted high to low:

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

MySQL Operators

The MySQL AND, OR and NOT Operators


The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
 The AND operator displays a record if all the conditions separated by AND are TRUE.
 The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

AND Example

Page 221 of 349


The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is
"Berlin":
Example
SELECT * FROM Customers
WHERE Country = 'Germany' AND City = 'Berlin';

OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "Stuttgart":
Example
SELECT * FROM Customers
WHERE City = 'Berlin' OR City = 'Stuttgart';
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
Example
SELECT * FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';

NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
Example
SELECT * FROM Customers
WHERE NOT Country = 'Germany';

Combining AND, OR and NOT


You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city
must be "Berlin" OR "Stuttgart" (use parenthesis to form complex expressions):
Example
SELECT * FROM Customers
WHERE Country = 'Germany' AND (City = 'Berlin' OR City = 'Stuttgart');

The MySQL LIKE Operator


The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:

Page 222 of 349


 The percent sign (%) represents zero, one, or multiple characters
 The underscore sign (_) represents one, single character
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"

WHERE CustomerName LIKE


Finds any values that have "or" in any position
'%or%'

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position

Finds any values that start with "a" and are at least 2 characters in
WHERE CustomerName LIKE 'a_%'
length

WHERE CustomerName LIKE Finds any values that start with "a" and are at least 3 characters in
'a__%' length

WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"

Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

Page 223 of 349


4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

Blauer See
6 Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
Delikatessen

Frédérique
7 Blondel père et fils 24, place Kléber Strasbourg 67000 France
Citeaux

Bólido Comidas Martín


8 C/ Araquil, 67 Madrid 28023 Spain
preparadas Sommer

Laurence 12, rue des


9 Bon app' Marseille 13008 France
Lebihans Bouchers

Bottom-Dollar Elizabeth 23 Tsawassen


10 Tsawassen T2F 8M4 Canada
Marketse Lincoln Blvd.

Victoria
11 B's Beverages Fauntleroy Circus London EC2 5NT UK
Ashworth

SQL LIKE Examples


Example
The following SQL statement selects all customers with a CustomerName starting with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';

Example
The following SQL statement selects all customers with a CustomerName ending with "a":

SELECT * FROM Customers


WHERE CustomerName LIKE '%a';
Example
The following SQL statement selects all customers with a CustomerName that have "or" in any position:

Page 224 of 349


SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
Example
The following SQL statement selects all customers with a CustomerName that have "r" in the second
position:

SELECT * FROM Customers


WHERE CustomerName LIKE '_r%';
Example
The following SQL statement selects all customers with a CustomerName that starts with "a" and are at
least 3 characters in length:

SELECT * FROM Customers


WHERE CustomerName LIKE 'a__%';
Example
The following SQL statement selects all customers with a ContactName that starts with "a" and ends with
"o":

SELECT * FROM Customers


WHERE ContactName LIKE 'a%o';

Example
The following SQL statement selects all customers with a CustomerName that does NOT start with "a":

SELECT * FROM Customers


WHERE CustomerName NOT LIKE 'a%';

MySQL Wildcard Characters

A wildcard character is used to substitute one or more characters in a string.


Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to
search for a specified pattern in a column.

Page 225 of 349


Wildcard Characters in MySQL
Symbol Description Example

% Represents zero or more characters bl% finds bl, black, blue, and blob

_ Represents a single character h_t finds hot, hat, and hit

The wildcards can also be used in combinations!


Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"

WHERE CustomerName LIKE '%a' Finds any values that ends with "a"

WHERE CustomerName LIKE


Finds any values that have "or" in any position
'%or%'

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position

WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3 characters in
'a_%_%' length

WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"

Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo Avda. de la


México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Page 226 of 349


Berglunds Christina
5 Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp Berglund

Blauer See
6 Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
Delikatessen

Frédérique
7 Blondel père et fils 24, place Kléber Strasbourg 67000 France
Citeaux

Bólido Comidas Martín


8 C/ Araquil, 67 Madrid 28023 Spain
preparadas Sommer

Laurence 12, rue des


9 Bon app' Marseille 13008 France
Lebihans Bouchers

Bottom-Dollar Elizabeth 23 Tsawassen


10 Tsawassen T2F 8M4 Canada
Marketse Lincoln Blvd.

Victoria Fauntleroy
11 B's Beverages London EC2 5NT UK
Ashworth Circus

Cactus Comidas Patricio Buenos


12 Cerrito 333 1010 Argentina
para llevar Simpson Aires

Centro comercial Francisco Sierras de México


13 05022 Mexico
Moctezuma Chang Granada 9993 D.F.

14 Chop-suey Chinese Yang Wang Hauptstr. 29 Bern 3012 Switzerland

Av. dos Lusíadas,


15 Comércio Mineiro Pedro Afonso São Paulo 05432-043 Brazil
23

Berkeley
Consolidated Elizabeth
16 Gardens 12 London WX1 6LT UK
Holdings Brown
Brewery

Drachenblut
17 Sven Ottlieb Walserweg 21 Aachen 52066 Germany
Delikatessend

67, rue des


Janine
18 Du monde entier Cinquante Nantes 44000 France
Labrune
Otages

19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK

Roland
20 Ernst Handel Kirchgasse 6 Graz 8010 Austria
Mendel

Page 227 of 349


21 Familia Arquibaldo Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil

FISSA Fabrica Inter. C/ Moralzarzal,


22 Diego Roel Madrid 28034 Spain
Salchichas S.A. 86

184, chaussée de
23 Folies gourmandes Martine Rancé Lille 59000 France
Tournai

24 Folk och fä HB Maria Larsson Åkergatan 24 Bräcke S-844 67 Sweden

Using the % Wildcard


Example
The following SQL statement selects all customers with a City starting with "ber":

SELECT * FROM Customers


WHERE City LIKE 'ber%';
Example
The following SQL statement selects all customers with a City containing the pattern "es":

SELECT * FROM Customers


WHERE City LIKE '%es%';

Using the _ Wildcard


Example
The following SQL statement selects all customers with a City starting with any character, followed by
"ondon":

SELECT * FROM Customers


WHERE City LIKE '_ondon';

Example
The following SQL statement selects all customers with a City starting with "L", followed by any character,
followed by "n", followed by any character, followed by "on":

Page 228 of 349


SELECT * FROM Customers
WHERE City LIKE 'L_n_on';

The MySQL IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.


The IN operator is a shorthand for multiple OR conditions.

IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);

Demo Database
The table below shows the complete "Customers" table from the Northwind sample database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund

Page 229 of 349


Blauer See
6 Hanna Moos Forsterstr. 57 Mannheim 68306 Germany
Delikatessen

Frédérique
7 Blondel père et fils 24, place Kléber Strasbourg 67000 France
Citeaux

Bólido Comidas Martín


8 C/ Araquil, 67 Madrid 28023 Spain
preparadas Sommer

Laurence 12, rue des


9 Bon app' Marseille 13008 France
Lebihans Bouchers

Bottom-Dollar Elizabeth 23 Tsawassen


10 Tsawassen T2F 8M4 Canada
Marketse Lincoln Blvd.

Victoria
11 B's Beverages Fauntleroy Circus London EC2 5NT UK
Ashworth

IN Operator Examples
Example
The following SQL statement selects all customers that are located in "Germany", "France" or "UK":
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
Example
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":

SELECT * FROM Customers


WHERE Country NOT IN ('Germany', 'France', 'UK');

Example
The following SQL statement selects all customers that are from the same countries as the suppliers:

SELECT * FROM Customers


WHERE Country IN (SELECT Country FROM Suppliers);

Page 230 of 349


The MySQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

Demo Database
Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun Seasoning 1 2 48 - 6 oz jars 22

5 Chef Anton's Gumbo Mix 1 2 36 boxes 21.35

BETWEEN Example

Example
The following SQL statement selects all products with a price between 10 and 20:

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20;

Page 231 of 349


NOT BETWEEN Example
Example
To display the products outside the range of the previous example, use NOT BETWEEN:

SELECT * FROM Products


WHERE Price NOT BETWEEN 10 AND 20;

BETWEEN with IN Example


Example
The following SQL statement selects all products with a price between 10 and 20. In addition; do not show
products with a CategoryID of 1,2, or 3:

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

BETWEEN Text Values Example

Example
The following SQL statement selects all products with a ProductName between "Carnarvon Tigers" and
"Mozzarella di Giovanni":

SELECT * FROM Products


WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Example
The following SQL statement selects all products with a ProductName between "Carnarvon Tigers" and
"Chef Anton's Cajun Seasoning":

SELECT * FROM Products


WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;

Page 232 of 349


NOT BETWEEN Text Values Example
Example
The following SQL statement selects all products with a ProductName not between "Carnarvon Tigers"
and "Mozzarella di Giovanni":

SELECT * FROM Products


WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

Sample Table
Below is a selection from the "Orders" table in the Northwind sample database:

OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 7/4/1996 3

10249 81 6 7/5/1996 1

10250 34 4 7/8/1996 2

10251 84 3 7/9/1996 1

10252 76 4 7/10/1996 2

BETWEEN Dates Example


Example
The following SQL statement selects all orders with an OrderDate between '01-July-1996' and '31-July-
1996':

SELECT * FROM Orders


WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

Page 233 of 349


MySQL Arithmetic Operators

Operator Description

+ Add

- Subtract

* Multiply

/ Divide

% Modulo

MySQL Bitwise Operators

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

MySQL Comparison Operators

Operator Description

= Equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

<> Not equal to

Page 234 of 349


MySQL Compound Operators

Operator Description

+= Add equals

-= Subtract equals

*= Multiply equals

/= Divide equals

%= Modulo equals

&= Bitwise AND equals

^-= Bitwise exclusive equals

|*= Bitwise OR equals

MySQL Logical Operators

Operator Description

ALL TRUE if all of the subquery values meet the condition

AND TRUE if all the conditions separated by AND is TRUE

ANY TRUE if any of the subquery values meet the condition

BETWEEN TRUE if the operand is within the range of comparisons

EXISTS TRUE if the subquery returns one or more records

IN TRUE if the operand is equal to one of a list of expressions

LIKE TRUE if the operand matches a pattern

NOT Displays a record if the condition(s) is NOT TRUE

OR TRUE if any of the conditions separated by OR is TRUE

Page 235 of 349


SOME TRUE if any of the subquery values meet the condition

MySQL Joins

MySQL Joining Tables


A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico

3 Antonio Moreno Taquería Antonio Moreno Mexico

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers"
table. The relationship between the two tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that
have matching values in both tables:

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
and it will produce something like this:

Page 236 of 349


OrderID CustomerName OrderDate

10308 Ana Trujillo Emparedados y helados 9/18/1996

10365 Antonio Moreno Taquería 11/27/1996

10383 Around the Horn 12/16/1996

10355 Around the Horn 11/15/1996

10278 Berglunds snabbköp 8/12/1996

Supported Types of Joins in MySQL


 INNER JOIN: Returns records that have matching values in both tables
 LEFT JOIN: Returns all records from the left table, and the matched records from the right table
 RIGHT JOIN: Returns all records from the right table, and the matched records from the left table
 CROSS JOIN: Returns all records from both tables

MySQL INNER JOIN Keyword

The INNER JOIN keyword selects records that have matching values in both tables.

INNER JOIN Syntax


SELECT column_name(s)
FROM table1

Page 237 of 349


INNER JOIN table2
ON table1.column_name = table2.column_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

And a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo Avda. de la


México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

MySQL INNER JOIN Example


Example
The following SQL statement selects all orders with customer information:

SELECT Orders.OrderID, Customers.CustomerName


FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Page 238 of 349


Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the
columns. If there are records in the "Orders" table that do not have matches in "Customers", these orders
will not be shown!

JOIN Three Tables


Example
The following SQL statement selects all orders with customer and shipper information:
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

MySQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records (if any)
from the right table (table2).

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

Page 239 of 349


1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo Avda. de la


México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

MySQL LEFT JOIN Example

Example
The following SQL statement will select all customers, and any orders they might have:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

MySQL RIGHT JOIN Keyword

The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records (if
any) from the left table (table1).

Page 240 of 349


RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

And a selection from the "Employees" table:

EmployeeID LastName FirstName BirthDate Photo

1 Davolio Nancy 12/8/1968 EmpID1.pic

2 Fuller Andrew 2/19/1952 EmpID2.pic

3 Leverling Janet 8/30/1963 EmpID3.pic

MySQL RIGHT JOIN Example


Example
The following SQL statement will return all employees, and any orders they might have placed:
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

Page 241 of 349


SQL CROSS JOIN Keyword

The CROSS JOIN keyword returns all records from both tables (table1 and table2).

CROSS JOIN Syntax


SELECT column_name(s)
FROM table1
CROSS JOIN table2;
Note: CROSS JOIN can potentially return very large result-sets!

Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

Ana Trujillo Avda. de la


México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

And a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

Page 242 of 349


MySQL CROSS JOIN Example
Example
The following SQL statement selects all customers, and all orders:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders;

Example
Note: The CROSS JOIN keyword returns all matching records from both tables whether the other table
matches or not. So, if there are rows in "Customers" that do not have matches in "Orders", or if there are
rows in "Orders" that do not have matches in "Customers", those rows will be listed as well.
If you add a WHERE clause (if table1 and table2 has a relationship), the CROSS JOIN will produce the same
result as the INNER JOIN clause:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
CROSS JOIN Orders
WHERE Customers.CustomerID=Orders.CustomerID;

MySQL Functions

MySQL has many built-in functions.


This reference contains string, numeric, date, and some advanced functions in MySQL.

MySQL String Functions

Function Description

ASCII Returns the ASCII value for the specific character

CHAR_LENGTH Returns the length of a string (in characters)

CHARACTER_LENGTH Returns the length of a string (in characters)

CONCAT Adds two or more expressions together

Page 243 of 349


CONCAT_WS Adds two or more expressions together with a separator

FIELD Returns the index position of a value in a list of values

FIND_IN_SET Returns the position of a string within a list of strings

Formats a number to a format like "#,###,###.##", rounded to a specified


FORMAT
number of decimal places

Inserts a string within a string at the specified position and for a certain
INSERT
number of characters

INSTR Returns the position of the first occurrence of a string in another string

LCASE Converts a string to lower-case

LEFT Extracts a number of characters from a string (starting from left)

LENGTH Returns the length of a string (in bytes)

LOCATE Returns the position of the first occurrence of a substring in a string

LOWER Converts a string to lower-case

LPAD Left-pads a string with another string, to a certain length

LTRIM Removes leading spaces from a string

MID Extracts a substring from a string (starting at any position)

POSITION Returns the position of the first occurrence of a substring in a string

REPEAT Repeats a string as many times as specified

REPLACE Replaces all occurrences of a substring within a string, with a new substring

REVERSE Reverses a string and returns the result

RIGHT Extracts a number of characters from a string (starting from right)

RPAD Right-pads a string with another string, to a certain length

RTRIM Removes trailing spaces from a string

SPACE Returns a string of the specified number of space characters

STRCMP Compares two strings

SUBSTR Extracts a substring from a string (starting at any position)

SUBSTRING Extracts a substring from a string (starting at any position)

Page 244 of 349


SUBSTRING_INDEX Returns a substring of a string before a specified number of delimiter occurs

TRIM Removes leading and trailing spaces from a string

UCASE Converts a string to upper-case

UPPER Converts a string to upper-case

MySQL Numeric Functions

Function Description

ABS Returns the absolute value of a number

ACOS Returns the arc cosine of a number

ASIN Returns the arc sine of a number

ATAN Returns the arc tangent of one or two numbers

ATAN2 Returns the arc tangent of two numbers

AVG Returns the average value of an expression

CEIL Returns the smallest integer value that is >= to a number

CEILING Returns the smallest integer value that is >= to a number

COS Returns the cosine of a number

COT Returns the cotangent of a number

COUNT Returns the number of records returned by a select query

DEGREES Converts a value in radians to degrees

DIV Used for integer division

EXP Returns e raised to the power of a specified number

FLOOR Returns the largest integer value that is <= to a number

GREATEST Returns the greatest value of the list of arguments

LEAST Returns the smallest value of the list of arguments

LN Returns the natural logarithm of a number

Page 245 of 349


Returns the natural logarithm of a number, or the logarithm of a number to a
LOG
specified base

LOG10 Returns the natural logarithm of a number to base 10

LOG2 Returns the natural logarithm of a number to base 2

MAX Returns the maximum value in a set of values

MIN Returns the minimum value in a set of values

MOD Returns the remainder of a number divided by another number

PI Returns the value of PI

POW Returns the value of a number raised to the power of another number

POWER Returns the value of a number raised to the power of another number

RADIANS Converts a degree value into radians

RAND Returns a random number

ROUND Rounds a number to a specified number of decimal places

SIGN Returns the sign of a number

SIN Returns the sine of a number

SQRT Returns the square root of a number

SUM Calculates the sum of a set of values

TAN Returns the tangent of a number

TRUNCATE Truncates a number to the specified number of decimal places

MySQL Date Functions

Function Description

ADDDATE Adds a time/date interval to a date and then returns the date

ADDTIME Adds a time interval to a time/datetime and then returns the time/datetime

CURDATE Returns the current date

CURRENT_DATE Returns the current date

CURRENT_TIME Returns the current time

Page 246 of 349


CURRENT_TIMESTAMP Returns the current date and time

CURTIME Returns the current time

DATE Extracts the date part from a datetime expression

DATEDIFF Returns the number of days between two date values

DATE_ADD Adds a time/date interval to a date and then returns the date

DATE_FORMAT Formats a date

DATE_SUB Subtracts a time/date interval from a date and then returns the date

DAY Returns the day of the month for a given date

DAYNAME Returns the weekday name for a given date

DAYOFMONTH Returns the day of the month for a given date

DAYOFWEEK Returns the weekday index for a given date

DAYOFYEAR Returns the day of the year for a given date

EXTRACT Extracts a part from a given date

FROM_DAYS Returns a date from a numeric datevalue

HOUR Returns the hour part for a given date

LAST_DAY Extracts the last day of the month for a given date

LOCALTIME Returns the current date and time

LOCALTIMESTAMP Returns the current date and time

MAKEDATE Creates and returns a date based on a year and a number of days value

MAKETIME Creates and returns a time based on an hour, minute, and second value

MICROSECOND Returns the microsecond part of a time/datetime

MINUTE Returns the minute part of a time/datetime

MONTH Returns the month part for a given date

MONTHNAME Returns the name of the month for a given date

NOW Returns the current date and time

PERIOD_ADD Adds a specified number of months to a period

Page 247 of 349


PERIOD_DIFF Returns the difference between two periods

QUARTER Returns the quarter of the year for a given date value

SECOND Returns the seconds part of a time/datetime

SEC_TO_TIME Returns a time value based on the specified seconds

STR_TO_DATE Returns a date based on a string and a format

SUBDATE Subtracts a time/date interval from a date and then returns the date

SUBTIME Subtracts a time interval from a datetime and then returns the time/datetime

SYSDATE Returns the current date and time

TIME Extracts the time part from a given time/datetime

TIME_FORMAT Formats a time by a specified format

TIME_TO_SEC Converts a time value into seconds

TIMEDIFF Returns the difference between two time/datetime expressions

TIMESTAMP Returns a datetime value based on a date or datetime value

TO_DAYS Returns the number of days between a date and date "0000-00-00"

WEEK Returns the week number for a given date

WEEKDAY Returns the weekday number for a given date

WEEKOFYEAR Returns the week number for a given date

YEAR Returns the year part for a given date

YEARWEEK Returns the year and week number for a given date

MySQL Advanced Functions

Function Description

BIN Returns a binary representation of a number

BINARY Converts a value to a binary string

CASE Goes through conditions and return a value when the first condition is met

CAST Converts a value (of any type) into a specified datatype

Page 248 of 349


COALESCE Returns the first non-null value in a list

CONNECTION_ID Returns the unique connection ID for the current connection

CONV Converts a number from one numeric base system to another

CONVERT Converts a value into the specified datatype or character set

Returns the user name and host name for the MySQL account that the server
CURRENT_USER
used to authenticate the current client

DATABASE Returns the name of the current database

IF Returns a value if a condition is TRUE, or another value if a condition is FALSE

Return a specified value if the expression is NULL, otherwise return the


IFNULL
expression

ISNULL Returns 1 or 0 depending on whether an expression is NULL

Returns the AUTO_INCREMENT id of the last row that has been inserted or
LAST_INSERT_ID
updated in a table

Compares two expressions and returns NULL if they are equal. Otherwise, the
NULLIF
first expression is returned

SESSION_USER Returns the current MySQL user name and host name

SYSTEM_USER Returns the current MySQL user name and host name

USER Returns the current MySQL user name and host name

VERSION Returns the current version of the MySQL database

MySQL Stored Procedures

MySQL stored procedures introduction

Page 249 of 349


The following CREATE PROCEDURE statement creates a new stored procedure that wraps the query
above:
DELIMITER $$

CREATE PROCEDURE GetCustomers()


BEGIN
SELECT
customerName,
city,
state,
postalCode,
country
FROM
customers
ORDER BY customerName;
END$$
DELIMITER ;

By definition, a stored procedure is a segment of declarative SQL statements stored inside the MySQL
Server. In this example, we have just created a stored procedure with the name GetCustomers().
Once you save the stored procedure, you can invoke it by using the CALL statement:
CALL GetCustomers();

And the statement returns the same result as the query.


The first time you invoke a stored procedure, MySQL looks up for the name in the database catalog,
compiles the stored procedure’s code, place it in a memory area known as a cache, and execute the stored
procedure.
If you invoke the same stored procedure in the same session again, MySQL just executes the stored
procedure from the cache without having to recompile it.
A stored procedure can have parameters so you can pass values to it and get the result back. For example,
you can have a stored procedure that returns customers by country and city. In this case, the country and
city are parameters of the stored procedure.
A stored procedure may contain control flow statements such as IF, CASE, and LOOP that allow you to
implement the code in the procedural way.
A stored procedure can call other stored procedures or stored functions, which allows you to modulize
your code.

MySQL stored procedures advantages


The following are the advantages of stored procedures.
Reduce network traffic
Stored procedures help reduce the network traffic between applications and MySQL Server. Because
instead of sending multiple lengthy SQL statements, applications have to send only the name and
parameters of stored procedures.

Page 250 of 349


Centralize business logic in the database
You can use the stored procedures to implement business logic that is reusable by multiple applications.
The stored procedures help reduce the efforts of duplicating the same logic in many applications and
make your database more consistent.
Make database more secure
The database administrator can grant appropriate privileges to applications that only access specific
stored procedures without giving any privileges on the underlying tables.

MySQL stored procedures disadvantages


Besides those advantages, stored procedures also have disadvantages:
Resource usages
If you use many stored procedures, the memory usage of every connection will increase substantially.
Besides, overusing a large number of logical operations in the stored procedures will increase the CPU
usage because the MySQL is not well-designed for logical operations.
Troubleshooting
It’s difficult to debug stored procedures. Unfortunately, MySQL does not provide any facilities to debug
stored procedures like other enterprise database products such as Oracle and SQL Server.
Maintenances
Developing and maintaining stored procedures often requires a specialized skill set that not all application
developers possess. This may lead to problems in both application development and maintenance.
In this tutorial, you have learned about the MySQL stored procedures, their advantages, and
disadvantages. Let’s move on to learn how to create a new stored procedure in MySQL.

MySQL Delimiter

Summary: in this tutorial, you will learn how to change the default MySQL delimiter by using the
DELIMITER command.
When writing SQL statements, you use the semicolon (;) to separate two statements like the following
example:
SELECT * FROM products;

SELECT * FROM customers;

A MySQL client program such as MySQL Workbench or mysql program uses the delimiter (;) to separate
statements and executes each statement separately.
However, a stored procedure consists of multiple statements separated by a semicolon (;).

Page 251 of 349


If you use a MySQL client program to define a stored procedure that contains semicolon characters, the
MySQL client program will not treat the whole stored procedure as a single statement, but many
statements.
Therefore, you must redefine the delimiter temporarily so that you can pass the whole stored procedure
to the server as a single statement.
To redefine the default delimiter, you use the DELIMITER command:
DELIMITER delimiter_character

The delimiter_character may consist of a single character or multiple characters e.g., // or $$. However,
you should avoid using the backslash (\) because it’s the escape character in MySQL.
For example, the following statement changes the current delimiter to //:
DELIMITER //
Once changing the delimiter, you can use the new delimiter to end a statement as follows:
DELIMITER //

SELECT * FROM customers //

SELECT * FROM products //


To change the delimiter to the default one, which is a semicolon (;), you use the following statement:
DELIMITER ;

Using MySQL DELIMITER for stored procedures


Typically, a stored procedure contains multiple statements separated by semicolons (;). To compile the
whole stored procedure as a single compound statement, you need to temporarily change the delimiter
from the semicolon (;) to another delimiter such as $$ or //:
DELIMITER $$

CREATE PROCEDURE sp_name()


BEGIN
-- statements
END $$

DELIMITER ;

MySQL CREATE PROCEDURE statement

This query returns all products in the products table from the sample database.
SELECT * FROM products;

Page 252 of 349


The following statement creates a new stored procedure that wraps the query:
DELIMITER //

CREATE PROCEDURE GetAllProducts()


BEGIN
SELECT * FROM products;
END //

DELIMITER ;

Executing a stored procedure


To execute a stored procedure, you use the CALL statement:
CALL stored_procedure_name(argument_list);

In this syntax, you specify the name of the stored procedure after the CALL keyword. If the stored
procedure has parameters, you need to pass arguments inside parentheses following the stored
procedure name.
This example illustrates how to call the GetAllProducts() stored procedure:
CALL GetAllProducts();

MySQL DROP PROCEDURE statement

The DROP PROCEDURE statement deletes a stored procedure created by the CREATE PROCEDURE
statement.
The following shows the syntax of the DROP PROCEDURE statement:
DROP PROCEDURE [IF EXISTS] stored_procedure_name;

In this syntax:
 First, specify the name of the stored procedure that you want to remove after the DROP
PROCEDURE keywords.
 Second, use IF EXISTS option to conditionally drop the stored procedure if it exists.
When you drop a procedure that does not exist without using the IF EXISTS option, MySQL issues an error.
In this case, if you use the IF EXISTS option, MySQL issues a warning instead.
Note that you need to have the ALTER ROUTINE privilege of the stored procedure in order to remove it.

Page 253 of 349


MySQL DROP PROCEDURE examples
Let’s take some examples of using the DROP PROCEDURE statement.
1) Using MySQL DROP PROCEDURE example
First, create a new stored procedure that returns employee and office information:
DELIMITER $$

CREATE PROCEDURE GetEmployees()


BEGIN
SELECT
firstName,
lastName,
city,
state,
country
FROM employees
INNER JOIN offices using (officeCode);

END$$

DELIMITER ;

Second, use the DROP PROCEDURE to delete the GetEmployees() stored procedure:
DROP PROCEDURE GetEmployees;

2) Using MySQL DROP PROCEDURE with the IF EXISTS option example


The following example drops a stored procedure that does not exist:
DROP PROCEDURE abc;

MySQL issued the following error:


Error Code: 1305. PROCEDURE classicmodels.abc does not exist

This statement drops the same non-existing stored procedure, but with IF EXISTS option:
DROP PROCEDURE IF EXISTS abc;

This time MySQL issued a warning.


0 row(s) affected, 1 warning(s): 1305 PROCEDURE classicmodels.abc does not exist

The statement SHOW WARNINGS shows the warning:


SHOW WARNINGS;

Page 254 of 349


MySQL stored procedure parameters

Often, stored procedures have parameters. The parameters make the stored procedure more useful and
reusable. A parameter in a stored procedure has one of three modes: IN,OUT, or INOUT.

IN parameters
IN is the default mode. When you define an IN parameter in a stored procedure, the calling program has
to pass an argument to the stored procedure.
In addition, the value of an IN parameter is protected. It means that even you change the value of the IN
parameter inside the stored procedure, its original value is unchanged after the stored procedure ends.
In other words, the stored procedure only works on the copy of the IN parameter.

OUT parameters
The value of an OUT parameter can be changed inside the stored procedure and its new value is passed
back to the calling program.
Notice that the stored procedure cannot access the initial value of the OUT parameter when it starts.

INOUT parameters
An INOUT parameter is a combination of IN and OUT parameters. It means that the calling program may
pass the argument, and the stored procedure can modify the INOUT parameter, and pass the new value
back to the calling program.

Defining a parameter
Here is the basic syntax of defining a parameter in stored procedures:
[IN | OUT | INOUT] parameter_name datatype[(length)]

In this syntax,
 First, specify the parameter mode, which can be IN , OUT or INOUT depending on the purpose of
the parameter in the stored procedure.
 Second, specify the name of the parameter. The parameter name must follow the naming rules
of the column name in MySQL.
 Third, specify the data type and maximum length of the parameter.

MySQL stored procedure parameter examples


Let’s take some examples of using stored procedure parameters.

Page 255 of 349


The IN parameter example
The following example creates a stored procedure that finds all offices that locate in a country specified
by the input parameter countryName:
DELIMITER //

CREATE PROCEDURE GetOfficeByCountry(


IN countryName VARCHAR(255)
)
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //

DELIMITER ;

In this example, the countryName is the IN parameter of the stored procedure.


Suppose that you want to find offices locating in the USA, you need to pass an argument (USA) to the
stored procedure as shown in the following query:
CALL GetOfficeByCountry('USA');

To find offices in France, you pass the literal string France to the GetOfficeByCountry stored procedure as
follows:
CALL GetOfficeByCountry('France')

Because the countryName is the IN parameter, you must pass an argument. If you don’t do so, you’ll get
an error:
CALL GetOfficeByCountry();

Here’s the error:


Error Code: 1318. Incorrect number of arguments for PROCEDURE
classicmodels.GetOfficeByCountry; expected 1, got 0
Code language: JavaScript (javascript)
The OUT parameter example
The following stored procedure returns the number of orders by order status.
DELIMITER $$

CREATE PROCEDURE GetOrderCountByStatus (


IN orderStatus VARCHAR(25),

Page 256 of 349


OUT total INT
)
BEGIN
SELECT COUNT(orderNumber)
INTO total
FROM orders
WHERE status = orderStatus;
END$$

DELIMITER ;

The stored procedure GetOrderCountByStatus() has two parameters:


 The orderStatus: is the IN parameter specifies the status of orders to return.
 The total: is the OUT parameter that stores the number of orders in a specific status.
To find the number of orders that already shipped, you call GetOrderCountByStatus and pass the order
status as of Shipped, and also pass a session variable ( @total ) to receive the return value.
CALL GetOrderCountByStatus('Shipped',@total);
SELECT @total;

To get the number of orders that are in-process, you call the stored procedure GetOrderCountByStatus as
follows:
CALL GetOrderCountByStatus('in process',@total);
SELECT @total AS total_in_process;

The INOUT parameter example


The following example demonstrates how to use an INOUT parameter in a stored procedure:
DELIMITER $$

CREATE PROCEDURE SetCounter(


INOUT counter INT,
IN inc INT
)
BEGIN
SET counter = counter + inc;
END$$

DELIMITER ;
In this example, the stored procedure SetCounter() accepts one INOUT parameter ( counter ) and one IN
parameter ( inc ). It increases the counter ( counter ) by the value of specified by the inc parameter.
These statements illustrate how to call the SetSounter stored procedure:

Page 257 of 349


SET @counter = 1;
CALL SetCounter(@counter,1); -- 2
CALL SetCounter(@counter,1); -- 3
CALL SetCounter(@counter,5); -- 8
SELECT @counter; -- 8
Here is the output:

Declaring variables

To declare a variable inside a stored procedure, you use the DECLARE statement as follows:
DECLARE variable_name datatype(size) [DEFAULT default_value];

In this syntax:
 First, specify the name of the variable after the DECLARE keyword. The variable name must follow
the naming rules of MySQL table column names.
 Second, specify the data type and length of the variable. A variable can have any MySQL data
types such as INT, VARCHAR , and DATETIME.
 Third, assign a variable a default value using the DEFAULT option. If you declare a variable without
specifying a default value, its value is NULL.
The following example declares a variable named totalSale with the data type DEC(10,2) and default value
0.0 as follows:
DECLARE totalSale DEC(10,2) DEFAULT 0.0;

MySQL allows you to declare two or more variables that share the same data type using a single DECLARE
statement. The following example declares two integer variables x and y, and set their default values to
zero.
DECLARE x, y INT DEFAULT 0;

Assigning variables
Once a variable is declared, it is ready to use. To assign a variable a value, you use the SET statement:
SET variable_name = value;

For example:
DECLARE total INT DEFAULT 0;
SET total = 10;

The value of the total variable is 10 after the assignment.

Page 258 of 349


In addition to the SET statement, you can use the SELECT INTO statement to assign the result of a query
to a variable as shown in the following example:
DECLARE productCount INT DEFAULT 0;

SELECT COUNT(*)
INTO productCount
FROM products;

In this example:
 First, declare a variable named productCount and initialize its value to 0.
 Then, use the SELECT INTO statement to assign the productCount variable the number of
products selected from the products table.

Variable scopes
A variable has its own scope that defines its lifetime. If you declare a variable inside a stored procedure,
it will be out of scope when the END statement of stored procedure reaches.
When you declare a variable inside the block BEGIN END, it will be out of scope if the END is reached.
MySQL allows you to declare two or more variables that share the same name in different scopes. Because
a variable is only effective in its scope. However, declaring variables with the same name in different
scopes is not good programming practice.
A variable whose name begins with the @ sign is a session variable. It is available and accessible until the
session ends.

Putting it all together


The following example illustrates how to declare and use a variable in a stored procedure:
DELIMITER $$

CREATE PROCEDURE GetTotalOrder()


BEGIN
DECLARE totalOrder INT DEFAULT 0;

SELECT COUNT(*)
INTO totalOrder
FROM orders;

SELECT totalOrder;
END$$

DELIMITER ;

Page 259 of 349


How it works.
First, declare a variable totalOrder with a default value of zero. This variable will hold the number of orders
from the orders table.
DECLARE totalOrder INT DEFAULT 0;

Second, use the SELECT INTO statement to assign the variable totalOrder the number of orders selected
from the orders table:

SELECT COUNT(*)
INTO totalOrder
FROM orders;

Third, select the value of the variable totalOrder.


SELECT totalOrder;

Note that you will learn how to use variables practically in the subsequent tutorials. The example in this
tutorial is just an illustration so that you understand the concept.
This statement calls the stored procedure GetTotalOrder():
CALL GetTotalOrder();

Here is the output:

MySQL simple IF-THEN statement

The IF-THEN statement allows you to execute a set of SQL statements based on a specified condition. The
following illustrates the syntax of the IF-THEN statement:
IF condition THEN
statements;
END IF;
Code language: SQL (Structured Query Language) (sql)
In this syntax:
 First, specify a condition to execute the code between the IF-THEN and END IF . If the condition
evaluates to TRUE, the statements between IF-THEN and END IF will execute. Otherwise, the
control is passed to the next statement following the END IF.
 Second, specify the code that will execute if the condition evaluates to TRUE.

Page 260 of 349


We’ll use the customers table from the sample database for the demonstration:

See the following GetCustomerLevel() stored procedure.


DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(


IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL(10,2) DEFAULT 0;

SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;

IF credit > 50000 THEN


SET pCustomerLevel = 'PLATINUM';
END IF;
END$$

DELIMITER ;

The stored procedure GetCustomerLevel() accepts two parameters: pCustomerNumber and


pCustomerLevel.

Page 261 of 349


 First, select creditLimit of the customer specified by the pCustomerNumber from the customers
table and store it in the local variable credit.
 Then, set value for the OUT parameter pCustomerLevel to PLATINUM if the credit limit of the
customer is greater than 50,000.

This statement finds all customers that have a credit limit greater than 50,000:
SELECT
customerNumber,
creditLimit
FROM
customers
WHERE
creditLimit > 50000
ORDER BY
creditLimit DESC;
Here is the partial output:

These statements call the GetCustomerLevel() stored procedure for customer 141 and show the value of
the OUT parameter pCustomerLevel:
CALL GetCustomerLevel(141, @level);
SELECT @level;

Because the customer 141 has a credit limit greater than 50,000, its level is set to PLATINUM as expected.

Page 262 of 349


MySQL IF-THEN-ELSE statement

In case you want to execute other statements when the condition in the IF branch does not evaluate to
TRUE, you can use the IF-THEN-ELSE statement as follows:
IF condition THEN
statements;
ELSE
else-statements;
END IF;
In this syntax, if the condition evaluates to TRUE, the statements between IF-THEN and ELSE execute.
Otherwise, the else-statements between the ELSE and END IF execute.
Let’s modify the GetCustomerLevel() stored procedure.
First, drop the GetCustomerLevel() stored procedure:
DROP PROCEDURE GetCustomerLevel;
Code language: SQL (Structured Query Language) (sql)

Then, create the GetCustomerLevel() stored procedure with the new code:
DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(


IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL DEFAULT 0;

SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;

IF credit > 50000 THEN


SET pCustomerLevel = 'PLATINUM';
ELSE
SET pCustomerLevel = 'NOT PLATINUM';
END IF;
END$$

DELIMITER ;

In this new stored procedure, we include the ELSE branch. If the credit is not greater than 50,000, we set
the customer level to NOT PLATINUM in the block between ELSE and END IF.

MySQL IF-THEN-ELSEIF-ELSE statement

If you want to execute statements conditionally based on multiple conditions, you use the following IF-
THEN-ELSEIF-ELSE statement:

Page 263 of 349


IF condition THEN
statements;
ELSEIF elseif-condition THEN
elseif-statements;
...
ELSE
else-statements;
END IF;

In this syntax, if the condition evaluates to TRUE , the statements in the IF-THEN branch executes;
otherwise, the next elseif-condition is evaluated.
If the elseif-condition evaluates to TRUE, the elseif-statement executes; otherwise, the next elseif-
condition is evaluated.
The IF-THEN-ELSEIF-ELSE statement can have multiple ELSEIF branches.
If no condition in the IF and ELSE IF evaluates to TRUE, the else-statements in the ELSE branch will execute.
We will modify the GetCustomerLevel() stored procedure to use the IF-THEN-ELSEIF-ELSE statement.
Example
DELIMITER $$

CREATE PROCEDURE GetCustomerLevel(


IN pCustomerNumber INT,
OUT pCustomerLevel VARCHAR(20))
BEGIN
DECLARE credit DECIMAL DEFAULT 0;

SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;

IF credit > 50000 THEN


SET pCustomerLevel = 'PLATINUM';
ELSEIF credit <= 50000 AND credit > 10000 THEN
SET pCustomerLevel = 'GOLD';
ELSE
SET pCustomerLevel = 'SILVER';
END IF;
END $$

DELIMITER ;

In this stored procedure:


 If the credit is greater than 50,000, the level of the customer is PLATINUM.
 If the credit is less than or equal 50,000 and greater than 10,000, then the level of customer is
GOLD.
 Otherwise, the level of the customer is SILVER.

Page 264 of 349


CASE statement

The following is the basic syntax of the simple CASE statement:


CASE case_value
WHEN when_value1 THEN statements
WHEN when_value2 THEN statements
...
[ELSE else-statements]
END CASE;
Code language: SQL (Structured Query Language) (sql)]

In this syntax, the simple CASE statement sequentially compares the case_value is with the when_value1,
when_value2, … until it finds one is equal. When the CASE finds a case_value equal to a when_value, it
executes statements in the corresponding THEN clause.
If CASE cannot find any when_value equal to the case_value, it executes the else-statements in the ELSE
clause if the ELSE clause is available.
When the ELSE clause does not exist and the CASE cannot find any when_value equal to the case_value,
it issues an error:
Case not found for CASE statement
Code language: PHP (php)

Note that the case_value can be a literal value or an expression. The statements can be one or more SQL
statements, and cannot have zero statement.
To avoid the error when the case_value does not equal any when_value, you can use an empty BEGIN
END block in the ELSE clause as follows:
CASE case_value
WHEN when_value1 THEN ...
WHEN when_value2 THEN ...
ELSE
BEGIN
END;
END CASE;
Code language: SQL (Structured Query Language) (sql)

The simple CASE statement tests for equality ( =), you cannot use it to test equality with NULL; because
NULL = NULL returns FALSE.

Simple CASE statement example


The following stored procedure illustrates how to use the simple CASE statement:
DELIMITER $$

Page 265 of 349


CREATE PROCEDURE GetCustomerShipping(
IN pCustomerNUmber INT,
OUT pShipping VARCHAR(50)
)
BEGIN
DECLARE customerCountry VARCHAR(100);

SELECT
country
INTO customerCountry FROM
customers
WHERE
customerNumber = pCustomerNUmber;

CASE customerCountry
WHEN 'USA' THEN
SET pShipping = '2-day Shipping';
WHEN 'Canada' THEN
SET pShipping = '3-day Shipping';
ELSE
SET pShipping = '5-day Shipping';
END CASE;
END$$

DELIMITER ;
How it works.
The GetCustomerShipping() stored procedure accepts two parameters: pCustomerNumber as an IN
parameter and pShipping as an OUT parameter.
In the stored procedure:
First, select the country of the customer from the customers table by the input customer number.
Second, use the simple CASE statement to determine the shipping time based on the country of the
customer. If the customer locates in USA , the shipping time is 2-day shipping . If the customer locates in
Canada , the shipping time is 3-day shipping . The customers from other countries have 5-day shipping .
The following flowchart demonstrates the logic of the CASE statement for determining the shipping time:

Page 266 of 349


HomeWorks

MySQL Create Table [20 exercises with solution]


1. Write a SQL statement to create a simple table countries including columns country_id,country_name
and region_id.
Click me to see the solution

Page 267 of 349


2. Write a SQL statement to create a simple table countries including columns country_id,country_name
and region_id which is already exists.
Click me to see the solution
3. Write a SQL statement to create the structure of a table dup_countries similar to countries.
Click me to see the solution
4. Write a SQL statement to create a duplicate copy of countries table including structure and data by
name dup_countries.
Click me to see the solution
5. Write a SQL statement to create a table countries set a constraint NOT NULL.
Click me to see the solution
6. Write a SQL statement to create a table named jobs including columns job_id, job_title, min_salary,
max_salary and check whether the max_salary amount exceeding the upper limit 25000.
Click me to see the solution
7. Write a SQL statement to create a table named countries including columns country_id, country_name
and region_id and make sure that no countries except Italy, India and China will be entered in the table.
Click me to see the solution
8. Write a SQL statement to create a table named job_histry including columns employee_id, start_date,
end_date, job_id and department_id and make sure that the value against column end_date will be
entered at the time of insertion to the format like '--/--/----'.
Click me to see the solution
9. Write a SQL statement to create a table named countries including columns country_id,country_name
and region_id and make sure that no duplicate data against column country_id will be allowed at the time
of insertion.
Click me to see the solution
10. Write a SQL statement to create a table named jobs including columns job_id, job_title, min_salary
and max_salary, and make sure that, the default value for job_title is blank and min_salary is 8000 and
max_salary is NULL will be entered automatically at the time of insertion if no value assigned for the
specified columns.
Click me to see the solution
11. Write a SQL statement to create a table named countries including columns country_id, country_name
and region_id and make sure that the country_id column will be a key field which will not contain any
duplicate data at the time of insertion.
Click me to see the solution
12. Write a SQL statement to create a table countries including columns country_id, country_name and
region_id and make sure that the column country_id will be unique and store an auto incremented value.
Click me to see the solution

Page 268 of 349


13. Write a SQL statement to create a table countries including columns country_id, country_name and
region_id and make sure that the combination of columns country_id and region_id will be unique.
Click me to see the solution
14. Write a SQL statement to create a table job_history including columns employee_id, start_date,
end_date, job_id and department_id and make sure that, the employee_id column does not contain any
duplicate value at the time of insertion and the foreign key column job_id contain only those values which
are exists in the jobs table.
Here is the structure of the table jobs;
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| JOB_ID | varchar(10) | NO | PRI | | |
| JOB_TITLE | varchar(35) | NO | | NULL | |
| MIN_SALARY | decimal(6,0) | YES | | NULL | |
| MAX_SALARY | decimal(6,0) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
Click me to see the solution
15. Write a SQL statement to create a table employees including columns employee_id, first_name,
last_name, email, phone_number hire_date, job_id, salary, commission, manager_id and department_id
and make sure that, the employee_id column does not contain any duplicate value at the time of insertion
and the foreign key columns combined by department_id and manager_id columns contain only those
unique combination values, which combinations are exists in the departments table.
Assume the structure of departments table below.
+-----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| DEPARTMENT_ID | decimal(4,0) | NO | PRI | 0 | |
| DEPARTMENT_NAME | varchar(30) | NO | | NULL | |
| MANAGER_ID | decimal(6,0) | NO | PRI | 0 | |
| LOCATION_ID | decimal(4,0) | YES | | NULL | |
+-----------------+--------------+------+-----+---------+-------+
Click me to see the solution
16. Write a SQL statement to create a table employees including columns employee_id, first_name,
last_name, email, phone_number hire_date, job_id, salary, commission, manager_id and department_id
and make sure that, the employee_id column does not contain any duplicate value at the time of insertion,
and the foreign key column department_id, reference by the column department_id of departments
table, can contain only those values which are exists in the departments table and another foreign key
column job_id, referenced by the column job_id of jobs table, can contain only those values which are
exists in the jobs table. The InnoDB Engine have been used to create the tables.
"A foreign key constraint is not required merely to join two tables. For storage engines other than InnoDB,
it is possible when defining a column to use a REFERENCES tbl_name(col_name) clause, which has no
actual effect, and serves only as a memo or comment to you that the column which you are currently
defining is intended to refer to a column in another table." - Reference dev.mysql.com
Assume that the structure of two tables departments and jobs.

Page 269 of 349


+-----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| DEPARTMENT_ID | decimal(4,0) | NO | PRI | 0 | |
| DEPARTMENT_NAME | varchar(30) | NO | | NULL | |
| MANAGER_ID | decimal(6,0) | YES | | NULL | |

| LOCATION_ID | decimal(4,0) | YES | | NULL | |


+-----------------+--------------+------+-----+---------+-------+

+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| JOB_ID | varchar(10) | NO | PRI | | |
| JOB_TITLE | varchar(35) | NO | | NULL | |
| MIN_SALARY | decimal(6,0) | YES | | NULL | |
| MAX_SALARY | decimal(6,0) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
Click me to see the solution
17. Write a SQL statement to create a table employees including columns employee_id, first_name,
last_name, job_id, salary and make sure that, the employee_id column does not contain any duplicate
value at the time of insertion, and the foreign key column job_id, referenced by the column job_id of jobs
table, can contain only those values which are exists in the jobs table. The InnoDB Engine have been used
to create the tables. The specialty of the statement is that, The ON UPDATE CASCADE action allows you
to perform cross-table update and ON DELETE RESTRICT action reject the deletion. The default action is
ON DELETE RESTRICT.
Assume that the structure of the table jobs and InnoDB Engine have been used to create the table jobs.
CREATE TABLE IF NOT EXISTS jobs (
JOB_ID integer NOT NULL UNIQUE PRIMARY KEY,
JOB_TITLE varchar(35) NOT NULL DEFAULT ' ',
MIN_SALARY decimal(6,0) DEFAULT 8000,
MAX_SALARY decimal(6,0) DEFAULT NULL
)ENGINE=InnoDB;

+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| JOB_ID | int(11) | NO | PRI | NULL | |
| JOB_TITLE | varchar(35) | NO | | | |
| MIN_SALARY | decimal(6,0) | YES | | 8000 | |
| MAX_SALARY | decimal(6,0) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
Click me to see the solution
18. Write a SQL statement to create a table employees including columns employee_id, first_name,
last_name, job_id, salary and make sure that, the employee_id column does not contain any duplicate
value at the time of insertion, and the foreign key column job_id, referenced by the column job_id of jobs
table, can contain only those values which are exists in the jobs table. The InnoDB Engine have been used
to create the tables. The specialty of the statement is that, The ON DELETE CASCADE that lets you allow

Page 270 of 349


to delete records in the employees(child) table that refer to a record in the jobs(parent) table when the
record in the parent table is deleted and the ON UPDATE RESTRICT actions reject any updates.
Assume that the structure of the table jobs and InnoDB Engine have been used to create the table jobs.
CREATE TABLE IF NOT EXISTS jobs (
JOB_ID integer NOT NULL UNIQUE PRIMARY KEY,
JOB_TITLE varchar(35) NOT NULL DEFAULT ' ',
MIN_SALARY decimal(6,0) DEFAULT 8000,
MAX_SALARY decimal(6,0) DEFAULT NULL
)ENGINE=InnoDB;

+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| JOB_ID | int(11) | NO | PRI | NULL | |
| JOB_TITLE | varchar(35) | NO | | | |
| MIN_SALARY | decimal(6,0) | YES | | 8000 | |
| MAX_SALARY | decimal(6,0) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
Click me to see the solution
19. Write a SQL statement to create a table employees including columns employee_id, first_name,
last_name, job_id, salary and make sure that, the employee_id column does not contain any duplicate
value at the time of insertion, and the foreign key column job_id, referenced by the column job_id of jobs
table, can contain only those values which are exists in the jobs table. The InnoDB Engine have been used
to create the tables. The specialty of the statement is that, The ON DELETE SET NULL action will set the
foreign key column values in the child table(employees) to NULL when the record in the parent table(jobs)
is deleted, with a condition that the foreign key column in the child table must accept NULL values and
the ON UPDATE SET NULL action resets the values in the rows in the child table(employees) to NULL values
when the rows in the parent table(jobs) are updated.
Assume that the structure of two table jobs and InnoDB Engine have been used to create the table jobs.
CREATE TABLE IF NOT EXISTS jobs (
JOB_ID integer NOT NULL UNIQUE PRIMARY KEY,
JOB_TITLE varchar(35) NOT NULL DEFAULT ' ',
MIN_SALARY decimal(6,0) DEFAULT 8000,
MAX_SALARY decimal(6,0) DEFAULT NULL
)ENGINE=InnoDB;

+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| JOB_ID | int(11) | NO | PRI | NULL | |
| JOB_TITLE | varchar(35) | NO | | | |
| MIN_SALARY | decimal(6,0) | YES | | 8000 | |
| MAX_SALARY | decimal(6,0) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
Click me to see the solution
20. Write a SQL statement to create a table employees including columns employee_id, first_name,
last_name, job_id, salary and make sure that, the employee_id column does not contain any duplicate

Page 271 of 349


value at the time of insertion, and the foreign key column job_id, referenced by the column job_id of jobs
table, can contain only those values which are exists in the jobs table. The InnoDB Engine have been used
to create the tables. The specialty of the statement is that, The ON DELETE NO ACTION and the ON UPDATE
NO ACTION actions will reject the deletion and any updates.
Assume that the structure of two table jobs and InnoDB Engine have been used to create the table jobs.
CREATE TABLE IF NOT EXISTS jobs (
JOB_ID integer NOT NULL UNIQUE PRIMARY KEY,
JOB_TITLE varchar(35) NOT NULL DEFAULT ' ',
MIN_SALARY decimal(6,0) DEFAULT 8000,
MAX_SALARY decimal(6,0) DEFAULT NULL
)ENGINE=InnoDB;

+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| JOB_ID | int(11) | NO | PRI | NULL | |
| JOB_TITLE | varchar(35) | NO | | | |
| MIN_SALARY | decimal(6,0) | YES | | 8000 | |
| MAX_SALARY | decimal(6,0) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
Click me to see the solution

MySQL Insert Rows into the Table [14 exercises with solution]
1. Write a SQL statement to insert a record with your own value into the table countries against each
columns.
Here in the following is the structure of the table countries.
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| COUNTRY_ID | varchar(2) | YES | | NULL | |
| COUNTRY_NAME | varchar(40) | YES | | NULL | |
| REGION_ID | decimal(10,0) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+
Click me to see the solution
2. Write a SQL statement to insert one row into the table countries against the column country_id and
country_name.
Here in the following is the structure of the table countries.
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| COUNTRY_ID | varchar(2) | YES | | NULL | |
| COUNTRY_NAME | varchar(40) | YES | | NULL | |
| REGION_ID | decimal(10,0) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+

Page 272 of 349


Click me to see the solution
3. Write a SQL statement to create duplicate of countries table named country_new with all structure and
data.
Here in the following is the structure of the table countries.
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| COUNTRY_ID | varchar(2) | YES | | NULL | |
| COUNTRY_NAME | varchar(40) | YES | | NULL | |
| REGION_ID | decimal(10,0) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+
Click me to see the solution
4. Write a SQL statement to insert NULL values against region_id column for a row of countries table.
Click me to see the solution
5. Write a SQL statement to insert 3 rows by a single insert statement.
Click me to see the solution
6. Write a SQL statement insert rows from country_new table to countries table.
Here is the rows for country_new table. Assume that, the countries table is empty.
+------------+--------------+-----------+
| COUNTRY_ID | COUNTRY_NAME | REGION_ID |
+------------+--------------+-----------+
| C0001 | India | 1001 |
| C0002 | USA | 1007 |
| C0003 | UK | 1003 |
+------------+--------------+-----------+
Click me to see the solution
7. Write a SQL statement to insert one row in jobs table to ensure that no duplicate value will be entered
in the job_id column.
Click me to see the solution
8. Write a SQL statement to insert one row in jobs table to ensure that no duplicate value will be entered
in the job_id column.
Click me to see the solution
9. Write a SQL statement to insert a record into the table countries to ensure that, a country_id and
region_id combination will be entered once in the table.
Click me to see the solution
10. Write a SQL statement to insert rows into the table countries in which the value of country_id column
will be unique and auto incremented.
Click me to see the solution

Page 273 of 349


11. Write a SQL statement to insert records into the table countries to ensure that the country_id column
will not contain any duplicate data and this will be automatically incremented and the column
country_name will be filled up by 'N/A' if no value assigned for that column.
Click me to see the solution
12. Write a SQL statement to insert rows in the job_history table in which one column job_id is containing
those values which are exists in job_id column of jobs table.
Click me to see the solution
13. Write a SQL statement to insert rows into the table employees in which a set of columns
department_id and manager_id contains a unique value and that combined values must have exists into
the table departments.
Click me to see the solution
14. Write a SQL statement to insert rows into the table employees in which a set of columns
department_id and job_id contains the values which must have exists into the table departments and
jobs.
Click me to see the solution

Structure of 'hr' database:

Page 274 of 349


MySQL Update Table [ 9 exercises with solution]
1. Write a SQL statement to change the email column of employees table with 'not available' for all
employees.
Here is the sample table employees.
Check employees table on hr-db.sql
Click me to see the solution
2. Write a SQL statement to change the email and commission_pct column of employees table with 'not
available' and 0.10 for all employees.
Here is the sample table employees.
Check employees table on hr-db.sql

Click me to see the solution


3. Write a SQL statement to change the email and commission_pct column of employees table with 'not
available' and 0.10 for those employees whose department_id is 110.
Here is the sample table employees.
Check employees table on hr-db.sql

Click me to see the solution


4. Write a SQL statement to change the email column of employees table with 'not available' for those
employees whose department_id is 80 and gets a commission is less than .20%
Here is the sample table employees.
Check employees table on hr-db.sql

Click me to see the solution


5. Write a SQL statement to change the email column of employees table with 'not available' for those
employees who belongs to the 'Accouning' department.
Here is the sample table employees.
Check employees table on hr-db.sql
Here is the sample table departments.
Check departments table on hr-db.sql
Click me to see the solution
6. Write a SQL statement to change salary of employee to 8000 whose ID is 105, if the existing salary is
less than 5000.

Page 275 of 349


Here is the sample table employees.
Check employees table on hr-db.sql
Click me to see the solution
7. Write a SQL statement to change job ID of employee which ID is 118, to SH_CLERK if the employee
belongs to department, which ID is 30 and the existing job ID does not start with SH.
Here is the sample table employees.
Check employees table on hr-db.sql
Click me to see the solution
8. Write a SQL statement to increase the salary of employees under the department 40, 90 and 110
according to the company rules that, salary will be increased by 25% for the department 40, 15% for
department 90 and 10% for the department 110 and the rest of the departments will remain same.
Here is the sample table employees.
Check employees table on hr-db.sql
Click me to see the solution
9. Write a SQL statement to increase the minimum and maximum salary of PU_CLERK by 2000 as well as
the salary for those employees by 20% and commission percent by .10.
Here is the sample table employees.
Check employees table on hr-db.sql
Here is the sample table jobs.
Check jobs table on hr-db.sql
Click me to see the solution

MySQL Alter Table [15 exercises with solution]


1. Write a SQL statement to rename the table countries to country_new.
Click me to see the solution
2. Write a SQL statement to add a column region_id to the table locations.
Click me to see the solution
3. Write a SQL statement to add a columns ID as the first column of the table locations.
Click me to see the solution
4. Write a SQL statement to add a column region_id after state_province to the table locations.
Click me to see the solution
5. Write a SQL statement change the data type of the column country_id to integer in the table locations.

Page 276 of 349


Click me to see the solution
6. Write a SQL statement to drop the column city from the table locations.
Click me to see the solution
7. Write a SQL statement to change the name of the column state_province to state, keeping the data
type and size same.
Click me to see the solution
8. Write a SQL statement to add a primary key for the columns location_id in the locations table.
Here is the sample table employees.
Sample table: employees (check hr-db.sql)
Click me to see the solution
9. Write a SQL statement to add a primary key for a combination of columns location_id and country_id.
Click me to see the solution
10. Write a SQL statement to drop the existing primary from the table locations on a combination of
columns location_id and country_id.
Click me to see the solution
11. Write a SQL statement to add a foreign key on job_id column of job_history table referencing to the
primary key job_id of jobs table.
Click me to see the solution
12. Write a SQL statement to add a foreign key constraint named fk_job_id on job_id column of
job_history table referencing to the primary key job_id of jobs table.
Click me to see the solution
13. Write a SQL statement to drop the existing foreign key fk_job_id from job_history table on job_id
column which is referencing to the job_id of jobs table.
Click me to see the solution
14. Write a SQL statement to add an index named indx_job_id on job_id column in the table job_history.
Click me to see the solution
15. Write a SQL statement to drop the index indx_job_id from job_history table.
Click me to see the solution

Page 277 of 349


Basic SELECT statement [19 exercises with solution]
Reference tables on hr-db.sql database.
1. Write a query to display the names (first_name, last_name) using alias name “First Name", "Last Name"
Sample table: employees
Click me to see the solution
2. Write a query to get unique department ID from employee table.
Sample table: employees
Click me to see the solution
3. Write a query to get all employee details from the employee table order by first name, descending.Go
to the editor
Sample table: employees
Click me to see the solution
4. Write a query to get the names (first_name, last_name), salary, PF of all the employees (PF is calculated
as 15% of salary).Go to the editor
Sample table: employees
Click me to see the solution
5. Write a query to get the employee ID, names (first_name, last_name), salary in ascending order of
salary.Go to the editor
Sample table: employees
Click me to see the solution
6. Write a query to get the total salaries payable to employees.Go to the editor
Sample table: employees

Click me to see the solution


7. Write a query to get the maximum and minimum salary from employees table.Go to the editor
Sample table: employees

Click me to see the solution


8. Write a query to get the average salary and number of employees in the employees table.Go to the
editor

Page 278 of 349


Sample table: employees
Click me to see the solution
9. Write a query to get the number of employees working with the company.Go to the editor
Sample table: employees
Click me to see the solution
10. Write a query to get the number of jobs available in the employees table. Go to the editor
Sample table: employees
Click me to see the solution
11. Write a query get all first name from employees table in upper case. Go to the editor
Sample table: employees
Click me to see the solution
12. Write a query to get the first 3 characters of first name from employees table.
Sample table: employees
Click me to see the solution
13. Write a query to calculate 171*214+625. Go to the editor
Click me to see the solution
14. Write a query to get the names (for example Ellen Abel, Sundar Ande etc.) of all the employees from
employees table. Go to the editor
Sample table: employees
Click me to see the solution
15. Write a query to get first name from employees table after removing white spaces from both side. Go
to the editor
Sample table: employees
Click me to see the solution
16. Write a query to get the length of the employee names (first_name, last_name) from employees table.
Go to the editor
Sample table: employees
Click me to see the solution
17. Write a query to check if the first_name fields of the employees table contains numbers. Go to the
editor
Sample table: employees
Click me to see the solution
18. Write a query to select first 10 records from a table. Go to the editor

Page 279 of 349


Sample table: employees
Click me to see the solution
19. Write a query to get monthly salary (round 2 decimal places) of each and every employee Go to the
editor
Note : Assume the salary field provides the 'annual salary' information.
Sample table: employees
Click me to see the solution

MySQL Restricting and Sorting data: [11 exercises with solution]


Reference tables on hr-db.sql database.
1. Write a query to display the name (first_name, last_name) and salary for all employees whose salary is
not in the range $10,000 through $15,000. Go to the editor
Sample table: employees
Click me to see the solution
2. Write a query to display the name (first_name, last_name) and department ID of all employees in
departments 30 or 100 in ascending order. Go to the editor
Sample table: employees
Click me to see the solution
3. Write a query to display the name (first_name, last_name) and salary for all employees whose salary is
not in the range $10,000 through $15,000 and are in department 30 or 100. Go to the editor
Sample table: employees
Click me to see the solution
4. Write a query to display the name (first_name, last_name) and hire date for all employees who were
hired in 1987. Go to the editor
Sample table: employees
Click me to see the solution
5. Write a query to display the first_name of all employees who have both "b" and "c" in their first name.
Go to the editor
Sample table: employees
Click me to see the solution
6. Write a query to display the last name, job, and salary for all employees whose job is that of a
Programmer or a Shipping Clerk, and whose salary is not equal to $4,500, $10,000, or $15,000. Go to the
editor

Page 280 of 349


Sample table: employees
Click me to see the solution
7. Write a query to display the last name of employees whose names have exactly 6 characters. Go to the
editor
Sample table: employees
Click me to see the solution
8. Write a query to display the last name of employees having 'e' as the third character. Go to the editor
Sample table: employees
Click me to see the solution
9. Write a query to display the jobs/designations available in the employees table.Go to the editor
Sample table: employees
Click me to see the solution
10. Write a query to display the name (first_name, last_name), salary and PF (15% of salary) of all
employees. Go to the editor
Sample table: employees
Click me to see the solution
11. Write a query to select all record from employees where last name in 'BLAKE', 'SCOTT', 'KING' and
'FORD'. Go to the editor
Sample table: employees
Click me to see the solution

Aggregate Functions and Group by [14 exercises with solution]


Reference tables on hr-db.sql database.
1. Write a query to list the number of jobs available in the employees table. Go to the editor
Sample table: employees
Click me to see the solution
2. Write a query to get the total salaries payable to employees. Go to the editor
Sample table: employees
Click me to see the solution
3. Write a query to get the minimum salary from employees table. Go to the editor
Sample table: employees

Page 281 of 349


Click me to see the solution
4. Write a query to get the maximum salary of an employee working as a Programmer. Go to the editor
Sample table: employees
Click me to see the solution
5. Write a query to get the average salary and number of employees working the department 90. Go to
the editor
Sample table: employees
Click me to see the solution
6. Write a query to get the highest, lowest, sum, and average salary of all employees. Go to the editor
Sample table: employees
Click me to see the solution
7. Write a query to get the number of employees with the same job. Go to the editor
Sample table: employees
Click me to see the solution
8. Write a query to get the difference between the highest and lowest salaries. Go to the editor
Sample table: employees
Click me to see the solution
9. Write a query to find the manager ID and the salary of the lowest-paid employee for that manager. Go
to the editor
Sample table: employees
Click me to see the solution
10. Write a query to get the department ID and the total salary payable in each department. Go to the
editor
Sample table: employees
Click me to see the solution
11. Write a query to get the average salary for each job ID excluding programmer. Go to the editor
Sample table: employees
Click me to see the solution
12. Write a query to get the total salary, maximum, minimum, average salary of employees (job ID wise),
for department ID 90 only. Go to the editor
Sample table: employees
Click me to see the solution

Page 282 of 349


13. Write a query to get the job ID and maximum salary of the employees where maximum salary is greater
than or equal to $4000. Go to the editor
Sample table: employees
Click me to see the solution
14. Write a query to get the average salary for all departments employing more than 10 employees. Go
to the editor
Sample table: employees
Click me to see the solution

MySQL Subquery [22 exercises with solution]


Reference tables on hr-db.sql database.
1. Write a query to find the name (first_name, last_name) and the salary of the employees who have a
higher salary than the employee whose last_name='Bull'. Go to the editor
Sample table: employees
Click me to see the solution
2. Write a query to find the name (first_name, last_name) of all employees who works in the IT
department. Go to the editor
Sample table: employees
Click me to see the solution
3. Write a query to find the name (first_name, last_name) of the employees who have a manager and
worked in a USA based department. Go to the editor
Hint : Write single-row and multiple-row subqueries
Sample table: employees
Sample table: departments
Sample table: locations
Click me to see the solution
4. Write a query to find the name (first_name, last_name) of the employees who are managers. Go to the
editor
Sample table: employees
Click me to see the solution
5. Write a query to find the name (first_name, last_name), and salary of the employees whose salary is
greater than the average salary. Go to the editor

Page 283 of 349


Sample table: employees
Click me to see the solution
6. Write a query to find the name (first_name, last_name), and salary of the employees whose salary is
equal to the minimum salary for their job grade. Go to the editor
Sample table: employees
Sample table: jobs
Click me to see the solution
7. Write a query to find the name (first_name, last_name), and salary of the employees who earns more
than the average salary and works in any of the IT departments. Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution
8. Write a query to find the name (first_name, last_name), and salary of the employees who earns more
than the earning of Mr. Bell. Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution
9. Write a query to find the name (first_name, last_name), and salary of the employees who earn the
same salary as the minimum salary for all departments. Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution
10. Write a query to find the name (first_name, last_name), and salary of the employees whose salary is
greater than the average salary of all departments. Go to the editor
Sample table: employees
Click me to see the solution
11. Write a query to find the name (first_name, last_name) and salary of the employees who earn a salary
that is higher than the salary of all the Shipping Clerk (JOB_ID = 'SH_CLERK'). Sort the results of the salary
of the lowest to highest. Go to the editor
Sample table: employees

Click me to see the solution


12. Write a query to find the name (first_name, last_name) of the employees who are not supervisors. Go
to the editor

Page 284 of 349


Sample table: employees
Click me to see the solution
13. Write a query to display the employee ID, first name, last name, and department names of all
employees. Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution
14. Write a query to display the employee ID, first name, last name, salary of all employees whose salary
is above average for their departments. Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution
15. Write a query to fetch even numbered records from employees table. Go to the editor
Sample table: employees

Click me to see the solution


16. Write a query to find the 5th maximum salary in the employees table. Go to the editor
Sample table: employees
Click me to see the solution
17. Write a query to find the 4th minimum salary in the employees table. Go to the editor
Sample table: employees
Click me to see the solution
18. Write a query to select last 10 records from a table. Go to the editor
Sample table: employees
Click me to see the solution
19. Write a query to list the department ID and name of all the departments where no employee is
working. Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution
20. Write a query to get 3 maximum salaries. Go to the editor
Sample table: employees

Page 285 of 349


Click me to see the solution
21. Write a query to get 3 minimum salaries. Go to the editor
Sample table: employees
Click me to see the solution
22. Write a query to get nth max salaries of employees. Go to the editor
Sample table: employees
Click me to see the solution

MySQL Joins [13 exercises with solution]


Reference tables on hr-db.sql database.
1. Write a query to find the addresses (location_id, street_address, city, state_province, country_name)
of all the departments. Go to the editor
Hint : Use NATURAL JOIN.
Sample table: locations
Sample table: countries
Click me to see the solution
2. Write a query to find the name (first_name, last name), department ID and name of all the employees.
Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution
3. Write a query to find the name (first_name, last_name), job, department ID and name of the employees
who works in London. Go to the editor
Sample table: departments
Sample table: locations
Click me to see the solution
4. Write a query to find the employee id, name (last_name) along with their manager_id and name
(last_name). Go to the editor
Sample table: employees
Click me to see the solution

Page 286 of 349


5. Write a query to find the name (first_name, last_name) and hire date of the employees who was hired
after 'Jones'. Go to the editor
Sample table: employees
Click me to see the solution
6. Write a query to get the department name and number of employees in the department. Go to the
editor
Sample table: employees
Sample table: departments
Click me to see the solution
7. Write a query to find the employee ID, job title, number of days between ending date and starting date
for all jobs in department 90. Go to the editor
Sample table: employees
Click me to see the solution
8. Write a query to display the department ID and name and first name of manager. Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution
9. Write a query to display the department name, manager name, and city. Go to the editor
Sample table: employees
Sample table: departments
Sample table: locations
Click me to see the solution
10. Write a query to display the job title and average salary of employees. Go to the editor
Sample table: employees
Click me to see the solution
11. Write a query to display job title, employee name, and the difference between salary of the employee
and minimum salary for the job. Go to the editor
Sample table: employees
Click me to see the solution
12. Write a query to display the job history that were done by any employee who is currently drawing
more than 10000 of salary. Go to the editor
Sample table: employees
Sample table: Job_history

Page 287 of 349


Click me to see the solution
13. Write a query to display department name, name (first_name, last_name), hire date, salary of the
manager for all managers whose experience is more than 15 years. Go to the editor
Sample table: employees
Sample table: departments
Click me to see the solution

Date and Time functions [21 exercises with solution]


Reference tables on hr-db.sql database.
1. Write a query to display the first day of the month (in datetime format) three months before the current
month. Go to the editor
Sample current date : 2014-09-03
Expected result : 2014-06-01
Click me to see the solution
2. Write a query to display the last day of the month (in datetime format) three months before the current
month. Go to the editor
Click me to see the solution
3. Write a query to get the distinct Mondays from hire_date in employees tables. Go to the editor
Sample table: employees
Click me to see the solution
4. Write a query to get the first day of the current year. Go to the editor
Click me to see the solution
5. Write a query to get the last day of the current year. Go to the editor
Click me to see the solution
6. Write a query to calculate the age in year. Go to the editor
Click me to see the solution
7. Write a query to get the current date in the following format. Go to the editor
Sample date : 2014-09-04
Output : September 4, 2014
Click me to see the solution
8. Write a query to get the current date in Thursday September 2014 format. Go to the editor
Thursday September 2014

Page 288 of 349


Click me to see the solution
9. Write a query to extract the year from the current date. Go to the editor
Click me to see the solution
10. Write a query to get the DATE value from a given day (number in N). Go to the editor
Sample days: 730677
Output : 2000-07-11
Click me to see the solution
11. Write a query to get the first name and hire date from employees table where hire date between
'1987-06-01' and '1987-07-30' Go to the editor
Sample table: employees
Click me to see the solution
12. Write a query to display the current date in the following format. Go to the editor
Sample output: Thursday 4th September 2014 00:00:00
Click me to see the solution
13. Write a query to display the current date in the following format. Go to the editor
Sample output: 05/09/2014
Click me to see the solution
14. Write a query to display the current date in the following format. Go to the editor
Sample output: 12:00 AM Sep 5, 2014
Click me to see the solution
15. Write a query to get the firstname, lastname who joined in the month of June. Go to the editor
Sample table: employees
Click me to see the solution
16. Write a query to get the years in which more than 10 employees joined. Go to the editor
Sample table: employees
Click me to see the solution
17. Write a query to get first name of employees who joined in 1987. Go to the editor
Sample table: employees
Click me to see the solution
18. Write a query to get department name, manager name, and salary of the manager for all managers
whose experience is more than 5 years. Go to the editor
Sample table: departments
Click me to see the solution
19. Write a query to get employee ID, last name, and date of first salary of the employees. Go to the editor

Page 289 of 349


Sample table: employees
Click me to see the solution
20. Write a query to get first name, hire date and experience of the employees. Go to the editor
Sample table: employees
Click me to see the solution
21. Write a query to get the department ID, year, and number of employees joined. Go to the editor
Sample table : employees
Click me to see the solution

References

All the chapters except MySQL Stored Procedures are based on W3School tutorial in the following link:
https://www.w3schools.com/mysql/

MySQL Stored Procedures are taken from: https://www.mysqltutorial.org/mysql-stored-procedure-


tutorial.aspx
All the Home Work assignments are taken from https://www.w3resource.com/mysql-exercises/

XAMPP

What is XAMPP?
XAMPP is the most popular PHP development environment
XAMPP is a completely free, easy to install Apache distribution containing MariaDB, PHP, and Perl. The
XAMPP open source package has been set up to be incredibly easy to install and to use.

Page 290 of 349


How to download and install?
You can download XAMP for different operating systems including: Windows, MacOS and Linux in the
following link:

https://www.apachefriends.org/download.html

For all the operating systems XAMP comes with package installer which is easy and straight forward.

Managing XAMPP applications with XAMP manager

XAMP have an application from which you can start/stop all of its services. To start or stop a service you
can simply select the service and start it.

Though out this course we will need only two services that XAMPP will offer and those are
MariaDB(MySQL) and PHP.

Page 291 of 349


Serving a site on Apache
To serve a site inside XAMPP apache you will need to copy your project files inside XAMPP folder called
htdocs you can locate this file inside installation folder of your XAMPP “XAMPP/xamppfiles/htdocs/”. Then
you can create folder inside it lets say “myfirstproject” and put your files inside it. In order to access it
from your browser you will simply need to go to http://localhost/[yourfolder] in this case
“http://localhost/myfirstproject”. Like all Apache they do index on two type of files .html and .php and
the main index of the folder should be named index.html or index.php.

Hosting a database
XAMPP comes with a GUI (Graphical User Interface) for MySQL/MariaDB and it is called phpMyAdmin.
This is a GUI build on PHP to manage MySQL instances. You can access it by browser on
“httpd://localhost/phpmyadmin”. It Looks like picture below:

Page 292 of 349


With phpMyAdmin you will have change to create/delete/update database, users, and write SQL
statements.

Page 293 of 349


Part V - Introduction to PHP

 PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-
purpose scripting language that is especially suited for web development and can be embedded
into HTML.
 The default file extension for PHP files is ".php".
 A PHP file normally contains HTML tags, and some PHP scripting code.
 Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function
"echo" to output the text "Hello World!" on a web page:

<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>

<?php
echo "Hello World!";
?>

</body>
</html>

PHP Case Sensitivity

In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not
case-sensitive.
In the example below, all three echo statements below are equal and legal:
<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello World!<br>";

Page 294 of 349


echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>

PHP Comments

 A comment in PHP code is a line that is not executed as a part of the program. Its only purpose is
to be read by someone who is looking at the code.
Syntax for single-line comments:
<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment


?>

</body>
</html>

Syntax for multiple-line comments:


<!DOCTYPE html>
<html>
<body>

Page 295 of 349


<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>

</body>
</html>

PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable.
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for PHP variables:


 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different variables)
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

PHP Data Types

Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:

Page 296 of 349


 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource
<!DOCTYPE html>
<html>
<body>

<?php

//PHP String
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;

echo "<br>";

//PHP Integer
$x_1 = 5985;
var_dump($x_1);

//PHP Float

$x_2 = 10.365;
var_dump($x_2);

?>

Page 297 of 349


</body>
</html>

Operator and Expression

Operators are used to perform operations on variables and values.


PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators

PHP Arithmetic Operators

Operator Name Example


+ Addition <?php
$x = 10;
$y = 6;
echo $x + $y;
?>

- Subtraction <?php
$x = 10;
$y = 6;
echo $x - $y;
?>

Page 298 of 349


* Multiplication <?php
$x = 10;
$y = 6;
echo $x * $y;
?>
/ Division <?php
$x = 10;
$y = 6;
echo $x / $y;
?>
% Modulus <?php
$x = 10;
$y = 6;
echo $x % $y;
?>
** Exponentiation <?php
$x = 2;
$y = 4;
echo $x**$y;
?>

PHP Assignment Operators

x += y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x /= y x=x/y Division

Page 299 of 349


x %= y x=x%y Modulus

PHP Comparison Operators

Operator Name Example


== Equal <?php
$x = 100;
$y = "100";
var_dump($x == $y); // returns true because values are
equal
?>

=== Identical <?php


$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are
not equal
?>
!= Not Equal <?php
$x = 100;
$y = "100";
var_dump($x != $y); // returns false because values are
equal
?>

Page 300 of 349


<> Not Equal <?php
$x = 100;
$y = "100";
var_dump($x <> $y); // returns false because values are
equal
?>

!== Not Identical <?php


$x = 100;
$y = "100";

var_dump($x !== $y); // returns true because types are


not equal
?>
> Greater then <?php
$x = 100;
$y = 50;
var_dump($x > $y); // returns true because $x is greater
than $y
?>

< Less then <?php


$x = 10;
$y = 50;

var_dump($x < $y); // returns true because $x is less than


$y
?>
>= Greater than or equal to <?php
$x = 50;

Page 301 of 349


$y = 50;

var_dump($x >= $y); // returns true because $x is greater


than or equal to $y
?>
<= Less than or equal to <?php
$x = 50;
$y = 50;

var_dump($x <= $y); // returns true because $x is less


than or equal to $y
?>

PHP Increment / Decrement Operators

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

Page 302 of 349


Operator Name Example Code
and And &x and $y <?php
$x = 100;
$y = 50;
if ($x == 100 and $y == 50) {
echo "Hello world!";
}
?>
or Or &x or $y <?php
$x = 100;
$y = 50;
if ($x == 100 or $y == 50) {
echo "Hello world!";
}
?>

xor Xor <?php


$x = 100;
$y = 50;
if ($x == 100 xor $y == 50) {
echo "Hello world!";
}
?>

Page 303 of 349


&& And <?php
$x = 100;
$y = 50;
if ($x == 100 && $y == 50) {
echo "Hello world!";
}
?>

|| Or <?php
$x = 100;
$y = 50;
if ($x == 100 or $y == 50) {
echo "Hello world!";
}
?>

! Not <?php
$x = 100;
if ($x !== 99) {
echo "Hello world!";
}
?>

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different conditions. You can
use conditional statements in your code to do this.
In PHP we have the following conditional statements:

Page 304 of 349


 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that condition
is false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

PHP Conditional Statements


The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
Example: Output "Have a good day!" if the current time (HOUR) is less than 20.

<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>

PHP Switch Statement

 Use the switch statement to select one of many blocks of code to be executed.

Page 305 of 349


Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

Example: Switch condition.

<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";

Page 306 of 349


}
?>

PHP Loops

Often when you write code, you want the same block of code to run over and over again a certain number
of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is true.
In PHP, we have the following loop types:
 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the specified
condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

PHP while Loop


The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}

Example: The example below displays the numbers from 1 to 5.

<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;

Page 307 of 349


}
?>

Example: The example below displays the multiplication table with 7.

<?php
$number=7;
$i=1;

while ($i <= 10) {


echo $number . "x" . $i . "=" . ($i*$number) . "<br>";
$i++;
}
?>

PHP do while Loop

The do...while loop will always execute the block of code once, it will then check the condition, and repeat
the loop while the specified condition is true.

Syntax
do {
code to be executed;
} while (condition is true);

Page 308 of 349


Example: The example below displays the multiplication table with 7.

<?php
$number = 7;
$i = 1;

do {
echo $number . "x" . $i . "=" . ($i * $number) . "<br>";
$i++;
} while ($i <= 10);

?>

PHP for Loop

The for loop is used when you know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

Example: The example below displays the multiplication table with 4.

Page 309 of 349


<?php
$number = 4;
for ($i=1; $i <=10 ; $i++) {
echo $number . "x" . $i . "=" . ($i * $number) . "<br>";
}
?>

Example: Create a script to construct the following pattern, using nested for loop!

*
**
***
****
*****

<?php
for($x=1;$x<=5;$x++)
{
for ($y=1;$y<=$x;$y++)
{
echo "*";
if($y< $x)
{
echo " ";
}
}
echo "\n";

Page 310 of 349


}

Example: Create a script to construct the following pattern, using a nested for loop.

*
**
***
****
*****
*****
****
***
**
*

<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo '\n';
}

Page 311 of 349


for($i=$n; $i>=1; $i--)
{
for($j=1; $j<=$i; $j++)
{
echo ' * ';
}
echo '\n ';
}
?>

Example: Write a program to calculate and print the factorial of a number using a for loop. The
factorial of a number is the product of all integers up to and including that number, so
the factorial of 4 is 4*3*2*1= 24

<?php
$n = 6;
$x = 1;
for($i=1;$i<=$n-1;$i++)
{
$x*=($i+1);
}
echo "The factorial of $n = $x"."\n";
?>

Example: Write a PHP script using nested for loop that creates a chess board as shown below.
Use table width="270px" and take 30px as cell height and width.

Page 312 of 349


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h3>Chess Board using Nested For Loop</h3>
<table width="270px" cellspacing="0px" cellpadding="0px" border="1px">
<!-- cell 270px wide (8 columns x 60px) -->
<?php
for($row=1;$row<=8;$row++)
{
echo "<tr>";
for($col=1;$col<=8;$col++)
{
$total=$row+$col;
if($total%2==0)
{

Page 313 of 349


echo "<td height=30px width=30px bgcolor=#FFFFFF></td>";
}
else
{
echo "<td height=30px width=30px bgcolor=#000000></td>";
}
}
echo "</tr>";
}
?>
</table>
</body>
</html>

Example: Write a PHP script that creates the following table (use for loops).

<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 10; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 10; $col++) {
$p = $col * $row;
echo "<td>$p</td> \n";
}
echo "</tr>";

Page 314 of 349


}
echo "</table>";
?>

PHP Break and Continue

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump
out" of a switch statement.

Example: This example jumps out of the loop when x is equal to 4.

<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>

Example: This example skips the value of 4.

<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}

Page 315 of 349


?>

PHP Functions

Besides the built-in PHP functions, it is possible to create your own functions.
 A function is a block of statements that can be used repeatedly in a program.
 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

Syntax

function functionName() {
code to be executed;
}

Example: In the example below, we create a function named "writeMsg()".

<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

Page 316 of 349


PHP Functions Argument

Example: In the example below, we create a function named "familyName()", with


arguments(parameters).

<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

Example: Using function, generate the multiplication table for a given value

<?php
function generateMultiplicationTable($number)
{
for ($i=1; $i <=10 ; $i++) {
echo $number . " x " . $i . " = " . ($i*$number) . "<br>";
}
}
generateMultiplicationTable(4);

Page 317 of 349


?>

Example: Using function, calculate the sum of numbers between two values.

<?php
function calculateSum($start_value, $end_value)
{
$s = 0;
for ($j = $start_value; $j <= $end_value; $j++) {
$s = $s + $j;
}
echo $s;
}
calculateSum(1, 3);
?>

Example: Write a function to calculate the factorial of a number (a non-negative integer). The
function accepts the number as an argument.

<?php
function factorial_of_a_number($n)
{
if($n ==0)
{
return 1;
}
else

Page 318 of 349


{
return $n * factorial_of_a_number($n-1);
}
}
echo(factorial_of_a_number(4)."\n");
?>

PHP Arrays

 An array stores multiple values in one single variable.


 An array is a special variable, which can hold more than one value at a time.
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
 Associative arrays - Arrays with named keys
 Multidimensional arrays - Arrays containing one or more arrays

PHP - The count() Function

Example: The count() function is used to return the length (the number of elements) of an array:

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

Page 319 of 349


PHP Indexed Arrays

There are two ways to create indexed arrays:


The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

Example: <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Or
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

Example: <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

Page 320 of 349


echo "Peter is ". $age['Peter'] ." years old.";
?>

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays
more than three levels deep are hard to manage for most people.

Name Stock Sold

Volvo 22 18

BMW 15 13

Saab 5 2

Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

Example: Now the two-dimensional $cars array contains four arrays, and it has two indices: row
and column.
To get access to the elements of the $cars array we must point to the two indices (row
and column):

Page 321 of 349


<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to
point to the two indices):

<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>

PHP - Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()

Page 322 of 349


Example: <?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

Sort Array in Descending Order - rsort()

Example: <?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>

Example: Write a PHP script to sort the following associative array :


array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40") in
a) ascending order sort by value
b) ascending order sort by Key
c) descending order sorting by Value
d) descending order sorting by Key

<?php
echo "
Associative array : Ascending order sort by value
";
$array2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); asort($array2);
foreach($array2 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Ascending order sort by Key

Page 323 of 349


";
$array3=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); ksort($array3);
foreach($array3 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Descending order sorting by Value
";
$age=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");
arsort($age);
foreach($age as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
echo "
Associative array : Descending order sorting by Key
";
$array4=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40"); krsort($array4);
foreach($array4 as $y=>$y_value)
{
echo "Age of ".$y." is : ".$y_value."
";
}
?>

Example: Write a PHP script to calculate and display average temperature, five lowest and
highest temperatures.

Page 324 of 349


Recorded temperatures : 78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 75, 76, 73, 68,
62, 73, 72, 65, 74, 62, 62, 65, 64, 68, 73, 75, 79, 73
Expected Output :
Average Temperature is : 70.6
List of seven lowest temperatures : 60, 62, 63, 63, 64,
List of seven highest temperatures : 76, 78, 79, 81, 85,

<?php
$month_temp = "78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73";
$temp_array = explode(',', $month_temp);
$tot_temp = 0;
$temp_array_length = count($temp_array);
foreach($temp_array as $temp)
{
$tot_temp += $temp;
}
$avg_high_temp = $tot_temp/$temp_array_length;
echo "Average Temperature is : ".$avg_high_temp."
";
sort($temp_array);
echo " List of five lowest temperatures :";
for ($i=0; $i< 5; $i++)
{
echo $temp_array[$i].", ";
}
echo "List of five highest temperatures :";
for ($i=($temp_array_length-5); $i< ($temp_array_length); $i++)
{
echo $temp_array[$i].", ";
}
?>

Page 325 of 349


PHP - ADVANCED

PHP Date and Time


The PHP date() function is used to format a date and/or a time.
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
 d - Represents the day of the month (01 to 31)
 m - Represents a month (01 to 12)
 Y - Represents a year (in four digits)
 l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.
The example below formats today's date in three different ways:
Example: <?php
echo "Today is ". date("Y/m/d") . "<br>";
echo "Today is ". date("Y.m.d") . "<br>";
echo "Today is ". date("Y-m-d") . "<br>";
echo "Today is ". date("l");
?>

PHP Include Files

The include (or require) statement takes all the text/code/markup that exists in the specified file and
copies it into the file that uses the include statement.
Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of
a website.
PHP include and require Statements
It is possible to insert the content of one PHP file into another PHP file (before the server executes it),
with the include or require statement.

Page 326 of 349


The include and require statements are identical, except upon failure:
 require will produce a fatal error (E_COMPILE_ERROR) and stop the script
 include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is missing, use
the include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding,
always use the require statement to include a key file to the flow of execution. This will help avoid
compromising your application's security and integrity, just in-case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard header, footer, or menu file
for all your web pages. Then, when the header needs to be updated, you can only update the header
include file.
Syntax
include 'filename';

or

require 'filename';
Example: PHP include Examples

<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</body>
</html>
Example: Assume we have a standard menu file called "menu.php":

<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>

Page 327 of 349


Functional Work : All functions perform similar work. All functions will include and evaluates the specific
file while executing the code.
Functional Difference :

include vs include_once : There is only one difference between include() and include_once(). If the code
from a file has been already included then it will not be included again if we use include_once(). Means
include_once() include the file only once at a time.
include vs require : if include() is not able to find a specified file on location at that time it will throw a
warning however, it will not stop script execution. For the same scenario, require() will throw a fatal error
and it will stop the script execution.
require vs require_once : There is only one difference between require() and require_once(). If the code
from a file has been already included then it will not be included again if we use require_once(). Means
require_once() include the file only once at a time.
<html>
<body>

<div class="menu">
<?php include 'menu.php';?>
</div>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>

</body>
</html>

PHP File Handling

PHP readfile() Function


The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language

Page 328 of 349


SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
Example: <?php
echo readfile("webdictionary.txt");
?>

PHP - OOP

OOP stands for Object-Oriented Programming.


Procedural programming is about writing procedures or functions that perform operations on the data,
while object-oriented programming is about creating objects that contain both data and functions.
Object-oriented programming has several advantages over procedural programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to
maintain, modify and debug
 OOP

PHP - What are Classes and Objects?

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

Page 329 of 349


Define a Class

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces
({}). All its properties and methods go inside the braces:

Syntax

<?php
class Fruit {
// code goes here...
}
?>

Example: Below we declare a class named Fruit consisting of two properties ($name and $color)
and two methods set_name() and get_name() for setting and getting the $name
property:

<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods

Page 330 of 349


function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>

PHP OOP - Constructor

A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function when you create an object
from a class.

Example: <?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>

Example: <?php
class Fruit {
public $name;
public $color;

Page 331 of 349


function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}

$apple = new Fruit("Apple", "red");


echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>

PHP OOP - Destructor

A destructor is called when the object is destructed or the script is stopped or exited.
If you create a __destruct() function, PHP will automatically call this function at the end of the script.

Example: <?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

Page 332 of 349


$apple = new Fruit("Apple");
?>

Example: <?php
class Fruit {
public $name;
public $color;

function __construct($name, $color) {


$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

$apple = new Fruit("Apple", "red");


?>

PHP OOP - Inheritance

PHP - What is Inheritance?


Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and methods from the parent class. In
addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
Example: <?php
class Fruit {
public $name;
public $color;

Page 333 of 349


public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>

Example: Write a simple PHP class which displays an introductory message like "Hello All, I am
Scott", where "Scott" is an argument value of the method within the class.

<?php
class user_message {
public $message = 'Hello All, I am ';
public function introduce($name)
{
return $this->message.$name;
}
}
$mymessage = New user_message();
echo $mymessage->introduce('Scott')."\n";
?>

Example: Write a PHP class that calculates the factorial of an integer.

Page 334 of 349


<?php
class factorial_of_a_number
{
protected $_n;
public function __construct($n)
{
if (!is_int($n))
{
throw new InvalidArgumentException('Not a number or missing argument');
}
$this->_n = $n;
}
public function result()
{
$factorial = 1;
for ($i = 1; $i <= $this->_n; $i++)
{
$factorial *= $i;
}
return $factorial;
}
}

$newfactorial = New factorial_of_a_number(5);


echo $newfactorial->result();
?>

Example: Calculate the difference between two dates using PHP OOP approach.
Sample Dates : 1981-11-03, 2013-09-04
Expected Result : Difference : 31 years, 10 months, 1 days

Page 335 of 349


<?php
$sdate = new DateTime("1981-11-03");
$edate = new DateTime("2013-09-04");
$interval = $sdate->diff($edate);
echo "Difference : " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
?>

Example: Write a PHP script to convert a string to Date and DateTime.


Sample Date : '12-08-2004'
Expected Output : 2004-12-08

<?php
$dt = DateTime::createFromFormat('m-d-Y', '12-08-2004')->format('Y-m-d');
echo $dt;
?>

PHP MySQL Database

 With PHP, you can connect to and manipulate databases.


 MySQL is the most popular database system used with PHP.

What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL

Page 336 of 349


 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation

PHP MySQL Database

PHP 5 and later can work with a MySQL database using:


 MySQLi extension (the "i" stands for improved)
 PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.

Open a Connection to MySQL

Example: Example (MySQLi Object-Oriented)

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

// Create connection
$conn = new mysqli($servername, $username, $password,$database);

// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

Page 337 of 349


echo "Connected successfully";
?>

Create a MySQL Database Using MySQLi and PDO

The CREATE DATABASE statement is used to create a database in MySQL.

Example: <?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: ". $conn->error;
}

$conn->close();
?>

PHP MySQL Create Table

Create a MySQL Table Using MySQLi and PDO


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

Page 338 of 349


Example: We will create a table named "MyGuests", with five columns: "id", "firstname",
"lastname", "email" and "reg_date":

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Example: Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

// sql to
create table
$sql = "CREATE TABLE
MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT
PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

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


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: ". $conn->error;

Page 339 of 349


}

$conn->close();
?>

PHP MySQL Insert Data

Insert Data Into MySQL Using MySQLi and PDO


After a database and a table have been created, we can start adding data in them.
 Here are some syntax rules to follow:
 The SQL query must be quoted in PHP
 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

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


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

Example: Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection

Page 340 of 349


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

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

$conn->close();
?>

PHP MySQL Get Last Inserted ID

Get ID of The Last Inserted Record


If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the
last inserted/updated record immediately.
In the table "MyGuests", the "id" column is an AUTO_INCREMENT field:
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
Example: Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

Page 341 of 349


$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')" ;

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


$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: ". $sql . "<br>" . $conn->error;
}

$conn->close();
?>

PHP MySQL Insert Multiple Records

Insert Multiple Records Into MySQL Using MySQLi and PDO


Multiple SQL statements must be executed with the mysqli_multi_query() function.

The following examples add three new records to the "MyGuests" table:

Example: Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

Page 342 of 349


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";

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


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

$conn->close();
?>

PHP MySQL Select Data

Select Data From a MySQL Database


The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name

Example: Example (MySQLi Object-oriented)

<?php
$servername = "localhost";

Page 343 of 349


$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


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

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

PHP MySQL Use The WHERE Clause

The WHERE clause is used to filter records.


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

SELECT column_name(s) FROM table_name WHERE column_name operator value

Example: Example (MySQLi Object-oriented)

Page 344 of 349


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";


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

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: ". $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

PHP MySQL Use The ORDER BY Clause

Select and Order Data From a MySQL Database


The ORDER BY clause is used to sort the result-set in ascending or descending order.
The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending
order, use the DESC keyword.
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

Page 345 of 349


Example: Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";


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

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

PHP MySQL Delete Data

Delete Data From a MySQL Table Using MySQLi and PDO


The DELETE statement is used to delete records from a table:

DELETE FROM table_name


WHERE some_column = some_value

Page 346 of 349


Let's look at the "MyGuests" table:

Example: Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

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


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

$conn->close();
?>

Page 347 of 349


PHP MySQL Update Data

Update Data In a MySQL Table Using MySQLi and PDO


The UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Example: Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

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


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

$conn->close();
?>

Page 348 of 349


PHP MySQL Limit Data Selections

Limit Data Selections From a MySQL Database


MySQL provides a LIMIT clause that is used to specify the number of records to return.
The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful on
large tables. Returning a large number of records can impact on performance.
Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The SQL query
would then look like this:
$sql = "SELECT * FROM Orders LIMIT 30";
When the SQL query above is run, it will return the first 30 records.
What if we want to select records 16 - 25 (inclusive)?
Mysql also provides a way to handle this: by using OFFSET.
The SQL query below says "return only 10 records, start on record 16 (OFFSET 15)":
$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";
You could also use a shorter syntax to achieve the same result:
$sql = "SELECT * FROM Orders LIMIT 15, 10";

Page 349 of 349


This manual is supported by the UK Government’s Conflict, Stability and Security Fund through the Project
“Amplifying Local Voices for Equitable Development” implemented by the consortium of organizations

You might also like