• No results found

Web Programing PHP & MYSQL. Halabja University Collage of Science /Computer Science Department CHAPTER TWO. Karwan Mahdi

N/A
N/A
Protected

Academic year: 2021

Share "Web Programing PHP & MYSQL. Halabja University Collage of Science /Computer Science Department CHAPTER TWO. Karwan Mahdi"

Copied!
32
0
0

Loading.... (view fulltext now)

Full text

(1)

Halabja University

Collage of Science /Computer Science Department

Web Programing

2020-2021

Karwan Mahdi

[email protected]

CHAPTER TWO

PHP & MYSQL

(2)

 Every Website sits on a computer known as a Web server. There are other Web Servers

also available in the market but they are very expensive.

 Apache HTTP Server

• This is the most popular web server in the world

developed by the Apache Software Foundation

• It is an open source software and can be installed

on almost all operating systems

• About 60% of the web server machines run the

Apache Web Server.

 Internet Information Services

• (IIS) is a high performance Web Server from Microsoft.

• This web server runs on Windows.

 Sun Java System Web Server

• This web server from Sun Microsystems is suited for medium and large websites.

• It is not open source, required for Web 2.0 such as JSP, Java Servlets.

(3)

XAMPP

XAMPP stands for Cross-Platform (X), Apache (A), MySQL (M), PHP (P) and Perl (P).

1. Apache:

•Apache is the actual web server application that processes and delivers web content to a

computer.

2. MySQL:

•Every web application, howsoever simple or complicated, requires a database for storing

collected data.

•MySQL is open source, is the world’s most popular database management system.

3. PHP:

•PHP stands for Hypertext Preprocessor. It is a server-side scripting language.

•It is open source, relatively easy to learn, and works perfectly with MySQL

4. Perl:

(4)

How to Install XAMPP?

 It is available on internet (Free to download).

 Disable your anti-virus as it can cause some XAMPP components to behave erratically.

 Disable User Account Control (UAC). UAC limits write permissions to XAMPP’s default

installation directory (c:/XAMPP).

 The XAMPP control panel gives

you complete control over all installed

XAMPP components.

 You can use the CP to start/stop

different modules.

 Create test.php file in C:\xampp\htdocs

 Write this code <?php echo ”Hello word”; ?>

(5)

 It is open source scripting language that are executed on the server

 It can generate dynamic page content and manipulate data from database

 PHP can collect form data and it can be used to control user-access

 It can create, open, read, write, delete, and close files on the server

 It can access cookies variables, session tracking and set them.

(6)

Why PHP

•PHP runs on various platforms (Windows, Linux, Unix, Mac OS X)

•PHP is compatible with almost all servers used today (Apache, IIS)

•PHP supports a wide range of databases

(MySQL, Oracle, Microsoft SQL Server and SQLite.)

•PHP is free to download(

http://php.net/manual/en/install.php)

.

•Stable: Since it is maintained by many developers,

so when bugs are found, it can be quickly fixed.

•Powerful library support: You can easily find

functional modules you need such as PDF, Graph etc.

(7)

PHP 5 VS later version

PHP 7.3.3 is the newest version of PHP and it is much faster than the previous popular stable release!  Release date was 6 March 2019 and will be supported until 6 December 2021.

The last versions of php has improved Error Handling, supports stricter Type Declarations and supports new operators, methods and properties.

(8)

Escaping to PHP

There are four ways to write PHP code

 Canonical PHP tags: This is always correctly interpreted.

<?php……. ?>

 Short-open (SGML-style) tags

<? …… ?>

•Choose the --enable-short-tags configuration

•Set the short_open_tag setting in your php.ini file to on

 ASP-style tags

<% ……%>

•You will need to set the configuration option in your php.ini file.

 HTML script tags

(9)

Commenting PHP Code

 A comment in PHP code is a line that is not read/executed as part of the program

 It is only for the human reader, to let others understand what you are doing and remind

yourself of what did you do

 PHP supports several ways of commenting:

Single-line comments

They are generally used for short explanations or notes

Multi-lines comments−

 They are generally used to provide code algorithms and more detailed explanations

when necessary.

# This is a comment

// This is a comment too. Each style comments only

(10)

PHP -Variable Types

 The main way to store information in the middle of a PHP program is by using a variable.

 Rules for naming a variable:

•A variable starts with the

$

sign, followed by the name of the variable

•Variable names must begin with a letter or underscore character.

•A variable name can consist of numbers, letters, underscores but you cannot use

characters like + , -, % , ( , ) . & , etc.

• NO keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are case-sensitive.

•Variable names are case-sensitive($text and $TEXT are two different variables)

$

text = "Hello world!";

$

x = 10;

$

y = 3.5;

 PHP is a Loosely Typed Language

 PHP automatically converts the variable to the correct data type, depending on its value.

(11)

PHP -Data Types

PHP has a total of eight data types which we use to construct our variables

 Integers

•are whole numbers, without a decimal point

•An integer cannot contain comma or blanks

•An integer can be either positive or negative

•It is a number between -2,147,483,648 and +2,147,483,647.

 Float

is a number with a decimal point or a number in exponential form.

•By default, doubles print with the minimum number of decimal places needed. For example,

 Boolean

(12)

 Interpreting other types as Booleans

•If the value is a number, it is false if exactly equal to zero and true otherwise.

•If the value is a string, it is false if the string is empty(has zero characters) or is the string

"0", and is true otherwise.

•Valid resources are true (although some functions that return resources when they are

successful will return FALSE when unsuccessful).

•Values of type NULL are always false.

•Don't use double as Booleans.

PHP -Data Types

 NULL

•NULL is a special type that only has one value: NULL.

•it is case insensitive $my_var= null; $my_var= NULL;

•It returns FALSE when tested with IsSet() function.

(13)

 String

•They are sequences of characters, PHP supports string operations

•A string can be any text inside quotes. You can use single or double quotes

PHP -Data Types

 String Concatenation

To concatenate two string variables together, use the dot (.) operator

 The Length of a String

The strlen() function is used to find the

length of a string.

 Reverse a String

The PHP strrev() function reverses a string:

 Other functions:

str_word_count( ), strops( ), str_replace( )

(14)

Echo and print Statements

Print

and

echo

are used to display the output.

$name=“hello world”;

echo $name; echo ($name); //or print ($name); print $name;

 echo can pass multiple string separated as ( , ) but print can’t

$name = "Ravi "; $age=20;

echo $name , $age " years old";

 print always return 1,but echo doesn’t return any value

$return=print $name;

but $return = echo $name;

 echo is faster then print

 The text can contain HTML markup

echo "<h2>PHP is Fun!</h2>";

(15)

Print Document

Multiple lines to a single string

 You can assign multiple lines to a single string variable using adocument

<?php

$channel =“<?XML <channel>

<title>What's For Dinner</title>

<link>http://menu.example.com/ </link> <description>Choose what to eat

tonight.</description> </channel>”;

echo <<<END

This uses the "document"noextra whitespace! END;

print "<br>";

print $channel; ?>

This uses the "document“ no extra whitespace! What's For Dinner http://menu.example.com/ Choose what to eat tonight

Object in PHP

(16)

 An array is a special variable that stores one or more similar type of values in a single value.

For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

 In PHP, the array() function is used to create an array array();  There are three types of arrays:

• Indexed arrays - Arrays with a numeric index • Associative arrays - Arrays with named keys

• Multidimensional arrays - Arrays containing one or more arrays

(17)

An array is a special variable, which can hold more than one value at a time. It means an array stores multiple values in one single variable:

Array types in PHP

Indexed arrays - Arrays with a numeric index Two ways to create indexed arrays:

Associative arrays - Arrays with named keys Two ways to create Associative arrays :

(18)

Multidimensional arrays - Arrays containing one or more arrays

Arrays in php(conti…)

 Multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage.

(19)

 A constant is a name or an identifier for a simple value(username, version )

 A constant value cannot be changed or undefined during the execution of the script

 It can be started with a letter or underscore, followed by any number of letters, numbers, or underscores  A constant is case-sensitive. By convention, constant identifiers are always uppercase

 To define a constant you have to use define( ) function and to retrieve the value of a constant Constants may be defined and accessed anywhere without regard to variable scoping rules.

Constant

1) sort( ) - sort arrays in ascending order

2) rsort( ) - sort arrays in descending order

1) asort( ) - sort associative arrays in ascending order, according to the value

2) ksort( ) - sort associative arrays in ascending order, according to the key

3) arsort( ) - sort associative arrays in descending order, according to the value

4) krsort( ) - sort associative arrays in descending order, according to the key

(20)

Variable Scope

 In PHP, variables can be declared anywhere in the script

 PHP variables can be one of four scope types

Local Variables

•A variable declared within a function has a LOCAL SCOPE and can only be accessed

within that function

•Any assignment outside of that function will be considered to be an entirely different

variable from the one contained in the function

Global Variables

 A variable declared outside a function has a GLOBAL SCOPE and can only be accessed

outside a function

(21)

Static Variables

 Astatic variable will not lose its value when the function exits and will still hold that

value should the function be called again.

 Use the static keyword when you first declare the variable

Function Parameters

 Function parameters are declared after the function name and inside parentheses. You can add as many arguments as you want, just separate them with a comma.

 Use the return statement to return a value.  If we call the function without arguments

it takes the default value as argument:

Dynamic Function Calls: It is possible to assign

(22)

Operators are used to perform operations on variables and values. PHP language supports following type of operators:

 Arithmetic Operators

 Comparison Operators

 Logical (or Relational) Operators

 Assignment Operators

 Conditional (or ternary) Operators

 Increment/Decrement operators

Operators

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the $y'th power (Introduced in PHP 5.6)

(23)

Comparison Operators

Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type != Not equal $x != $y Returns true if $x is not equal to $y

< > Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type

> Greater than $x > $y Returns true if $x is greater than $y < Less than $x < $y Returns true if $x is less than $y

>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y <= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y

Operator Name Example Result

.

Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2

.=

Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

(24)

Logical Operators

Operator Name Example Result

and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both && And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

Assignment Operators

Assignment Description Result

x = y The left operand gets set to the value of the expression on the right x = y

x += y Addition x = x + y

x -= y Subtraction x = x - y

x *= y Multiplication x = x * y

x /= y Division x = x / y

(25)

Conditional Operator

Increment / Decrement Operators

Operator Description Example

? : Conditional

Expression If Condition is true ? Then value $X : Otherwise value $Y

Operator Name Description

(26)

 Like most programming languages, PHP also allows you to write code that perform different actions based on the results of a logical or comparative test conditions at run time.

 You can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions. There are several statements in PHP that you can use to make decisions: (if, if...else, if...elseif....else and The switch...case statement)

Decision Making

Limitation of Switch over if-else

 The variable expression are also not allowed in cases.

case $i+2: is not allowed in switch, but is valid on if-else Advantages of switch over if-else

 A switch statement works much faster than equivalent if-else ladder.

(It is because compiler generates a jump table for a switch during compilation. Consequently, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.)  It is more readable and in compare to if-else statements.

• If there are large number of compares for a condition in your program, use switch over if-else ladder.

(27)

 if statement - executes some code only if a specified condition is true

 if...else statement - executes some code if a condition is true and another code if the condition is false

 if...elseif....else statement - specifies a new condition to test, if the first condition is false

if...else...elseif Statements

(28)

Loops in PHP are used to execute the same block of code a specified number of times while the specified

condition is true. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task

PHP supports following four loop types.

• for - loops through a block of code a specified number of times.

• while - loops through a block of code if and as long as a specified condition is true.

• do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true. • foreach - loops through a block of code for each element in an array.

Loop Types

For loop statement

Parameters:

• init counter: Initialize the loop counter value • test counter: Evaluated for each loop iteration.

If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.

(29)

The while statement will execute a block of code if and as long as a test expression is true.  If the test expression is true then the code block will be executed.

 After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

While and

do...while

loop statement

(30)

 The foreach statement is used to loop through arrays.

 For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element

foreach loop statement

Break statement

(31)

Continue statement

 The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.

 For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.

HTML Forms

 HTML Forms are required when you want to collect some data from the site visitor. example during user

registration you would like to collect information such as name, email address, credit card, etc. When the

(32)

 There are two ways the browser client can send information to the web server.

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. The GET method produces a long string that appears in your server logs, in the browser's Location: box.

 The GET method is restricted to send up to 1024 characters only. Never use GET method if you have password or other sensitive information to be sent to the server.

 GET can't be used to send binary data, like images or word documents, to the server. The data sent by GET method can be accessed using QUERY_STRING environment variable.

Form Method (GET)

 The POST method transfers information via HTTP headers. And the POST method does not have any restriction on data size to be sent.

 The POST method can be used to send ASCII as well as binary data. The data sent by POST

method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.

 The information is encoded as described in case of GET method and put into a header called QUERY_STRING. Never Cached ,parameters are not saved in browser history and also can not be bookmarked

References

Related documents

“With Ruby and Rails we went from nothing to a live site from nothing to a live site in about in about 3 months 3 months. Only one person in the company had any prior Ruby

One of the best ways to guarantee paid gigs as a notary is by becoming a loan signing agent A loan signing agent is a notary public that is present when loan documents are signed

In the following SQL IF Statement, it evaluates the expression, and if the condition is true, then it executes the statement mentioned in IF block otherwise statements within

However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access

• Condition that if evaluates to true, execute the following code block (same as while); end condition should be something you can reach later, otherwise you will be stuck in

Recent work suggests that learning-related emotions (LREs) play a crucial role in performance especially in the first year of university, a period of transition for

The created Scene can then be used to create an Exploded view in a CATDrawing The Assembly Product unaffected by the Explode command used in the Scene Exploded Scene Scene attached

Keywords: uncertainty quantification; stochastic partial differential equations; elastic wave equation; regularity; collocation method; error analysis.. AMS Subject