IT School - Manuali
IT School - Manuali
TRAINING MANUAL
for
HTML, CSS, JS, MySQL, PHP.
October 2021
Table of Contents
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
</head>
<body>
</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>
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!
Page 19 of 349
<body>
</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!
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"
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">
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
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.
<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 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>
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>
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>
Page 27 of 349
I have a bike
I have a car
I have a boat
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>
This chapter describes the different attributes for the HTML<form> element.
Tip: If the action attribute is omitted, the action is set to the current page.
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
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
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>
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.
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>
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>
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.
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>
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>
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>
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>
HTML
CSS
JavaScript
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>
I have a bike
I have a car
I have a boat
Page 40 of 349
<input type="button" onclick="alert('Hello World!')" value="Click Me!">
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>
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>
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>
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 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>
Page 45 of 349
HTML Input Attributes
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>
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>
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>
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>
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
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.
h1 {
color: white;
text-align: center;
}
p {
font-family: verdana;
font-size: 20px;
}
</style>
</head>
<body>
</body>
Page 52 of 349
</html>
CSS Syntax
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;
}
You can also specify that only specific HTML elements should be affected by a class.
p.center.{
text-align: center;
color: red;
}
Page 54 of 349
The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.
* {
text-align: center;
color: blue;
}
p {
text-align: center;
color: red;
}
Page 55 of 349
To group selectors, separate each selector with a comma.
h1, h2, p {
text-align: center;
color: red;
}
When a browser reads a style sheet, it will format the HTML document according to the information in
the style sheet.
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>
</body>
</html>
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.
Tomato
Orange
DodgerBlue
MediumSeaGreen
Gray
SlateBlue
Violet
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>
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.
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
%, 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>
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;
}
CSSBorders
The CSS border properties allow you to specify the style, width, and color of an element's 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).
Page 64 of 349
p {
margin: 25px 50px 75px 100px;
}
Page 65 of 349
div {
width: 300px;
margin: auto;
border: 1px solid red;
}
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).
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
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.
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;
}
Example:
Use the padding shorthand property with three values.
div {
padding: 25px 50px 75px;
}
Example:
Use the padding shorthand property with two values.
div {
padding: 25px 50px;
}
Page 70 of 349
Example:
Use the padding shorthand property with one value.
div {
padding: 25px;
}
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;
}
Page 72 of 349
Example:
Demonstration of the box model.
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
Example:
This <div> element will have a total width of 350px:
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
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.
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.
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:
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;
}
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;
}
.row::after {
content: "";
clear: both;
display: table;
}
[class*="col-"] {
float: left;
padding: 15px;
}
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>
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%;}
Page 83 of 349
Example:
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}
.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;
}
Page 85 of 349
}
<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>
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%;
}
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;
}
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>
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>
/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {...}
/* 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;}
}
/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
.example {background: pink;}
}
</style>
</head>
<body>
</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;
}
<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;
}
<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
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;
}
div:hover {
width: 300px;
}
</style>
</head>
<body>
<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.
<!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>
<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>
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}
<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>
Transition + Transformation
The following example adds a transition effect to the transformation:
div {
transition: width 2s, height 2s, transform 2s;
}
div:hover {
width: 300px;
height: 300px;
transform: rotate(180deg);
}
</style>
</head>
<body>
<h1>Transition + Transform</h1>
<div></div>
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier
versions.</p>
</body>
</html>
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
<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 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.
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">
Downloading Bootstrap 4
If you want to download and host Bootstrap 4 yourself, go to https://getbootstrap.com/, and follow the
instructions there.
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
<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>
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 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.
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.
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>
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>
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
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>
<h2>JavaScript Variables</h2>
<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>
<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
<h2>JavaScript Variables</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script>
</body>
</html>
<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.
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>
<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>
<p id="demo"></p>
<script>
var x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>
<p id="demo"></p>
<script>
var x = "John" + " " + "Doe";
document.getElementById("demo").innerHTML = x;
</script>
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";
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.";
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");
Example
let x = new String("John");
let y = new String("John");
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!";
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;
Operator Description
- Subtraction
* Multiplication
** Exponentiation
/ Division
++ Increment
-- Decrement
Operator Description
!= not equal
? ternary operator
Operator Description
|| logical or
! logical not
Operator Description
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;
JavaScript Arrays
<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.
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>
</body>
</html>
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).
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"];
function myFunction(value) {
text += "<li>" + value + "</li>";
}
<h2>JavaScript Arrays</h2>
<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:
Solution:
const cars = ["Volvo", "Jeep", "Mercedes"];
cars[0] = "Ford";
JavaScript Functions
<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>
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.
<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>
Why Functions?
You can reuse code: Define the code once, and use it many times.
<h2>JavaScript Functions</h2>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
</script>
</body>
</html>
<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>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
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 id="demo1"></p>
<p id="demo2"></p>
<script>
myFunction();
function myFunction() {
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();
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>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
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 id="demo"></p>
document.getElementById("demo").innerHTML = greeting;
</script>
</body>
</html>
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>
<h2>JavaScript if .. else</h2>
<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>
The switch statement is used to perform different actions based on different conditions.
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
</body>
</html>
<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>
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>
<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>
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 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:
<p id="demo"></p>
<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let text = "";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
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):
Loop Scope
Using var in a loop:
Example
var i = 5;
// 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>
Example
let i = 5;
// 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>
<p id="demo"></p>
<script>
</body>
</html>
If you forget to increase the variable used in the condition, the loop will never end. This will crash your
browser.
<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!
<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"];
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
JavaScript Objects
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>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
</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:
</body>
</html>
Object Properties
firstName John
lastName Doe
age 50
eyeColor blue
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
</body>
</html>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
</body>
</html>
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
firstName John
lastName Doe
age 50
eyeColor blue
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;
}
};
</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;
}
};
Exercise:
Alert "John" by extracting information from the person object.
const person = {
firstName: "John",
lastName: "Doe"
};
alert( ___________);
Solution:
Alert(person.firstName);
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
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
Example
The following example changes the content (the innerHTML) of the <p> element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is a property.
Method Description
Property Description
Method Description
Method Description
Method Description
document.applets Deprecated 1
document.domConfig Obsolete. 3
document.links Returns all <area> and <a> elements that have a href attribute 1
This page teaches you how to find and access HTML elements in an HTML page.
<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.
<p id="demo"></p>
<script>
const element = document.getElementsByTagName("p");
</script>
</body>
</html>
This example finds the element with id="main", and then finds all <p> elements inside "main":
Example
<!DOCTYPE html>
<html>
<body>
<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>
<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>
<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>
<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>
The HTML DOM allows JavaScript to change the content of HTML elements.
<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>
<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"
<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"
<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
<script>
document.write(Date());
</script>
</body>
</html>
Never use document.write() after the document is loaded. It will overwrite the document.
JavaScript Forms
<h2>JavaScript Validation</h2>
</body>
</html>
<input id="numb">
<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>
<h2>JavaScript Validation</h2>
<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.
Attribute Description
Selector Description
What is MySQL?
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.
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
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).
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
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
What is SQL?
SQL is the standard language for dealing with Relational Databases.
SQL is used to insert, search, update, and delete database records.
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.
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
BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of 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
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)
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.
MySQL Database
Tip: The empty "Persons" table can now be filled with data with the SQL INSERT INTO statement.
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!
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.
Syntax
TRUNCATE TABLE table_name;
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.
MySQL Constraints
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,
....
);
MySQL Statements
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;
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.!
Operator Description
= Equal
Not equal. Note: In some versions of SQL this operator may be written as
<>
!=
Bottom of Form
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
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, ...);
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;
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:
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
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:
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 00000 Mexico
Constitución 2222 D.F.
helados
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:
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 00000 Mexico
Constitución 2222 D.F.
helados
4 Around the Horn Thomas Hardy 120 Hanover Sq. London 00000 UK
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
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
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
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
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
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 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.
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
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
Example
The following SQL statement lists the number of customers in each country:
Example
MySQL Operators
AND Example
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';
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 '_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:
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
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
Victoria
11 B's Beverages Fauntleroy Circus London EC2 5NT UK
Ashworth
Example
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
The following SQL statement selects all customers with a CustomerName that does NOT start with "a":
% Represents zero or more characters bl% finds bl, black, blue, and blob
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 '_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:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
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
Victoria Fauntleroy
11 B's Beverages London EC2 5NT UK
Ashworth Circus
Berkeley
Consolidated Elizabeth
16 Gardens 12 London WX1 6LT UK
Holdings Brown
Brewery
Drachenblut
17 Sven Ottlieb Walserweg 21 Aachen 52066 Germany
Delikatessend
Roland
20 Ernst Handel Kirchgasse 6 Graz 8010 Austria
Mendel
184, chaussée de
23 Folies gourmandes Martine Rancé Lille 59000 France
Tournai
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":
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:
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
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
Frédérique
7 Blondel père et fils 24, place Kléber Strasbourg 67000 France
Citeaux
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":
Example
The following SQL statement selects all customers that are from the same countries as the suppliers:
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:
2 Chang 1 1 24 - 12 oz bottles 19
BETWEEN Example
Example
The following SQL statement selects all products with a price between 10 and 20:
Example
The following SQL statement selects all products with a ProductName between "Carnarvon Tigers" and
"Mozzarella di Giovanni":
Sample Table
Below is a selection from the "Orders" table in the Northwind sample database:
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
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
% Modulo
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
Operator Description
= Equal to
Operator Description
+= Add equals
-= Subtract equals
*= Multiply equals
/= Divide equals
%= Modulo equals
Operator Description
MySQL Joins
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
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:
The INNER JOIN keyword selects records that have matching values in both tables.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The LEFT JOIN keyword returns all records from the left table (table1), and the matching records (if any)
from the right table (table2).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
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;
The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records (if
any) from the left table (table1).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The CROSS JOIN keyword returns all records from both tables (table1 and table2).
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
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:
MySQL Functions
Function Description
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
REPLACE Replaces all occurrences of a substring within a string, with a new substring
Function Description
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
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
DATE_ADD Adds a time/date interval to a date and then returns the date
DATE_SUB Subtracts a time/date interval from a date and then returns the date
LAST_DAY Extracts the last day of the month for a given date
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
QUARTER Returns the quarter of the year for a given date value
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
TO_DAYS Returns the number of days between a date and date "0000-00-00"
YEARWEEK Returns the year and week number for a given date
Function Description
CASE Goes through conditions and return a value when the first condition is met
Returns the user name and host name for the MySQL account that the server
CURRENT_USER
used to authenticate the current client
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
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();
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;
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 (;).
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 //
DELIMITER ;
This query returns all products in the products table from the sample database.
SELECT * FROM products;
DELIMITER ;
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();
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.
END$$
DELIMITER ;
Second, use the DROP PROCEDURE to delete the GetEmployees() stored procedure:
DROP PROCEDURE GetEmployees;
This statement drops the same non-existing stored procedure, but with IF EXISTS option:
DROP PROCEDURE IF EXISTS abc;
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.
DELIMITER ;
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();
DELIMITER ;
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;
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:
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;
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.
SELECT COUNT(*)
INTO totalOrder
FROM orders;
SELECT totalOrder;
END$$
DELIMITER ;
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;
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();
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.
SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;
DELIMITER ;
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.
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 $$
SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;
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.
If you want to execute statements conditionally based on multiple conditions, you use the following IF-
THEN-ELSEIF-ELSE statement:
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 $$
SELECT creditLimit
INTO credit
FROM customers
WHERE customerNumber = pCustomerNumber;
DELIMITER ;
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.
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:
+------------+--------------+------+-----+---------+-------+
| 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
+------------+--------------+------+-----+---------+-------+
| 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
+------------+--------------+------+-----+---------+-------+
| 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 | |
+--------------+---------------+------+-----+---------+-------+
References
All the chapters except MySQL Stored Procedures are based on W3School tutorial in the following link:
https://www.w3schools.com/mysql/
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.
https://www.apachefriends.org/download.html
For all the operating systems XAMP comes with package installer which is easy and straight forward.
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.
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:
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>
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>";
</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
</body>
</html>
</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).
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
<?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);
?>
- Subtraction <?php
$x = 10;
$y = 6;
echo $x - $y;
?>
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
|| 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!";
}
?>
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:
<?php
$t = date("H");
Use the switch statement to select one of many blocks of code to be executed.
<?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!";
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
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
<?php
$number=7;
$i=1;
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);
<?php
$number = 7;
$i = 1;
do {
echo $number . "x" . $i . "=" . ($i * $number) . "<br>";
$i++;
} while ($i <= 10);
?>
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: 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";
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';
}
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.
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>";
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.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
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;
}
<?php
function writeMsg() {
echo "Hello world!";
}
<?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);
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
PHP Arrays
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);
?>
$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] . ".";
?>
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");
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):
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>";
}
?>
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
Example: <?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
<?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
Example: Write a PHP script to calculate and display average temperature, five lowest and
highest temperatures.
<?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].", ";
}
?>
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.
or
require 'filename';
Example: PHP include Examples
<html>
<body>
</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>';
?>
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>
</body>
</html>
PHP - OOP
Classes and objects are the two main aspects of object-oriented programming.
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
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;
}
}
Example: <?php
class Fruit {
public $name;
public $color;
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}.";
}
}
Example: <?php
class Fruit {
public $name;
public $color;
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: 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
<?php
$dt = DateTime::createFromFormat('m-d-Y', '12-08-2004')->format('Y-m-d');
echo $dt;
?>
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
<?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);
}
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
$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
)";
$conn->close();
?>
The INSERT INTO statement is used to add new records to a MySQL table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}
$conn->close();
?>
The following examples add three new records to the "MyGuests" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn->close();
?>
<?php
$servername = "localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}
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();
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}
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
$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);
}
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
$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);
}
$conn->close();
?>
<?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);
}
$conn->close();
?>