Web Programming

Learn basics about HTML, CSS, JavaScript, PHP & Wordpress.

Get Started

Definitions



Static Vs Dynamic Websites?

Static: contains web pages with fixed content coded in HTML and stored on a web server. It does not change, it stays the same, or "static" for every viewer of the site. A static website does not require web programming or database design.
Dynamic: A Dynamic Website (also referred to as a database-driven site) requires web programming and database design. A dynamic website contains information and content that changes, depending on factors.


Websites Vs Web-Applications?

Websites: Websites are one-way informational feeds, they do not allow viewers to interact or communicate back to the site.
Web-Applications: Web applications are websites with functionality and interactive elements. Gmail, Facebook, YouTube, Twitter, etc. are all web apps that are dynamic, and built for user engagement.


Hosting & Domain

Hosting: Web hosting is the place where all the files of your website live.
Domain: Domain name is the address of your website that people type in the browser’s URL bar to visit your website.


POST Vs GET Method?

Both GET and POST method is used to transfer data from client to server in HTTP protocol.

POST: The data sent to the server with POST is stored in the request body of the HTTP request:

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length

GET: GET method is used to appends form data to the URL in name or value pair.

  • GET requests can be cached
  • GET requests remain in the browser history
  • GET requests can be bookmarked
  • GET requests have length restrictions

HTML?

HTML document is a plain text file that has been encoded using Hypertext Markup Language (HTML) so that it appears nicely formatted in a Web browser.


HTML Syntax

    <!DOCTYPE html>
    <html>
        <head>
            <title>Page Title</title>
        </head>
        <body>
            <h1>My First Heading</h1>
            <p>My first paragraph.</p>
        </body>
    </html>

Syntax Exaplanation

  • <!DOCTYPE html> define the version of HTML.
  • <html> root element of HTML page.
  • <head> may contains stylesheets & meta information of HTML page.
  • <title> define page title (which is shown in the browser's title bar).
  • <body> body is a container for all the visible contents, such as headings, paragraphs, images, videos, hyperlinks, tables, lists, forms etc.
  • <h1> heading tag.
  • <p> paragraph tag.

HTML Elements

An element in HTML usually consist of a start tag <tag name>, close tag </tag name> and content inserted between them. Technically, an element is a collection of start tag, attributes, end tag, content between them.

Note: Some HTML elements have no content (like the <br> element). These elements are called empty elements. Empty elements do not have an end tag!
Element Examples:
    <h1>My Heading</h1>
    <p>My Paragraph.</p>

HTML Tags

HTML tags are like keywords which defines that how web browser will format and display the content.

Tag Examples:
    <h1>
    <p>

HTML Attributes

Attributes are special words which provide additional information about the elements. attribute should always be applied with opening/start tag. attribute should be applied with its name and value. we can use multiple attribute in single element with space between two attributes.

Attribute Examples:
    <input type="text" />
    <marquee direction="left" bgcolor="red">My Marquee.</marquee>

HTML Meta Tags

The <meta> tag defines metadata about an HTML document. Metadata is data (information) about data. <meta> tags always go inside the <head> element, and are typically used to specify language, character set, page description, keywords, author of the document, and viewport settings. Metadata will not be displayed on the page, but browser read that. Metadata is also SEO ranking fector.

Meta Tag Examples:
<head>
  <meta charset="UTF-8">
  <meta name="description" content="Free Web tutorials">
  <meta name="keywords" content="HTML, CSS, JavaScript">
  <meta name="author" content="John Doe">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

Event Attributes

HTML has the ability to let events trigger actions in a browser, like starting a JavaScript when a user clicks on an element.

HTML have many types of event attributes:

  • Window Event
  • Form Events
  • Keyboard Events
  • Mouse Events
  • Drag Events
  • Clipboard Events
  • Media Events
  • Misc Events
Event Attribute Examples:
<body onresize="alert("User resize the screen size");">
<input oninput="myFunction()">
<input type="text" onkeydown="keyDownFunction()">
<input ondblclick="alert("User Perform Double Click Action");">
<input type="text" oncopy="alert("You text has been copied!")" value="Try to copy this text">


HTML Error Messages

When a browser requests a service from a web server, an error might occur, and the server might return an error code like "404 Not Found". But these messages are something called HTTP status messages. In fact, the server always returns a message for every request. The most common message is 200 OK.


1xx: Information
  • 100 Continue
  • 101 Switching Protocols
  • 103 Checkpoint

2xx: Successful
  • 200 OK
  • 201 Created
  • 202 Accepted
  • 203 Non-Authoritative Information
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content

3xx: Redirection
  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found
  • 303 See Other
  • 304 Not Modified
  • 306 Switch Proxy
  • 307 Temporary Redirect
  • 308 Resume Incomplete

4xx: Client Error
  • 400 Bad Request
  • 401 Unauthorized
  • 402 Payment Required
  • 403 Forbidden
  • 404 Not Found
  • 405 Method Not Allowed
  • 406 Not Acceptable
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Request Entity Too Large
  • 414 Request-URI Too Long
  • 415 Unsupported Media Type
  • 416 Requested Range Not Satisfiable
  • 417 Expectation Failed

5xx: Server Error
  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported
  • 511 Network Authentication Required

HTML Tags

Tag Description
< !DOCTYPE > Define document type or version of HTML
< html > Define html document
< head > Contains metadata/information for the document
< title > Defines a title for the document
< body >
< h1 to h6 > Define headings 1 to 6
< p > Define a paragraph
< br > Define single break line
< hr > Define horizontal line
< !-- ... -- > Define Comment

CSS?

CSS stands for Cascading Style Sheets.
CSS describes how HTML elements are to be displayed.


CSS Syntax

A CSS rule consists of a selector and a declaration block:
Selector may be HTML tag, id & class
Declaration Block in curly braces contains one or more declarations separated by semicolons.
Declaration includes a CSS property name and a value, separated by a colon.


How to add CSS with HTML?

There are 3 ways to attach CSS with HTML.

  • Inline: CSS use by "style" attribute.
    • Example:
      <p style="color:red;">
  • Internal: the internal style is defined inside the <style> element, inside the <head> section.
    • Example:
      <head>
          <style>
              p { 
                  color:red;
              } 
          /<style>
      </head>
      
  • External: style sheet use by <link> tag inside <head> tag. External CSS file save with .css extension.
    • Example:
      <head>
          <link href="/style.css">
      </head>
      

CSS Comment

A CSS comment starts with /* and ends with */


CSS Padding & Margin

Padding: properties are used to generate space around an element's content, inside of any defined borders.
Margin: properties are used to create space around elements, outside of any defined borders.

JavaScript?

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language. While it is most well-known as the scripting language for Web pages. JavaScript is case-sensitive language.
JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

JavaScript Framework

There are many useful Javascript frameworks and libraries available:

  • Angular
  • React
  • jQuery
  • Vue.js
  • Node.js
  • Backbone.js
  • etc.

JavaScript Supported Datatypes

According to the latest ECMAScript release, following are the data types supported in Javascript:

  • Boolean
  • Number
  • String
  • Object
  • Null
  • Undefined
  • Symbol

JavaScript Primitive or Non-Primitive Datatypes

Primitive:

  • Boolean
  • Number
  • String
  • Null
  • Undefined

Non-Primitive:

  • Object
  • Date
  • Array

JavaScript Vs JScript

Both JavaScript and Jscript designed for to make web page More dynamic.

JavaScript: JavaScript is a scripting language developed by Netscape Communications designed for developing client and server Internet applications.

JScript: JScript is owned by Microsoft and used in one of the most popular web browser Microsoft’s Internet Explorer. JScript can also be called “Microsoft’s JavaScript”.

Pros & Cons of JS

Pros Cons
Fast to the end user Security Flows on user end
Simplicity More and better Competitor
Versatility File Download [JavaScript file is download on client machine so anyone can read the code and reuse it.]

JavaScript Where to Add

There are 3 ways to attach javascript with web pages or HTML Documents

  • Inline: use by html events attributes.
    • Example:
      <input type="button" onclick="alert("This alert call by inline Java Script");">
  • Internal: JS embed in <head> or <body> tag using <script> tag.
    • Example:
      // use javascript in head section
      <head>
          <script>
              function myFunction() {
                  alert("This alert call by internal Java Script");
              } 
          /<script>
      </head>
      
      // use javascript in body tag before closing body section 
      <body>
         
          <p>...</p>
          <h2>...</h2>
          
          
          <script>
              function myFunction() {
                  alert("This alert call by internal Java Script");
              } 
          /<script>
      </body>
      
      
  • External: JS use by <link> tag inside <head> section. External JavaScript file save with .js extension.
    • Example:
      <head>
          <link href="/script.js">
      </head>
      

JavaScript Statement

A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are called "statements".

JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

The statements are executed, one by one, in the same order as they are written.


JavaScript Syntax

JavaScript syntax is the set of rules, how JavaScript programs are constructed.

var a, b, c;       // Declare Variables
a = 5; b = 6;      // Assign Values
c = a + b;         // Compute Values

document.write(c); // output on HTML document
document.log(c);   // output on browser console tab


JavaScript Keywords

JavaScript keywords are used to identify actions to be performed.

Example:

"var" keyword is identifiy to perform declaration of variable.
"function" keyword is identify to perform function statement.


JavaScript Variables

In a programming language, variables are used to store data values.


JavaScript Operators

An operator is a character that represents an action.

in javascript have many types of operators:

Operators Symbols
Arithmetic Operators +, -, *, /, %, ++, --
Comparison Operators ==, !=, >, <, <=, >=, ===
Arithmetic Operators +, -, *, /, %, ++, --
Logical Operators &&, ||, !
Bitwise Operators &, |, ^, ~, <<, >>, >>>
Conditional Operator ? : (if condition is true ? then value is X : otherwise value is Y)
Assignment Operators =, +=, -=, *=, /=, %=

JavaScript Expression

An expression is a combination of values, variables, and operators, which computes to a value.


JavaScript Comment

Single Line Comment: denoted by //
Multiline Comment: start with /* and end with */


Important Questions?


  • strict mode in JavaScript
    • It allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

    • Example:
      'use strict';
      var str = "Hello World";
      document.write(str);
      

  • Scope of variable in JavaScript
    • The scope of a variable is controlled by the location of the variable declaration, and defines the part of the program where a particular variable is accessible.
      JavaScript has two scopes:
    • Global Scope
      Local Scope

  • What is === Operator?
    • The "===" operator is a binary logical operator to check whether the two values are same and are of same data type. It will return false even when their values are equal but they are not of same data type.
      For Example: 555 and '555', according to the values are same but they are not of same data type, hence === will return false.

  • Difference b/w null & undefined
    • undefined means a variable has been declared but has not yet been assigned a value.
      Example: var a;
    • null null is an assignment value. It can be assigned to a variable as a representation of null(no) value:
      Example: var a = null;

  • What are JavaScript Cookies?
    • JavaScript cookies are the small test files stored in your system and it gets created when the user visits the websites to store information that they need.

  • Nan & isNan()?
    • isNaN() function determines whether a value is an illegal number (Not-a-Number).
    • NaNThe NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.

  • Conversion String to Number & Number to String
    • String to Number

      • parseInt(): It accepts two arguments. The first argument is the "string" to convert. The second argument is called the "radix." This is the base number used in mathematical systems.
      • var text = '42px';
        var integer = parseInt(text, 10);
        // returns 42
      • parseFloat(): Convert string into a point number.
      • var text = '42.35px';
        var integer = parseInt(text);
        // returns 42.35
      • Number(): Sometimes it’s an integer. Other times it’s a point number. And if you pass in a string with random text in it, you’ll get NaN(Not-a-Number).
      • Number('123'); // returns 123
        Number('12.3'); // returns 12.3
        Number('42px'); // returns NaN

    • Number to String
      • toString(): method converts a number to a string.
      • var num = 15;
        var n = num.toString();

  • Client Side Vs Server Side JS
    • Client Side: JavaScript that enables the enhancement and manipulation of web pages and client browsers. In a browser environment , your code will have access to things provided only by the browser. The main tasks of Client side JavaScript are validating input, animation, manipulating UI elements, applying styles, some calculations are done when you don't want the page to refresh so often.
    • Server Side: JavaScript that enables back-end access to databases, file systems, and servers. Server side javascript, is javascript code running over a server local resources.

  • DOM
    • DOM which is short for "Document Object Model", is the specification for how objects in a web page should appear. It is an interface that allows a programming language to manipulate the content, structure, and style of a website.

PHP?

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.

  • PHP is an acronym for "PHP: Hypertext Preprocessor"
  • PHP is a widely-used, open source scripting language
  • PHP scripts are executed on the server
  • PHP is free to download and use
  • PHP 7 is the latest stable release.

PHP File?

  • PHP files can contain text, HTML, CSS, JavaScript, and PHP code.
  • PHP code is executed on the server, and the result is returned to the browser as plain HTML.
  • PHP files have extension ".php".

PHP Do?

  • PHP can generate dynamic page content
  • PHP can create, open, read, write, delete, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can be used to control user-access
  • PHP can encrypt data

Install PHP on local system

Some tools required for installation of PHP.

  • PHP
  • Apache Server
  • MySQL Database
  • Text Editor
  • Browser

PHP, Apache, MySQL all are available in XAMPP or WAMP server.


What is Apache?

Apache is an open-source and free web server software. The official name is Apache HTTP Server. Apache is a cross-platform software, therefore it works on both Unix and Windows servers. It allows website owners to serve content on the web — hence the name “web server.” It’s one of the oldest and most reliable web servers, with the first version released more than 20 years ago, in 1995.
we call Apache a web server, it is not a physical server, but rather a software that runs on a server. Its job is to establish a connection between a server and the browsers of website visitors.


WAMP & XAMPP stands for?

WAMP: Windows, Apache, MySQL, PHP

XAMPP: Cross-Platform, Apache, MySQL, PHP and Perl


PHP Syntax

Recommended Use: <? php ?>

<body>
    <ul>
        <?php for($i=1;$i<=5;$i++){ ?>
            <li> Menu Item <?php echo $i; ?> </li>
        <?php } ?>
    <ul>
</body>
output:
Menu Item 1
Menu Item 2
Menu Item 3
Menu Item 4
Menu Item 5

Short Tag: <?= ?>

If you want to shorten your code as much as possible, you can go for the short_tags option. This will save you from typing <?php at the beginning of the code, shortening it to just <?. In order to enable this, you should update the php.ini file and turn the "short_tags" setting from "Off" to "On"

<body>
    <p>Hello, today is <?= date('Y/m/d H:i:s'); ?>.</p>
</body>
output:
2012/03/06 17:33:07

PHP Variables

Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter a,b,c,..., or the underscore _ character
  • A variable name cannot start with a number 0,1,2,...
  • A variable name can only contain alpha-numeric characters and underscores
  • Variable names are case-sensitive ($name and $Name are two different variables)

PHP echo & print

With PHP, there are two basic ways to get output: echo and print.

echo Example:
<php
$txt1 = "Learn Web Programming";
$txt2 = "thenanosoft.github.io/WD-6B";
$x = 5;
$y = 4;

echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
echo Example:
<php
$txt1 = "Learn Web Programming";
$txt2 = "thenanosoft.github.io/WD-6B";
$x = 5;
$y = 4;

print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
Note: For concatenation string we use ‘.’ dot operator

PHP String Functions

Function Description
strlen() Return the Length of a String
<?php
echo strlen("Hello world!"); // outputs 12
?>
str_word_count() Count Words in a String
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
strrev() Reverse a String
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
strpos() Search For a Text Within a String
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
str_replace() Replace Text Within a String
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>

WordPress?

WordPress (WordPress.org) is a free and open-source content management system (CMS) written in PHP and paired with a MySQL or MariaDB database.


WordPress Features?

  • Simplicity makes it possible for you to get online and get publishing, quickly.
  • Flexibility to make any type of website
  • Publish with Ease You can create Posts and Pages, format them easily, insert media, and with the click of a button your content is live and on the web.
  • Publishing Tools Create drafts, schedule publication, and look at your post revisions. Make your content public or private, and secure posts and pages with a password.
  • User Management Not everyone requires the same access to your website. Administrators, editors, authors & contributors and subscriber users, for each user have different rules & regulation
  • Easy Theme System WordPress comes bundled with three default themes. Single click to install new theme.
  • Extend with Plugins WordPress comes packed with a lot of features for every user. For every feature that’s not in WordPress core, there’s a plugin directory with thousands of plugins.
  • any many more features available on wordpress

WordPress Theme

WordPress users may install and switch among different themes. Themes allow users to change the look and functionality of a WordPress website without altering the core code or site content. Every WordPress website requires at least one theme to be present.


WordPress Plugin

WordPress plugin architecture allows users to extend the features and functionality of a website or blog. As of January 2021, WordPress.org has 58,164 plugins available


WordPress.org Vs WordPress.com

WordPress.org you host your own site.

WordPress.com that takes care of all of this for you (easier to start, less freedom). And that’s the major difference.

Wordpress.com vs wordpress.org

My SQL?

MySQL is the most popular database system used with PHP. The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows. Databases are useful for storing information.

  • MySQL Open Source & Free
  • Easy to use
  • Very Popular

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

MySQL compiles on a number of platforms.

MySQL is free to download and use.

MySQL is developed, distributed, and supported by Oracle Corporation.

MySQL is named after co-founder Monty Widenius's daughter. My


Basic Terminologies

  • Database
  • Table
  • Column
  • Row
  • Field
  • Index
  • Foreign Key

Difference b/w Database & Spreadsheet

  • Spreadsheets: are optimized for adding numbers.
  • Database: are optimized for working data.

What is CRUD

  • C: Create
  • R: Read
  • U: Update
  • D: Delete

Manipulating MySQL Databases

  • Select
  • Insert
  • Delete
  • Update

PHP Connect to MySQL

PHP 5 and later can work with a MySQL database using:

  • MySQL extension (Original MySQL API)
  • MySQLi extension (the "i" stands for improved API)
  • PDO (PHP Data Objects)
  • Steps for Connection PHP to Database

  • Create a database connection
  • Perform database query
  • Use returned data (if want)
  • Release returned data
  • Close database connection
  • Function for Connection

  • mysqli_connect()
  • mysqli_connect_errorno()
  • mysqli_connect_error()
  • mysqli_close()

  • Creating & Checking database connection

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $databasename);
    // Check connection
    if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
    }
    echo "Connected successfully";
    ?>

    Only checking database connection

    <?php
    $conn = mysqli_connect($servername, $username, $password, $databasename);
    // Check connection
    if (mysqli_connect_errno()) {
    die("Connection Field");
    }
    else {
    echo("Connection Established");
    }
    ?>


    Closing database connection

    <?php
    mysqli_close($conn);
    ?>

    Function for query database

  • mysqli_query()
    • <?php
      // Perform query
      $query = "SELECT * FROM Persons";
      $result = mysqli_query($con, $query);
      if (!($result)) {
      die("database query failed.");
      }
      else {
      echo("database query passed.");
      }
      ?>
  • mysqli_fetch_row()
    • <?php
      <body>
      while($row = mysqli_fetch_row($result)){
      var_dump($row);
      echo “<hr />;
      }
      </body>
      ?>
  • mysqli_free_result() [release return data]
    • <?php
      mysqli_free_result($result);
      ?>

    Query Details:

  • mysqli_query(): The mysqli_query() function accepts a string value representing a query as one of the parameters and, executes/performs the given query on the database.
  • mysqli_query($conn, $query)

  • mysqli_fetch_row(): function fetches one row from a result-set and returns it as an enumerated array.
  • mysql_fetch_row($result);

  • mysqli_fetch_assoc(): Fetch a result row as an associative array.
  • mysqli_fetch_assoc($result)

  • mysqli_fetch_array(): Fetch a result row as a numeric array and as an associative array.
  • mysqli_fetch_assoc($result, $resulttype)
    where $result is mysql query & connection "result", and $resulttype Specifies what type of array that should be produced.

    Mid Quiz

    1. What tag is used to display a picture in an html page.
      • img
    2. Apart from 'b' tag what other tag makes text bold?
      • strong
    3. Which html tag is used to define an internel style sheet?
      • style
    4. Which is correct CSS syntax?
      • body {color:black;}
    5. How to you display hyperlinks without and underline?
      • a{text-decoration:none;}
    6. The externel javascript file must contain script tag?
      • False
    7. Which property is used to change the font of an element?
      • font-family
    8. Which property is used to change the left margin of an element?
      • margin-left
    9. Html web pages can be read and rendered by?
      • web browser
    10. When using the padding property are you allowed to use negative values?
      • False
    11. How do you select elements with class name 'test'?
      • .test
    12. Tags and texts are not directly displayed on the page are return in ______ section?
      • head
    13. Which is the correct CSS syntax for making all the P elements bold?
      • P {font-weight:bold;}
    14. Which html tag used the biggest heading?
      • h1
    15. Which html attributes is used to define inline style?
      • style
    16. Fundamental html block is known as?
      • html tags
    17. Html is what type of language?
      • markup language
    18. Which property is used to change the background color in CSS?
      • background-color
    19. Html uses
      • fixed-tag-define by langauge
    20. Hoe do you make a list that list its item with squares?
      • list-style-type:square;
    21. How do you create a function in javascript?
      • function myfun() {}
    22. How do you use select an element with id 'demo'?
      • #demo
    23. How do you add a background color for all h1 elements?
      • h1{backgroound-color:red;}
    24. How do you make a text bold:
      • font-weight:bold
    25. How do you make each word in a text start with a capital letter?
      • text-transform:capitalize;
    26. Which is the correct way to write a javascript aray?
      • var colors = ["red", "green", "blue"]
    27. How can you make a number list?
      • ol
    28. What is correct HTML for reffering to an external style sheet
      • <link href="mystyle.css">
    29. What is correct JavaScript syntax to change the content of the HTML element below < p id="demo" > This is a value </p>
      • document.getElementById("demo").innerHTML = "Hello World";

    Address


    Rahim Yar Khan, Punjab, Pakistan.