Intro to PHP & MySQL
2020/21 COMP3322 Modern Technologies on WWW
Contents
• Server-side Technologies
• A quick tour of PHP
• Common server-side scripting scenarios • Intro to MySQL
• Session & Cookie
2
Server-side Scripting
• “Server-side scripting is a technique used in web development which involves employing scripts on a web server which produce a response customized for each client’s request to the website.” – from Wikipedia.
• Customized means dynamically generating content.
3
Common Server-side Technologies
• PHP
• Python
• Django • Ruby
• Ruby on Rails • ASP.NET
• Node.js
• Perl
https://www.similartech.com/categories
4
History of PHP development
• PHP is an open source technology and runs on most operating systems and with most Web servers.
• It takes most of its syntax from C, Java, and Perl.
• PHP was written in the C programming language by Rasmus Lerdorf in 1994.
• For managing his person information. For this reason, PHP originally stood for “Personal Home Page”.
• Rasmus released PHP 1.0 in 1995; he extended it to work with web forms and databases.
• A development team began to form and PHP 2 was released in late 1997.
• The acronym was formally changed to PHP: HyperText Preprocessor since then.
• PHP 3 was released in 1998 and PHP 4 was released in 2000.
• PHP 5 was released in 2004 and the latest PHP version is 7, which was released in 2015.
5
A Quick Tour of PHP
PHP: Hypertext Preprocessor
• PHP, like JavaScript, is a dynamically typed language.
• It uses classes and functions in a way consistent with other object-
oriented languages such as C++, C#, and Java.
• The syntax for loops, conditionals, and assignment is identical to JavaScript.
• Differs when you get to functions, classes, and in how you define variables.
7
PHP Tags
• The most important fact about PHP is that the programming code can be embedded directly within an HTML file.
• A PHP file will usually have the extension .php
• Programming code must be contained within
• an opening tag
• Any code outside the tags is echoed directly out to the client
• Onserverswithshorthandsupport,aPHPscriptcanstartwith and end with ?>
8
PHP Tags
php
$user =
?>
“Tony”;
Welcome
Current server time is
echo ““;
echo date(“H:i:s”);
echo ““;
?>
Welcome Tony
Current server time is 09:38:54
9
PHP Comments
10
Variables
• Variables in PHP are loosely typed in that a variable can be assigned different data types over time.
• Similar to JavaScript
• To declare a variable you must preface the variable name with the dollar
($) symbol.
• $count = 42;
• A variable name must start with a letter or the underscore character.
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive.
11
Variable Scope
• PHP has three different variable scopes: • Local scope
• Global scope • Static scope
• Local Scope
• A variable declared in a function can be referenced solely in that function.
12
Variable Scope
• Global Scope
• A variable defined in the main script (outside a function) has a GLOBAL SCOPE and can only be accessed outside a function.
• PHP does allow variables with global scope to be accessed within a function using the global keyword
13
Variable Scope
• Static Scope
• When a function is completed, all of its variables
are deleted.
• A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
• A static variable is initialized only in first call of the function.
14
Writing Output
• To output something that will be seen by the browser, you can use the echo() or print() function.
• echo(“hello”); or echo “hello”; OR • print(“hello”); or print “hello”;
• Output variables • echo $name;
• Another alternative is using the printf() function.
• Like the C programming language; also have the variations like sprintf() and
fprintf().
• printf(“
%s
\n”, $title);
https://www.w3schools.com/php/func_string_printf.asp
15
$course = array(
“code” => “COMP3322”,
“title” => “Modern Tech on WWW”, “sem” => 2,
“class” => “B”,
“teacher” => array(“last” => “Tam”,
“first” => “Anthony”));
Writing Output
• Debugging
• var_dump(), var_export(), and print_r() are functions that you can use to check values.
• var_dump() shows the values and their types of a variable. Arrays and objects are explored recursively with values indented to show structure.
• print_r() only shows the value in a human- readable format.
• var_export() like the above two, but it returns the information in a parsable string representation.
var_dump($course); array(5) {
[“code”]=>
string(8) “COMP3322” [“title”]=>
string(18) “Modern Tech on WWW” [“sem”]=>
int(2)
[“class”]=>
string(1) “B”
[“teacher”]=>
array(2) {
[“last”]=> string(3) “Tam” [“first”]=> string(7) “Anthony”
} }
print_r($course); Array
(
[code] => COMP3322
[title] => Modern Tech on WWW [sem] => 2
[class] => B
[teacher] => Array
(
[last] => Tam
[first] => Anthony )
) 16
“COMP3322”,
“title” => “Modern Tech on WWW”, “sem” => 2,
“class” => “B”,
“teacher” => array(“last” => “Tam”,
“first” => “Anthony”));
echo “output by ‘var_dump’
“; var_dump($course);
echo “
output by ‘print_r’
“; print_r($course);
echo “
output by ‘var_export’
“; var_export($course);
?>
Welcome to
Current server time is “;
echo date(“H:i:s”);
echo ““;
?>
https://i.cs.hku.hk/~atctam/c3322/PHP/debug.php
17
Data Types
Data Type
Description
boolean
A logical true or false value
integer
Whole numbers
Max. size is platform-dependent, but at least 32-bit.
float
Decimal numbers
Again platform-dependent; usually, in 64 bit IEEE format.
string
A sequence of characters (8 bits) enclosed in single or double quotes.
Array
An array in PHP is actually an ordered map.
It supports numeric array, associative array, and multi- dimensional array.
Object
Instances of programmer-defined classes.
Null
NULL is the only possible value of type null.
18
Case Sensitivity
• Case sensitive • variables
• constants
• array keys
• class properties
• Case insensitive • functions
• class constructors/methods
• keywords and constructs (e.g., if, else, echo, etc.)
19
Constants
define(“DB_HOST”, “localhost”); define(“DB_NAME”, “StudentDB”); define(“USERNAME”, “c3322”); define(“PASSWORD”, “ew#@rtycd”);
$db = mysqli_connect(DB_HOST, USERNAME, PASSWORD, DB_NAME); • Define the constant via the define() function
• Once a constant is defined, it can be referenced without using the $ symbol.
20
String
• A string can be any text inside quotes. You can use single or double quotes.
• String Concatenation
• Strings can easily be appended together using the concatenate operator,
which is the period (.) symbol.
• Alert! JavaScript uses the plus (+) symbol.
• Example:
• $username = “World”;
• echo”Hello”.$username; • WillOutput“HelloWorld”
21
String
• Difference between single quote and double quote strings. • Single quotes are used to denote a “literal string”.
• The system does not attempt to parse special characters or variables within the single quote string.
• You can add special characters (e.g., \n, \t) and variables in double quote string. The system understands.
• Example:
$username = “World”; echo “Hello $username”; Will Output “Hello World”
$username = “World”;
echo ‘Hello $username’; Will Output “Hello $username”
22
Arrays
• Defining an array
• $days = array();
• Thisdeclaresanemptyarray.
• You can initialize it with a comma-delimited list of values using either of two following syntaxes:
• $days = array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”); • $days = [“Mon”,”Tue”,”Wed”,”Thu”,”Fri”];
• You can also declare each subsequent element in the array individually: • $days = array();
• $days[0] = “Mon”;
• $days[1] = “Tue”;
• $days[] = “Wed”;
23
Arrays
• In most programming languages array keys are limited to integers, start at 0, and go up by 1.
• In PHP, array keys must be either integers or strings and need not be sequential.
• If you don’t explicitly define the keys, they are 0,1,…
• Fornumericindexes,youcanskipsomeindexes. • $menu[0] = “appetizer”;
• $menu[2] = “soup”;
• $menu[4] = “main course”; • $menu[8] = “dessert”;
• print_r($menu);
//Array([0] => appetizer [2] => soup [4] => main course [8] => dessert)
24
Arrays
• Associative Arrays
• $record = array(“name” => “Tony Stark”, “number” =>
“3015123456”, “age” => 20, “email” => “tonystark@hku.hk”);
• $record = [“name” => “Tony Stark”, “number” => “3015123456”, “age” => 20, “email” => “tonystark@hku.hk”];
• To loop through and print all the values of an associative array, we could use a foreach loop
foreach ($record as $x => $x_value) {
echo “Key=” . $x . “, Value=” . $x_value;
}
25
Superglobal Variables
• Superglobal
• Several predefined variables in PHP can always be accessible, regardless of scope.
• Commonly used superglobal variables are: • $_GET
• An associative array containing name/value pairs sent from the client with the GET method
• $_POST
• An associative array containing name/value pairs sent from the client with the POST method
• $_COOKIE
• An associative array containing cookie variables and values
• $_SESSION
• An associative array containing session
variables and values • $_REQUEST
• An associative array contains the contents of $_GET, $_POST and $_COOKIE
• $_SERVER
• An associative array contains information about request headers, paths, and script locations
https://www.w3schools.com/php/php_superglobals.asp
26
Include Files
• PHP provides four different statements for including files, as shown below.
• include “somefile.php”;
• include_once “somefile.php”; • require “somefile.php”;
• require_once “somefile.php”;
• The include and require statements are identical, except upon failure
• With include, a warning is displayed and then execution continues. With require, an error is displayed and execution stops.
27
The Scope of Include Files
• Include files are the equivalent of copying and pasting.
• Variables defined within an include file will have the scope of the
line on which the include occurs.
• Any variables available at that line in the calling file will be available within the called file.
• If the include occurs inside a function, then all of the code contained in the called file will behave as though it had been defined inside that function.
28
User Defined Functions in PHP
• A user-defined function declaration starts with the word function.
function functionName($arg1,$arg2,…..,$argX) { code to be executed;
}
• A function name must start with a letter or an underscore. Function names are NOT case-sensitive.
• Functions need not be defined before they are referenced.
• All functions in PHP have the global scope
• They can be called outside a function even if they were defined inside another function.
29
<
? <
User-Defined Functions
• Function parameters
• These parameters work like variables inside your function; in principle, they
are of dynamic type.
• Since PHP 7, it is possible to declare types for the function parameters.
• http://php.net/manual/en/functions.arguments.php#functions.arguments.type- declaration
• PHP supports passing arguments by value (the default), passing by reference, and default argument values.
• Pass by reference: function myFunction(&$arg) { . . . . }
30
Using JSON in PHP
• PHP has some built-in functions to handle JSON.
• Objects and arrays in PHP can be converted into JSON string by using:
$json_str = json_encode($php_obj); $json_str = json_encode($php_arr);
• Converting a JSON string into a PHP object or array by using: $anArray = json_decode($json_str, true);
$anObject = json_decode($json_str);
• In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
When TRUE, returned objects will be converted into associative arrays.
31
decode()
Breakfast at
Tiffany’s
}
$anObject = json_decode($json_str);
if (json_last_error() == JSON_ERROR_NONE) { echo $anObject->library->DVD[1]->title;
}
?>
//-> Contact
32
encode()
library->DVD[1]->title = “Avengers”;
$anObject->library->DVD[1]->genre = “Action”; $new_str = json_encode($anObject);
echo $new_str; ?>
//-> {“library”:{“DVD”:[{“id”:”1″,”title”:”Breakfast at Tiffany’s”,”format”:”Movie”,”genre”:”Classic”},{“id”:”2″,”title”:”Av engers”,”format”:”Movie”,”genre”:”Action”}]}}
33
Common Server-side Scripting Scenarios
Common Actions
Access data in the request
Perform the computation
• Validate the data
• Database accesses
Store/retrieve data
to/from database
• Compose the response
Keep state information
35
Demo 1 – Just Echo Back
Account Registration Form
Welcome
Welcome to the member area!
delete cookie
if (isset($_COOKIE[session_name()])) { setcookie(session_name(),”,time()-3600, ‘/’);
}
session_unset(); session_destroy();
}
?>
#Set redirection
header(‘location: login.php’);
81
References
• PHP Tutorial – Tutorialspoint.com
• https://www.tutorialspoint.com/php/index.
htm
• PHP 5 Tutorial – W3school.com
• https://www.w3schools.com/php/default.as
p
• PHP Manual
• https://secure.php.net/manual/en/index.php
• PHP The Right Way
• https://phptherightway.com/
• PHP MySQL – W3school.com
• https://www.w3schools.com/php/php_mys
ql_intro.asp
• PHP Session – zentut.com
• http://www.zentut.com/php-tutorial/php- session/
82