PHP Initiation - Soul Theory

stickyraffleΛογισμικό & κατασκευή λογ/κού

4 Νοε 2013 (πριν από 3 χρόνια και 7 μήνες)

54 εμφανίσεις

PHP

PHP is a server side scripting language which means it is processed on a server and the results are
returned to the computer screen.

PHP is very easy to learn and is necessary for web applications of all sizes.

PHP Initiation

To init
i
ate php

code use this syntax inside an .html, .asp, .php, etc.

file

wherever

you want it to be.


Declaration

and Assignment

Variables are used to store and transfer information from one page to another. In PHP, the values of
most variables can only be used on the page that called it. Once the page is refreshed, often times the
value of the

variable is lost. There are exceptions to this rule and we will go into them later.

Variables must first be
declared
. When a variable actually gets assigned a value that process is called
assignment
. To declare variables in PHP use this syntax:


$var is
not

the same as $Var. Capitalization matters. End
all
statements

in PHP with a
semicolon
.

<?php

//
This is a single line PHP comment. Two forward slashes.

/*

This is a block PHP comment

All of this information will not be passed when the .php file is call
ed.

*/

?>

<?php


$variable;






//Declaration


$tHisWorks;

$_thisalsoWorks123;

$amppTechnologies = “Some words.”; //This is declaration and assignment

$numb敲‽ 100;

?>


Variable Scope

PHP has four variable scopes:
local, global, static, parameter

Local variable
:

Variables declared within a function. Cannot be accessed outside a function.


Global variable
:

variables declared outside any function. Can be accessed from anywhere in a script
except
in a function. To access a global variable in a function use the
global

keyword.


Static variable
: a local variable inside a function that doesn’t lose its value once the function ends.

T
he
variable continues to keep the last value
assigned to it
.


Parameters:
a local variable whose value is

passed when the function is called.

<?php


function myTest()

{


$variable = 2;

//local variable

}

?>


<?php


$x=5;




//Global scope



function myTest()

{

global $x; //Pulls the global variable and now x can be used inside myTest
()


print $x;

}


?>


<?php


function myTest()

{

static $
x

= 1
;



print $x
++
;

//Prints x + 1 each time function is called

i.e. 1,2,3,4,etc.

}

?>


<?php


function myTest(
$
param1)

{



print
$
param1;

}

?>


Variable Data Types

PHP is an object oriented programming language. This means that everything is treated as an object that
we can manipulate.

There are different data types that PHP uses. We will mainly focus on these:



Strings

(text)





ex. $string = ‘Some text’;



Integers

(whole numbers)


ex. $int = 9;



Floating point numbers

(decimals) ex. $float = 2.15;



Arrays

(a li
st of elements with values) ex. $arr = array(0 => “This”, 1 => “Is Cool”);



Objects

(an abstract “thing”)



ex. $object = new ObjectClass();



Resources

(only used for the database connection)

N/A



Boolean

(true or false always)



NULL

( a value of nothing)

Strings and String Functions

Strings are lines of keyboard characters. There are two
basic

ways to create a string literal.


In some cases you will have to
escape

the string literal because the string contains single or double
quotes. Single quote strings
can
contain double quotes and double quotes
can
contain single quotes.
You only escape single quotes inside single quoted strings and double quotes inside double quoted
strings.
Here

is how to escape them to avoid PHP errors.


To concatenate strings together use the . operator.


Normally you will only be making queries to the database and returning strings to display on the page.
There will be very little, if any, manipulation to the data that’s already in the database so
there won’t be
many string functions you will need.


<?php

//Declare and initialize string literals


$var1 = ‘This is a single quoted string. It is used mainly

for static text.’;


$var2 = “This is a double quoted string. It is used mainly to parse variables within a string.”;

?>


<?php


$escapeSingleQuotes
= ‘This is a single. I
\
’m escaping characters to avoid errors.’;


$escapeDoubleQuotes = “This is a
Toub汥l
\
”WOW!
\
”, he said!”;

?>


<?php


$test
= “long”;


$longString = “This” . “is” . ‘a’ .
$瑥獴

. “string”;
†††††
// “This is a long string”

?>


Here are some key String functions you
will

use (but are not limited to).

Function

Description

md5

Calculates the MD5 has
h

of a string (passwords encryption)

print

echo

Outputs a string

str_pad

Pads a

string (leading or trailing zeros

i.e.

for ID numbers)

strtolower

Converts string to lowercase

trim

Strips whitespace and tabs from both sides of string

substr

Returns only a part of a string (as a brand new string)

Integers and Integer Functions

Integers are whole numbers (1
, 100, 24, 0
,
-
20, etc.). This data type is used for arithmetic operations. The
syntax for those operations
is

similar to those you find in most other programming languages.

Floating numbers

Floating numbers are decimal numbers
(2.05, 99.9). This data type is also used for arithmetic operations.

Since mathematical operations are built in to PHP, there are not any functions you need to worry about
when it relates to the actual value of the integer/float number. We will go into det
ail later about some
variable handling functions that pertain to all these different data types later.

Arrays

Arrays will be the bulk of how we retrieve and store data in the database.

An array is a list of elements
that are considered ‘indexes’
with

their

related values. Think of arrays as a huge variable t
hat contains
many mini
-
variable that have values
.
They are extremely useful outside of the scope of this project but
we will focus on them mainly for data manipulation to store and retrieve data.
There a
re three types of
arrays

in PHP
.



Indexed arrays



Arrays with numerical index (the first element index starts at 0)



Associative arrays


Arrays with named keys (Strings are used to associate a key to its value)



Multidimensional arrays



Arrays containing on
e or more arrays (very common)

Basically w
hen we store and retrieve data we will mostly be using
associative arrays

because the key
s of
those
elements (indexes)

will be the
column

names

of the tables we are manipulating. Since we already
know the column names it
makes perfect since and easier
code to use this type of array

rather

than an
indexed array (column orders can be changed which would completel
y destroy our co
de in terms or
retri
eving data); we only want the value, we
already
know the column name
s in the database table
.

We
will also use
indexed

arrays where appropriate.

Array functions

Function

Description

count

Returns the number of elements in the array

array_push

Inserts one
or more elements in an array

array_pop

Deletes last element in array


Operators

for Integers and Floats (and Arrays)
:

Addition: $x + $y


Multiplication: $x * $y



Modulus: $x % $y

Subtraction: $x
-

$y


Division: $x / $y




Less than: $x < $y

Equal: $x =
= $y



Not equal: $x != $y



Greater than: $x > $y

And: $x && y



Or: $x || $y




Not: !$x

Conditional Statements:

Here are the types of conditional statements:



If statement



If…else statement



If…elsif….else statement



Switch statement



While loop



For loop

Conditional block statements (in other words blocks of code inside a conditional statement

that are
2 or
more lines of code
) have to be encapsulated with brackets like this:




<?php


$x
= 1;

//Declaration and assignment


if (
$x
== 1)

/
/Conditional check of equality


{



$x
+= 2;


//same thing as

saying

$x = $x + 2



echo

“x is equal to” .

$砠
;
†† †
IIp物r琠瑨攠牥獵sW
Ⱐ楮⁴桩s⁣慳攬ax⁩猠敱e慬a瑯″


}

?>


Switch statements are conditional cases
where only one

block of code

is
run

at a time. It is possible that
someone may have to use this, but switch statements can
always

be programmed in some sort of
if…elsif…else statement.

While loops are the bulk of the assignment. When we’re making our queri
es to the database we will use
a while loop to return all the rows of the queried table results, which will then be stored in some sort of
array object (more on that later). Then with all that data we can loop through it to display it using a
foreach loop
or for loop
.

For loop is used when you know how many times you want to loop through

something

(you know an
exact number). This is useful if you

already

know the length of
a
n

array (meaning how many results

we
re
returned) because you can
display the re
sults

in a neat and clean table.

Foreach loop is used only for arrays. It works the exact same way as a for loop except the each element
of the array is broken down into variables and have some code executed upon it (the code inside the
foreach loop). More on t
his later.

Objects

Objects are how we’re going to manipulate the data in our program. In PHP Objects are simply abstract
things. Those things can be whatever you want it to be. To create an object we use the
class

keyword.

Functions created inside an objec
t are called
methods
.

So after we create the class of the object we
must assign a variable to a new instance of that object to access its functions and variables. To create a
new
instance

of the
object

we use the
new
keyword when assign the object to the v
ariable.


We are going to make class objects for everything
.

We are also going to make class objects for
functionality of those objects: Add Inventory, Add Customers, etc. That way code is structured properly
and eas
ily accessible when we need to improve the code.

<?php


//Create class


class
Bicycle

{




function
ride
(
$
speed)



{




echo “Current speed: “ .
$
sp敥T;



}


}

$b楣祣l攠
=敷
䉩捹捬c
⠩;
†† ††
II捲c慴aT⁡ ⁩湳瑡 捥f⁴h攠䉩By捬cbj散e

$b楣祣le
-
>
物re
(“10mph”); //calls function of
瑨攠楮獴慮捥sv慲a慢汥l睩瑨⁰慲am整敲ep慳獥s

?>


Visibility

To ensure that data is secure some
variables and functions will be made
public

while others will be
made
private

and some may be
protected

(we probably won’t use this)
. Use:



public

scope to make
that variable/function available from anywhere, other classes and instances
of the object.



private

scope when you want your variable/function to be visible in its own class only.



protected

scope when you want to make your variable/function visible in all c
lasses that extend
current class including the parent class.

For instance a connection link to the database will be a
private

variable because we don’t want anyone
knowing exactly what database name we are using, host, server language, port number, etc. So

creating the variable private will avoid that problem.

More on this when we actually code.

Functions and Returns

Functions simply do something. You can create a function anywhere (i.e. the global class or inside a class
etc.) Those functions are never cal
led until you explicitly call that function. Some functions are created
simply to return a value to a variable. This is how a functi
on returns a value to a variable
:


Each Object class we create will contain many functions to handle tasks (database queries, adding
records, updating records, etc. all will be separate functions).

Here are some various functions that relate to
variables

not data types

Function

Description

is_int, is_array,
is_float,is_string, is_object

Returns a Boolean (true or false) if the variable is or isn’t a
捯牲r獰潮s楮g⁤慴愠 ype;⁵獥晵s⁩渠楦⁣onT楴楯n慬⁳ 慴em敮瑳

print_r

Used for debugging. Prints the contents of an array.

var_dump

Used for
debugging. Prints the contents of any type of variable.

isset

Checks if a variable is set, meaning assigned a value. Very useful
for forms and logins

and many other things

<?php


//Declare function

that can be used anywhere


public
function
customFunction
(
$value1, $value2
)


{



return $value1 + $value2;


}


$
value3

=
customFunction(1,2);

//
explicit call to the function that will return a value

echo
$value3
;



//will print 3

?>


Forms, $_GET, $_POST, $_SESSION

There are built in arrays within PHP. Three of the
se are $_GET, $_POST, and $_SESSION. $_GET deals
with URI values that have been passed, $_POST deals with processed and parsed values that have been
passed from forms, and $_SESSION is used for a user’s session (i.e. think of cookies on one person’s
comput
e
r). $_SESSION will be used globally to manage the login and what that employee can see.

For
ALL

HTML
forms on our project we will use the
$_POST

variable.

This means that all forms will look
similar to this:


The method says
post
, meaning that when the action is called $_POST will be used to retrieve the values
from the form. To actually get the values from the input boxes in the form we need to give each input
box a
name
.

Finally o
n the PHP page you would have something like this
:


Conclusion

The language is not that hard
to learn because things are already ready for you. The next lesson will
involve the database information. Here are some additional links if you would like help outside of this
information. Look over it and contact me if you have any questions or concerns.

http://www.w3schools.com/php/default.asp

(Quick reference guide)

http://www.php.net/manual/en/

(Official PHP manual, very detailed and extensive)

http://thenewboston.org/list.php?cat=11

(200 videos of PHP, step by step, long but informative)

<form action=”processed_PHP_page.php” method
=”
po獴
”>

Email: <input type=”text”
n慭e
=”Email” >
㱢爾

㱩<
put type=”submit”
name
=”submit” value=”Submit”>

㰯fo牭>

<?php

if (isset($_POST[‘submit’])) //Has the submit button been clicked? If so then..

{

$email = $POST[‘Email’];

IIs瑯r攠瑨W⁶慬a攠o映fhe⁩湰u琠
box named ‘Email’

echo “Your email is “ . $email;

}

?>