Chapter One (Full)
Chapter One (Full)
- Dynamic Content
Server Side vs Client Side
Programming Languages
Client side scripts
• Are executed by the client, particularly by the
browser
• They are used for appearance and behavior of a
web page
• It has little or no access to the underlying operating
system
• Some features may not work or properly rendered
on specific browser(s)
Cont…
• What is server side scripting language ?
– a server-side scripting language is a script that is
executed on the server as apposed to client-side
scripting languages like JavaScript
– It requires server-side scripting engine
– It has full access to the server operating system
– there are variety of them like PHP, Python, Ruby,
C#, NodeJS, etc….
When to use server-side scripting
• When developing Dynamic web pages
• Authentication, authorization and session
tracking.
• Template-driven page generation. Including
repeated content like header/footers and
navigation menus around the “content area”
of a web page.
Cont.….
• Personalization and customization of content based
on authentication and authorization. This also
includes the serving of content based on the content
of the page (e.g. YouTube, Amazon, Facebook) or the
browsing behavior of the user.
• Handling POST form input
• Communication with other programs, libraries and
APIs – e.g. sending out e-mail
PHP
• It is server-side scripting language
• It is not visible to visitors
• It should be saved with .php extension
• It is denoted in a page with opening and
closing tags as follows
<?php
?>
• Every statement ends with a semicolon
Cont.…
• Example
<?php
// First line of code goes here;
// Second line of code goes here;
// Third line of code goes here;
?>
• Commenting
– Single line (//) or multiple line (/* -----*/)
Cont.….
• Creating the first program.
<html>
<head>
</head>
<body>
<?Php
echo “ hello there”;
?>
</body>
</html>
Cont.….
• PHP script can be emended into HTML page.
• Pitfalls:-
– Double quotes
• Use \” escaping character or single quote.
– Remember that you still have to follow PHP rules,
even though you’re coding in HTML.
• echo “<font size=\”2\”>”;
– Don’t try to cram too much HTML into your PHP
sections.
Variables and Constants
• It is case-sensitive.
• Variable declaration rules are applied.
– A variable starts with the $ sign, followed by the name of
the variable
– A variable name must start with a letter or the underscore
character
– A variable name cannot start with a number
– A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
– Variable names are case-sensitive ($age and $AGE are two
different variables)
Cont.…..
• A value in a variable is displayed using echo or print
statement.
• PHP also supports static variables. E.g. static $x = 0
• Variables have global and local scopes.
• define (“FAVMOVIE”, “The Life of Brian”);
e.g. echo “My favorite movie is “;
echo FAVMOVIE;
• Variables are denoted with a dollar sign ($).
• $num = 5;
• It is loosely typed language.
PHP data types
• PHP supports the following data types:
– String
– Integer - It is a number between -2,147,483,648 and
+2,147,483,647.
– Float (floating point numbers - also called double)
– Boolean
– Array
– Object
– NULL
• Reading Assignment : - string methods.
Cont.….
• Built in math functions.
– Rand([min],[max]);
– Ceil(number) Round numbers up to the nearest
integer;
– Floor(number) Round numbers down to the
nearest integer;
– Max(arg1, arg2);
– min(arg1,arg2);
Passing variables between pages
• $_GET
• $_POST
• $_REQUEST
• $_FILES
• $_SESSION
Control Structure
• Control structures determine the flow of code
within an application.
• Conditional statement
if (expression) {
statement
}
Cont.…..
if (expression) {
statement
}
else{
statement
}
Cont.….
switch($variable) {
case “expression 1":
statement(s)
break;
case “expression 2":
statement(s)
break;
default:
statement(s)
}
Looping
• While
while (expression) {
statements
}
• For
for(expression1;expression2;expressio
n3) {
statements
}
Break and Continue
• Encountering a break statement will
immediately end execution of a do...while, for,
foreach, switch, or while block.
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Cont…..
• Connecting to MySQL through PDO
– PDO requires provider and database (Data Source Name) in
addition to address, username and password of the database
server to connect
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Executing Query
• MySQLi
$sql = “create database db_name”;
$conn → query($sql);
– Query method returns true if the query executed
successfully, otherwise returns false
• PDO
– $conn → exec($sql);
Class
• It is a data type.
• Collection of objects.
• It is composed of fields and methods.
• E.g. class classname
{
// Field declarations defined here
// Method declarations defined here
}
Objects
• Is an instance of a class.
• The practice of creating objects based on
predefined classes is often referred to as class
instantiation.
• Objects are created using the new keyword.
• E.g.
– $employee = new Staff();
Invoking Fields
• Fields are referred to using the -> operator and, unlike
variables, are not prefaced with a dollar sign.
• Syntax:-
– $object->field
• When you refer to a field from within the class in
which it is defined, it is still prefaced with the ->
operator, although instead of correlating it to the
class name, you use the $this keyword.
Cont.…..
Field Scopes
– PHP supports five class field scopes: public, private,
protected, final, and static.
– Public
• Public fields can then be manipulated and accessed directly
by a corresponding object.
– Private
• Private fields are only accessible from within the class in
which they are defined.
– Protected
• Protected fields are also made available to inherited classes
for access and manipulation, a trait not shared by private
fields.
– final
Methods
• A method is quite similar to a function, except
that it is intended to define the behavior of a
particular class.
• E.g. public [function scope] function
functionName()
{
/* Function body goes here */
}
$object->method_name();
Constructors
• It is a block of code that automatically
executes at the time of object instantiation.
• PHP recognizes constructors by the name
__construct.
• Syntax:-
function __construct([argument1, argument2, ..., argumentN])
{
/* Class initialization code */
}
Static Class Members
• Static members of a class are shared by
multiple objects and they belong to a class.
• Syntax:-
– Public static variable_name;
– Static function function_name(){}
• Autoloading Objects
– require_once("classes/Books.class.php");
Session
• The Hypertext Transfer Protocol (HTTP) defines the rules
used to transfer text, graphics, video, and all other data
via the World Wide Web.
• It is a stateless protocol, meaning that each request is
processed without any knowledge of any prior or future
requests.
• means that by default, any two requests are handled
completely independently, regardless if they come from
the same address, request the same resource.
• The solution for the above problem are cookies and
sessions.
Cont.…..
• It is a means to solve the problem of
statelessness.
• This is accomplished by assigning each site
visitor a unique identifying attribute, known as
the session ID (SID), and then correlating that
SID with any number of other pieces of data,
be it number of monthly visits, favorite
background color, or middle name.
Starting a Session & VDestroying a
Session
• Use the session_start() function to create
session.
• Use session_destroy() function for destroying
a session.
Creating and Deleting Session
Variables
• Use $_SESSION super global array to create
session.
• To delete use unset(variable name);
– E.g.
<?php
session_start();
$_SESSION['username'] = "jason";
echo "Your username is ".$_SESSION['username'].".";
?>
Cont.….
<?php
session_start();
$_SESSION['username'] = "jason";
echo "Your username is: ".$_SESSION['username'].".<br />";
unset($_SESSION['username']);
echo "Username now set to: ".$_SESSION['username'].".";
?>