PHP MYSQL Programming, For Beginners, Quick Start Guide.
Author: Yao, Ray
Date: 2020-08-06
Publisher: Step by Step Tutorial eBook & Book

PHP  MYSQL
Programming
For Beginners
Quick Start Guide
Ray Yao

Copyright © 2015 by Ray Yao

All Rights Reserved

Neither part of this book nor whole of this book may be reproduced or transmitted in any form or by any means electronic, photographic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without prior written permission from the author. All Rights Reserved!

Ray Yao

Ray Yao’s eBooks & Books on Amazon
Advanced C++ Programming by Ray Yao
Advanced Java Programming by Ray Yao
AngularJs Programming by Ray Yao
C# Programming by Ray Yao
C# Interview & Certification Exam
C++ Programming by Ray Yao
C++ Interview & Certification Exam
Django Programming by Ray Yao
Go Programming by Ray Yao
Html Css Programming by Ray Yao
Html Css Interview & Certification Exam
Java Programming by Ray Yao
Java Interview & Certification Exam
JavaScript Programming by Ray Yao
JavaScript 50 Useful Programs
JavaScript Interview & Certification Exam
JQuery Programming by Ray Yao
JQuery Interview & Certification Exam
Kotlin Programming by Ray Yao
Linux Command Line
Linux Interview & Certification Exam
MySql Programming by Ray Yao
Node.Js Programming by Ray Yao
Php Interview & Certification Exam
Php MySql Programming by Ray Yao
PowerShell Programming by Ray Yao
Python Programming by Ray Yao
Python Interview & Certification Exam
R Programming by Ray Yao
Ruby Programming by Ray Yao
Rust Programming by Ray Yao
Scala Programming by Ray Yao
Shell Scripting Programming by Ray Yao
Visual Basic Programming by Ray Yao
Visual Basic Interview & Certification Exam
Xml Json Programming by Ray Yao

Preface

“PHP MySQL Programming” is a useful book for beginners. You can learn complete primary knowledge of PHP & MYSQL fast and easily.

This book includes many practical Exercises. You can learn PHP MySQL coding fast with Exercises.

Note:

This book is only for PHP MySQL beginners, it is not suitable for experienced PHP MySQL programmers.

Source Code for Download

This book provides source code for download; you can download the source code for better study, or copy the source code to your favorite editor to test the programs.

Source Code Download Link:

https://forms
.
aweber
.
com/form/50/1828597050
.
htm

Table of Contents

Chapter 1

Start PHP

Install PHP & MySQL
What is PHP?
Run First Program
Comments
PHP Reserved Words
Variables
Data Types
Escaping Characters
Functions
Function with Arguments
Variable Scope
Multiple Arguments
Exercise: Calculation

Chapter 2

PHP Basic

Conditional Operator
Arithmetical Operators
Logical Operators
Assignment Operators
Comparison Operators
If Statement
If-else Statement
Switch Statement
For Loop
While Loop
Do-While Loop
Break Statement
Continue Statement
Return Statement
Exercise: One to Ten

Chapter 3

Use Array

Create an Array
Show array element values
Get the Size of Array
Array keys & Values
Iterate Array
Add Array Elements
Remove Array Elements
Merge Array
Extract Array
Sort Array
Exercise: Start with Zero

Chapter 4

Form Basic

Create a Form
Text Inputs
Password inputs
Submit Inputs
Reset Inputs
Textarea Inputs
Radio Inputs
Checkbox Inputs
Form Works with PHP
Form Works with PHP
Exercise: Radio’s Colors

Chapter 5

Dynamic Data

Date & Time
String Process
Redirection of Browser
Information of Visitor
Cookie
Session
Session Usage
Open a File
Read a File
Write a File
Close a File
Exercise: Extract Sth.

Chapter 6

Class & Object

Class Definition
Object Declaration
Class & Object

$this
-
> variable

Constructor (1)
Constructor (2)
Destructor
Extend Class
Inheritance
Class:: method ( )
Exercise: Appointment

Chapter 7

MySQL Basic

What is MySQL?
MySQL Data Type
Column Modifiers
phpMyAdmin
Show Databases
Create a Database
Select a Database
Create a table
Show Table
Insert Data to Table
Browse Table
Alter a table
Update Data
Select Queries
Database Commands
Table Commands
Field Modifiers
Operation Commands
Exercise: Set Database

Chapter 8

MySQL & PHP

Connect MySql Server
Select Database
Insert Table Data
Alter Table Structure
Update Table Data
Retrieve Table Data
mysqli_fetch_row( )
mysqli_fetch_assoc( )
mysqli_fetch_array( )
mysqli_num_rows( )
mysqli_close( )
mysqli_xxx_xxx (  ) Summary
Exercise: Work Together

Appendix 1

PHP Security Projects

Why Security Code?
1:  Filter Malicious Password
2:  Filter Malicious Characters
3:  Filter Malicious Input
4:  Limit Specified Input
5:  Escape Output
6:  Protect Database

Appendix 2

Tests & Answers

Tests
Answers
Source Code Download

Chapter 1

Start PHP

Install PHP & MySQL

If you want to run PHP and MySQL, you need to set up a development environment on your own computer. You can install “AppServ” to set up a server. Please download AppServ to install.

AppServ

“AppServ ” is free software to setup a server; it can run Apache, PHP, MySQL, PhpMyAdmin, Ajax, JavaScript, JQuery and Html file……

http://www
.
appservnetwork
.
com/

Please install AppServ to the folder “C:\AppServ ”.

MySQL default username: root

Please set password: 12345678

Having installed AppServ, test to see if AppServ installation is successful, please run a browser, and type address:

http://localhost

If you can see the page like this:

Congratulation! PHP, MySQL and Apache server are running successfully!

Note: The folder “C:\AppServ\www” is a working folder of PHP programs. You create more sub folders under the working folder, and put all your PHP program files to this working folder or its sub folders. From now on, you are able to run PHP files in “C:\AppServ\www ” folder or its sub folders.

What is PHP?

PHP is a server-side language for web development, meaning “Personal Homepage Program”.

The syntax of PHP looks like this:

<?php      some PHP codes in here       ?>

Example 1.1
<html>
<?php
echo ("Hello World!");
?>
</html>

Output:
Hello World!

Explanation:

PHP code tag begins with <?php and ends with ?> , its syntax looks like this:

<?php       some PHP codes in here       ?>

“echo” is command of PHP, meaning “output” or “display”.

echo (“Hello World”); will output “Hello World”.

Each PHP statement ends with “; ”.

Run First Program

The best free PHP editor can be downloaded from the following links:

Notepade++

https://notepad-plus-plus
.
org/

Eclipse

http://www
.
eclipse
.
org/downloads/

Netbeans

https://netbeans
.
org/

Bluefish

http://bluefish
.
openoffice
.
nl/index
.
html

PSPad

http://www
.
pspad
.
com/

ContextEditor

http://www
.
contexteditor
.
org/index
.
php

Notpad

Microsoft Windows Computer

When using above PHP editors, you should save the PHP files to the working folder C:\AppServ\www”.

Example 1.2

Using your favorite PHP editor, write PHP codes as following.

<html>
<?php
echo ("Hello World! ");
?>
</html>

Please Save the file with the file name “Hello. php” to the working folder. (C:\AppServ\www”).

Run the program in editor Or run a browser and type URL address:

http://localhost/Hello.php

Output:

Hello World!

Explanation:

Congratulation!   The first PHP program runs successfully!

If you use Notepad to write any other PHP program, please save it as xxx. php to the working folder (C:\AppServ\www), run a browser, and type url address:

http://localhost/xxx.php

The above url can run any xxx. php programs.

If you want to edit the xxx. php file with Notepad, please right click it > Open with > Notepad.

Comments

// is used in single-line comments.

/*……*/ are used in multi-line comments.

The PHP compiler always ignores all PHP comments.

Example 1.4

<?php
echo (“ OK ”);  // output OK
.

echo (“ Hello ”);   /* echo (“Hello”); is a PHP statement, echo is a reserved word, it displays a word “OK”
.
PHP is very easy to learn
.
*/

?>

Output:    OK   Hello

Explanation:

// output OK; is a single-line comment.

/* echo (“OK”); is a PHP statement, echo is a keyword, it display a word OK
.
PHP is very easy to learn
.
*/  is a multi-line comment.

The PHP compiler always ignores all PHP comments.

PHP Reserved Words

Some words are only used by PHP language itself. They may not be used when choosing identifier names for variable, function, and labels. The following words are part of PHP reserved words

and

array( )

break

case

const

continue

default

do

echo( )

else

else if

empty( )

eval( )

exception

exit( )

extends

false

for

function

foreach

global

if

include( )

include_once( )

isset( )

list( )

new

null

or

print( )

require( )

require_once( )

return( )

static

switch

true

unset( )

xor

while

Example 1.3
const
// const is a reserved word
.

continue
// continue is a reserved word
.

Explanation:

PHP reserved words may not be used as variable name, function name, and label name.

Variables

A variable is a symbolic name associated with a value. Variable name starts with $ symbol.

Example 1.5

<?php

$var;
//declare a variable

$abcde;
//declare a variable

$my_variable;
//declare a variable

?>

Explanation:

$var, $abcde and $my_variable are all variables.

They can store some values. e. g.
$var=100;
$abcde=”Hello World”;
$my_variable=true;

Note that variable names cannot start with a number, without space. e. g. “$23var”, “$abc de” are invalid variable names. But “$var23”, “$abcde” are valid variable names.

Data Types

String – characters within double or single quotation.

Integer – numbers without decimal point.
Boolean – a value with true or false.
Float – numbers with decimal point.
Example 1.6
$str=’I am a string’;
$int=168;
$float=12. 88;
$bool=true;
Explanation:

$str=’I am a string’;  // $str data type is String
.

$int=168;  // $int data type is Integer
.

$float=12. 88;  // $float data type is Float
.

$bool=true;  // $bool data type is Boolean
.

Note: Double quotes or single quotes are always used in the string. e. g. “abcde”, ‘learning’.

Escaping Characters

The “ \ ” backslash character can be used to escape characters.

\n outputs content to the next new line.
\r makes a return
\t makes a tab
\’ outputs a single quotation mark.
\” outputs a double quotation mark.
Example 1.7
<?php
echo “PHP said \” Hello World\” ”;

//
\”
outputs a double quotation mark
.

?>

Output:     PHP said “ Hello World”

Explanation:

\” outputs a double quotation mark.

Another sample:

echo “Hello \t\t\t World”;   // Note it has three taps

(  Output:   Hello     World  )

Functions

A function is a code block that can repeat to run many times. To define a function, use “function function-name ( ) { }”.

function function-name ( ) {……}

To call a function, use “function-name ( );”

function-name ( );

Example 1.8
<?php
function test( ) {    // declare a function
echo ("show a sample");    // output
}
test ( ) ;     // call the function
?>
Output:  show a sample
Explanation:

“function test( ) { }” is a declaration of PHP test( ) function.

“test( );” is a command to call a function named test( ){ }.

When running the function test ( ), it will output “show a sample”.

Function with Arguments

A function can have one or more arguments inside the bracket. Arguments are used to pass data to function.

function function-name ( $argument ){……}

Example 1.9

<?php
function test( $arg ) {     //declare a function with arguments
echo (“$arg”);

}

test(“display a sample”) ;  //call the function, pass args
.

?>
Output:     display a sample
Explanation:

$arg is an argument of function test($arg ){ }. When test(“display a sample”) call the function test($arg){… }, it will pass the “display a sample” to $arg. After $arg has received the data, it will pass the data inside the function. echo ($arg) will use the data, and then outputs “display a sample”.

Variable Scope

A global variable is declared outside the function, it can be used in everywhere; local variable is declared inside the function, it is only used inside current function.

Example 1.10

<?php

$num=200;
// This $num is a global variable
.

function test( ){

$num=100;
// This $num is a local variable
.

}
echo $num;
?>
Output:    200
Explanation:

echo $num outputs 200, which means $num store a value of global variable.

If you want to declare a global variable inside a function, you should use a keyword “global” preceding the variable name. e. g. function test( ) { global $num; …… }

Multiple Arguments

A function may have several arguments; these arguments will pass data simultaneously for the function.

function function-name ( $arg1, $arg2, $arg3){……}

Example 1.11

<?php
function test ($a, $b, $c) {   //with multiple arguments

$sum=$a+$b+$c;     // calculation
echo $sum;       // output
}

test(3, 6, 9) ;   //call the function, and pass arguments

?>
Output:   18
Explanation:

When test(3, 6, 9) calls the function test ($a, $b, $c) {…}, arguments 3,6,9 will pass to the $a, $b, $c, the $sum will be assigned the value of 18. The output is 18.

Exercise: Calculation

Function Demo

Open your favorite PHP editor, write following codes to it:

<?php
function multiply($x, $y){    // declare a function with args
calculate($x, $y);   // call the function “calculate()”, pass args

}

function calculate($a, $b){   // decalare a function with args

$result = $a * $b;    // calculate
echo("The value is $result");   // output the result

}
?>
<?php
multiply(10,20);    // call the function “multiply()”, pass args

?>

“Save ” the file with name “functionDemo. php”, and run the program.

Output:

The value is 200

Explanation:

“function multiply($x, $y){… }” defines a function “multiply”.

“function calculate($a, $b){… }” defines a function “calculate”.

“multiply(10,20);” calls the function “function multiply($x, $y){… }”, and passes two parameters to $x and $y.

“calculate($x, $y);” calls the function “function calculate($a, $b){…}”, and passes two parameters to $a and $b.

If you use Notepad to write above PHP program, please save it as functionDemo. php to the working folder (C:\AppServ\www), run a browser, and type address:

http://localhost/functionDemo.php

The above link can run functionDemo. php programs.

If you want to edit the functionDemo. php with Notepad, please right click it > Open with > Notepad.

Chapter 2

PHP Basic

Conditional Operator

The syntax of conditional operator looks as following:

(test-expression) ? (if-true-do-this) : (if-false-do-this);

( test-expression) looks like $a<$b, $x! =$y, $m==$n. etc.

Conditional Operator first tests an expression for a true or false value, then executes the given statements according to the result of the test.

Example 2.1
<?php
$a=100; $b=200;

$result1=($a<$b) ? "apple <br>" : "banana <br>";

// (test-expression)
?
(if-true-do-this)
:
(if-false-do-this);
echo $result1;

$result2=($a>$b) ? "apple <br>  " : "banana <br>";

// (test-expression)
?
(if-true-do-this)
:
(if-false-do-this);
echo $result2;
?>
Output:
apple
banana
Explanation:

The conditional operator use ($a<$b) to test the $a and $b, because $a is less than $b, it returns true. Therefore, the output is “apple”.

The conditional operator use ($a>$b) to test the $a and $b, because $a is less than $b, it returns false. Therefore, the output is “banana”.

Arithmetical Operators

Operators

Running

+

add

-

subtract

*

multiply

/

divide

%

get modulus

++

increase 1

- -

decrease 1

.

connect two strings

Example 2.2
$add=100+ 200;   echo $add;
$div=800/ 2;   echo $div;
$mod=10% 3;   echo $mod;
$inc=10;   echo ++ $inc;
$str=”abc”. ”de”;  echo $str;
Explanation:
$add=100+200;   echo $add; will output  300
$div=800/2;   echo $div; will output  400;
$mod=10%3;   echo $mod; will output  1;
$inc=10;   echo ++$inc; will output  11;

$str=”abc”. ”de”;  echo $str; will output abcde.

Logical Operators

Operators

Equivalent

&&

and

||

or

!

not

After using logical operators, the result will be true(1) or false(0).

Example 2.3
<?php
$a = true; $b = false;
$test1 = ( $a && $b )? "true ":"false ";
$test2 = ( $a || $b )? "true ":"false ";
$test3 = ( ! $a )? "true ":"false ";
$test4 = ( ! $b )? "true ":"false ";
echo $test1;
echo $test2;
echo $test3;
echo $test4;
?>
Output:
false
true
false
true
Explanation:

true && true;
returns true;

true && false;
returns false;

false &&false;
returns false;

true II true;
returns true;

true II false;
returns true;

false II false;
return false;

! false;
returns true;

! true;
returns false;

Assignment Operators

Operators

Examples:

Equivalent:

+=

$x+=$y

$x=$x+$y

- =

$x- =$y

$x=$x- $y

* =

$x* =$y

$x=$x* $y

/ =

$x/ =$y

$x=$x/ $y

%=

$x%=$y

$x=$x%$y

. =

$x. =$y

$x=$x. $y

Example 2.4
<?php
$x=200;   $y=100;
$x+=$y;  echo ("$x<br>");
$x-=$y;  echo ("$x<br>");
$x/=$y;  echo ("$x<br>");
$x*=$y;  echo ("$x<br>");
$x%=$y;  echo ("$x<br>");
$m="abc"; $n="de";
$m. =$n;   echo $m;
?>
Output:
300
200
2
200
0
abcde
Explanation:

$x+=$y;   // $x=$x+$y;       x is 300
.

$x- =$y;    //  $x=$x
-
$y;      x is 200

$x/ =$y;    // $x=$x
/
$y;         x is 2

$x* =$y;    // $x=$x
*
$y;        x is 200

$x% =$y;   // $x=$x
%
$y;    x is 0

$m. =$n;    // $m=$m
.
$n;   echo $m; outputs  abcde

Comparison Operators

Operators

Running

>

greater than

<

less than

>=

greater than or equal

<=

less than or equal

==

equal

! =

not equal

After using comparison operators, the result will be true or false.

Example 2.5
<?php
$a=100; $b=200;
$result1 = ($a>$b)? "true":"false";
$result2 = ($a==$b)? "true":"false";
$result3 = ($a! =$b)? "true":"false";
echo $result1;
echo $result2;
echo $result3;
?>
Output:
false
false
true
Explanation:

$result1 = ($a>$b); // test 100>200 ; outputs false
.

$result2 = ($a==$b); // test 100==200; outputs false
.

$result 3= ($a! =$b); // test 100
!
=200 ; outputs true
.

Note:

The logical evaluation returns: “1” represents true, “0” represents false.

If Statement

if ( test-expression ) {   // if true do this;    }

“if statement” executes codes inside { … } only if a specified condition is true, does not execute any codes inside {…} if the condition is false.

Example 2.6
<?php
$a=200;
$b=100;
if ($a>$b) {    // if true, run following code
echo "a is greater than b. ";
}
?>
Output:      a is greater than b.
Explanation:

( $a>$b ) is a test expression, namely (200>100), if returns true, it will execute the codes inside the { }, if returns false, it will not execute the codes  inside the { }.

If-else Statement

if ( test-expression) {   // if true do this;   }

else  {  // if false do this;   }

“if... else statement” runs a part of codes if the test returns true or runs other part of codes if the test returns false.

Example 2.7
<?php
$a=100; $b=200;
if ($a>$b) {
echo "a is greater than b. ";
}
else {   // if false, run following code
echo "a is less than b";
}
?>
Output:       a is less than b.
Explanation:

( $a>$b ) is a test expression, namely (100>200). If returns true, it will output ”a is greater than b. ” If returns false, it will output “a is less than b”.

Switch Statement

switch ( $variable ) {
case 1: if equals this case, do this;  break;
case 2: if equals this case, do this;  break;
case 3: if equals this case, do this;  break;
default : if not equals any case, run default code;  break;

}

The value of $variable will compare each case first, if it equals one of the “case” value; it will execute that “case” code.

If the $variable doesn’t match any case, it will execute the “default” statement.

“break;” terminates the codes running on the switch statement.

Example 2.8
<?php
$number=20;
switch ( $number ) {  //$number will compare each case
case 10 : echo “Running case 10”;  break;
case 20 : echo “Running case 20”;  break;
case 30 : echo “Running case 30”;  break;
default
:   echo “Running default code”;  break;  }

?>

Output:

Running case 20

Explanation:

The $number value is 20; it will match case 20, so it will run the code in case 20.

For Loop

for( init, test-expression, increment) { // some code ; }

“for loop” runs a block of code by the specified number of times.

Example 2.9

<?php
for ($x = 0; $x <= 5; $x++) {   // repeat at most 5 times
echo "$x ";
}
?>
Output:       012345
Explanation:
$x = 0 is an initializer,

$x <= 5 is test-expression, the code will repeat at most 5 times.

$x++ means that x will increase 1each loop.

After 5 times loop, the code will output 012345.

While Loop

while ( test-expression ) {  // some php code in here ;  }

“while loop” loops through a block of code if the specified condition is true.

Example 2.10
<?php
$counter=0;
while ($counter < 8){  // run at most 8 times
echo “&”;
$counter++;
}
?>
Output:        &&&&&&&&
Explanation:

“$counter< 8” is a test expression, if the condition is true, the code will loop less than 8 times, until the $counter is 8, then the condition is false, the code will stop running.

Do-While Loop

do{ // some php code in here } while ( test-expression);

“do... while” loops through a block of code once, and then repeats the loop if the specified condition is true.

Example 2.11
<?php
$counter=0;
do {
echo “@”;
$counter++;

} while ($counter<8);   // run at most 8 times

?>
Output:       @@@@@@@@
Explanation:

“$counter< 8” is a test expression, if the condition is true, the code will loop less than 8 times, until the $counter is 8, then the condition is false, the code will stop running.

Break Statement

Break;

“break” keyword is used to stop the running of a loop according to the condition.

Example 2.12
<?php
$num=0;
while ($num<10){

if ($num==5)  break;
// leave the current while loop

$num++;
}
echo ( $num );
?>
Output:    5
Explanation:

“if ($num==5)  break;” is a break statement. If $num is 5, the program will run the “break” command, the break statement will leave the while loop, then run “echo ( $num )”.

Continue Statement

continue;

“continue” keyword is used to stop the current iteration, ignoring the following code, and then continue the next loop.

Example 2.13
<?php
$num=0;
while ($num<10){
$num++;
if ($num==5)  continue;
// go to the next while loop
echo ( $num );
}
?>
Output:       1234678910
Explanation:
Note that the output has no 5.

“if ($num==5)  continue;” includes “continue” command. When the $num is 5, the program will run “continue”, skipping the next command “echo ( $num )”, and then continue the next loop.

Return Statement

return $variable;

“return $variable” is used to return a value to the caller of the function.

Example 2.14
<?php
function multiply($x, $y){
return $x * $y;
// return the result value to caller

}
?>
<?php

$result=multiply(10,20);    // this is a caller
echo $result;
?>
Output:        200
Explanation:

“return $x * $y;” returns a value “200” to “multiply(10, 20)”. You can treat it as “multiply(10, 20) = 200”.

Exercise: One to Ten

Loop Statement Demo

Open your favorite PHP editor, write following codes to it:

<?php
echo "while statement: <br>";
$value1=1;
while($value1<=10) {     // repeat at most 10 times
echo $value1. "&nbsp;";
$value1++;
}
echo "<br><br>";
echo "do... while statement: <br>";
$value2=1;
do {
echo $value2. "&nbsp;";
$value2++;

}while($value2<=10) ;   // repeat at most 10 times
echo "<br><br>";
echo "for statement: <br>";
for($i=1;$i<=10;$i++) {   // repeat at most 10 times

$value3=$i;
echo $value3. "&nbsp;";
}
?>

“Save ” the file with name “loopDemo. php”, and run the program.

Output:

while statement:

1 2 3 4 5 6 7 8 9 10
do... while statement:

1 2 3 4 5 6 7 8 9 10
for statement:

1 2 3 4 5 6 7 8 9 10

Explanation:

“while loop” loops through a block of code if the specified condition is true.

“$value1< =10” is a test expression, if the condition is true, the code will loop 10 times,

“do... while” loops through a block of code once, and then repeats the loop if the specified condition is true.

“$value2< =10” is a test expression, if the condition is true, the code will loop 10 times,

“for($i=1;$i<=10;$i++)” runs a block of code by the specified number of times.

“$i = 1” initializes the variable “i” as 1.

“$i<=10” sets the loop’s number of times.

“$i++” increases 1 in each loop.

"&nbsp;” is an html code, means “space”.

Chapter 3

Use Array

Create an Array

An array is a particular variable, which can contain one or more value at a time. array( ) is used to create an array.

(1) The syntax to create an array:

$arrayName = array (“value0”, “value1”, “value2”);

(2) Other syntax to create an array:

$arrayName = array ( );
$arrayName[index0] = “value0”;
$arrayName[index1] = “value1”;
$arrayName[index2] = “value2”;

Example 3.1

<?php

$color = array ( );    // creat an array $color

$color [0] = red;        // assign value to the first element

$color [1] = yellow;
$color [2] = green;
echo "<br>$color[0]";
echo "<br>$color[1]";
echo "<br>$color[2]";
?>
Output:
red
yellow
green
Explanation:

Above code creates an array, array name is $color, it has three elements: $color [0], $color [1], $color [2]. Its indexes are 0, 1, and 2. Its values are red, yellow, and green.

Show array element values

To show array element values, use syntax as following:

echo (   $arrayName[index]    );

Example 3.2

<?php

$color = array("yellow", "purple", "orange");   //create an array
echo ( $color[1] );
//show value of the second element

?>

Output:      purple

Explanation:

From above, you can know:

The value of $color[0] is yellow.

The value of $color[1] is purple.

The value of $color[2] is orange.

Note that the indexes begin counting from zero.

Get the Size of Array

Two functions can get the size of an array.

count( $array);

sizeof($array);

Example 3.3
<?php
$color = array(“yellow”, “purple”, “orange”);

$size1=  count ($color);    // get the size of the array

$size2 = sizeof ($color);    // get the size of the array
echo ( "$size1  " );        echo ( "$size2  " );

?>

Output:

3   3

Explanation:

count($color) or sizeof($color) can return the size of array $color.

array(“yellow”, “purple”, “orange”) has three elements, so its size is 3.

Array keys & Values

Array elements are consisted of keys and value pair.

array( key1=>value1, key2=>value2, kay3=>value3… );

“=>” is used to connect key and value. ( key and index is the same meaning. )

Example 3.4

<?php

$book=array( "1st"=>"JSP", "2nd"=>"ASP", "3th"=>"PHP") ;     // “1st” is a key, “JSP” is a value
echo $book[ "3th" ];     // “3th” is a key

?>

Output:

PHP

Explanation:

A string can act as an index of the array.

“echo $book[3th]” shows the element value “PHP”, its index is “3th”.

Iterate Array

foreach( $array as $key=>$value ){ }

For every loop iteration, each key of the array element is assigned to $key, each value is assigned to $value, until iterates the last array element.

Example 3.5

<?php

$book=array( "1st"=>"JSP", "2nd"=>"ASP", "3th"=>"PHP");
foreach ( $book as $key=>$value ) {    // iteration
echo "The $key book is about $value. <br>";

}   // $key stores all keys, $value stores all values

?>

Output:   The 1st book is about JSP.

The 2nd book is about ASP
.

The 3th book is about PHP
.

Explanation:

“foreach ($book as $key=>$value)” assigns $book’s key to $key, assign $book’s value to $value on each loop iteration. On the first loop iteration, “1st” is assigned to $key, “JSP” is assigned to $value, and so on……

Add Array Elements

array_unshift( array, value1,  value2…);

array_push( array, value1,  value2… );

array_unshift( array, value1,  value2) adds value1, value2  at the beginning of the array.

array_push( array, value1,  value2… ) adds value1, value2  at the end of the array.

Example 3.6
<?php
$myArray=array("A", "B", "C");
array_unshift($myArray, "START") ;  //add to beginning
array_push($myArray, "END") ;   //add to the end
echo ( "$myArray[0]  " );
echo ( "$myArray[1]  " );
echo ( "$myArray[2]  " );
echo ( "$myArray[3]  " );
echo ( "$myArray[4]  ");
?>
Output:
START A B C END
Explanation:

array_unshift($myArray, “START”) adds the element START at the beginning of  the element A, B, C in $myArray.

array_push($myArray, “END”) adds the element END at the end of element A, B, C in $myArray.

There are five elements in $myArray now.

Remove Array Elements

array_shift( array );

array_pop( array);

array_shift (array) removes element at the beginning of the array.

array_pop (array) removes element at the end of the array.

Example 3.7

<?php

$myArray=array("START", "A",  "B", "C", "END");
array_shift($myArray) ;   // remove the beinning
array_pop($myArray) ;    // remove the end
echo ( "$myArray[0]  " );
echo ( "$myArray[1]  " );
echo ( "$myArray[2]  " );
?>
Output:
A B C
Explanation:

array_shift($myArray) removes the first element in the $myArray.

array_pop($myArray) removes the last element in the $myArray.

There are only three elements in $myArray now.

Merge Array

array_merge( array1, array2 );

array_merge( array1, array2 ) can merge array1 and array2, and create a new array.

Example 3.8
<?php
$array1=array ("A", "B", "C");
$array2=array ("D", "E", "F");

$array=array_merge( $array1, $array2 );   //merge arrays
foreach( $array as $value) { echo("$value " );}

?>

Output:

A B C D E F

Explanation:

array_merge( $array1, $arra2 ) can merge two arrays to a new array $array. After merging, the new array holds the six elements from two arrays; therefore, the program returns ABCDEF.

Extract Array

array_slice( array, start, length );

array_slice( array, start, length ) can extract some elements from an array, at the start position and by specifying length, and create a new array.

Example 3.9
<?php
$array=array("A","B","C","D","E","F");

$arr=array_slice( $array, 2, 3 ) ;   //extract three elements
foreach($arr as $value){ echo "$value ";}
?>
Output:
C D E
Explanation:

array_slice( array, 2, 3 ) extracts 3 elements at the position 2 from $array.

Note that the beginning of position starts with 0.

Sort Array

sort( array );

sort(array) can sort the array in alphabetical order by value.

Example 3.10

<?php

$color =array("yellow", "red", "blue", "white");
sort ( $color ) ;    // sort the array in order
foreach( $color as $value ) { echo "$value ";}

?>

Output:

blue  red  white  yellow

Explanation:

sort ( $color ) rearranges the order of $color array elements by value alphabetically. After sorting, the array elements list in order as “blue red white yellow”.

Exercise: Start with Zero

Iterate Array Demo

Open your favorite PHP editor, write following code to it:

<html>
<body>
<?
$a = array("zero", "one", "two");
echo "In array('zero', 'one', 'two'): <br><br>";
foreach ($a as $key => $v) {    /* store all element keys to $key, store all element values to $v   */
echo "The number ". $key. " element:  <br>";
echo "key is: ". $key. ",   ";
echo "value is: ". $v. "<br><br><br>";
}
?>
</body>
</html>

“Save ” the file with name “arrayDemo. php”, and run the program.

Output:

In array('zero', 'one', 'two'):

The number 0 element:

key is: 0, value is: zero

The number 1 element:

key is: 1, value is: one

The number 2 element:

key is: 2, value is: two

Explanation:

“$a = array("zero", "one", "two");” creates an array named $a.

“foreach ($a as $key => $v)” assigns array $a’s key to $key, assign array $a’s value to $value on each loop iteration. On the first loop iteration, “0” is assigned to $key, “zero” is assigned to $value, and so on……

Chapter 4

Form Basic

Create a Form

Html form submits data to the server.

<form  action=”url”  method=”get/post”>
……
</form>

The “action” attribute specifies the URL of the PHP file that processes data from the form.

The “method” attribute specifies the way to pass data to a PHP file. Its value may be “get” or “post”.

Example 4.1
<form  action= “myfile.php”  method=”get” >
……
<form>
Explanation:

action= “myfile. php”  specifies a PHP file myfile. php that processes the data from this form.

method=”get” specifies the pass-data method is “get”, which is an open way to pass data.

method=”post” specifies the pass-data method is “post”, which is a hidden way to pass data.

Comment symbol:  <!- -        - ->

Text Inputs

<input type=”text”  name=”xxx”>

“type” attribute specifies the input type, which may be “text”, “password”, “radio”, “checkbox”, “hidden”……etc.

“text” type is used to input basic data

“name” attribute specifies the inputted contents that will be passed to the PHP file for processing.

Example 4.2
<form action=”myfile. php”  method=”get”>
<input type=”text”  name=”information”>
</form>
Display:

Explanation:

input type=”text” specifies the input type is “text”,
name=”information” specifies the inputted contents that will be passed to the PHP file for processing.

Password inputs

input type=”password” name=”yyy”

“type” attribute specifies the input type, which may be “text”, “password”, “radio”, “checkbox”, “hidden”…… etc..

“password” type is used to input password.

“name” attribute specifies the inputted password that will be passed to the PHP file for processing.

Example 4.3
<form action=”myfile. php”  method=”post”>
<input type=”password”  name=”secret”>
</form>
Display:

Explanation:

input type= “password” specifies the input type is “password”, name=”secret” specifies the inputted password that will be passed to the PHP file for processing.

Submit Inputs

<input type=”submit”  value=”xxx”>

“submit” type is used to submit all data in the form to the server.

“value” attribute specifies the characters will be displayed on a button.

Example 4.4
<form action=”myfile. php”  method=”post”>
<input type=”submit”  value=”Send”>
</form>
Display:

<form>

……

Send

</form>

Explanation:

input type=”submit” will submit all data in the form to the server.

value=”Send” means the word “Send” shown on the button.

Reset Inputs

<input type=”reset”  value=”xxx”>

“reset” type is used to clear all data in the form.

“value” attribute specifies the characters will be displayed on a button.

Example 4.5
<form action=”myfile. php”  method=”post”>
<input type=”reset”  value=”Clear”>
</form>
Display:

<form>

……

Clear

</form>

Explanation:

input type=”reset” will clear all data in the form.

value=”Clear” means the word “Clear” shown on button.

Textarea Inputs

<textarea  name=”xxx”  rows=”num”  cols=”num”>

“textarea” type is used to input data in a text area.

“rows” specifics the number of row.

“cols” specifics the number of column.

Example 4.6

<form action=”myfile. php”  method=”post”>

<textarea  name=”knowledge”  rows=”5”  cols=”10”>

</form>

Display:

Explanation:

name=”knowledge” specifies the inputted contents that will be passed to the PHP file for processing.

“rows” specifies the number of rows as 5.

“cols” specifies the number of columns as 10.

Radio Inputs

<input type=”radio”  name=”data” value=”myvalue”>

type=”radio” is used to input data by single choice.

name=”data” specifies the inputted data that will be passed to the PHP file for processing.

value=”myvalue” specifies one of the optional contents.

Example 4.7

<input type=”radio”  name=”color” value=”red”>

<input type=”radio”  name=”color” value=”blue”>

<input type=”radio”  name=”color” value=”pink”>

Display:

○　red
○　blue ○　pink

Explanation:

type=”radio” allows you to select one of the circles you like.

name=”color” specifies the selected data that will be passed to the PHP file for processing.

value=”red” specifies one of the choices that is red.

Checkbox Inputs

<input type=”checkbox”  name=”data” value=”myvalue”>

type=”checkbox” is used to input data by multiple choice.

name=”data” specifies the inputted contents that will be passed to the PHP file for processing.

value=”myvalue” specifies one of the optional contents.

Example 4.8

<input type=”checkbox”  name=”color” value=”red”>

<input type=”checkbox”  name=”color” value=”blue”>

<input type=”checkbox”  name=”color” value=”pink”>

Display:

□　red
□　blue   □　pink

Explanation:

type=”checkbox allows you check the box you like.

name=”color” specifies the selected contents that will be passed to the PHP file for processing.

value=”red” specifies one of the contents that is red.

Form Works with PHP

$myData=$_GET[ data ];

$myData=$_GET[ data ]: gets data from HTML form and assigns its value to $myData. (Note: form method =”get”).

.
Example 4.9
(getDemo. php)
<html>
<body>
<form action="getDemo. php "  method="get">

<input type="text"  name="information">  <! - - user input - ->

</form>

<?php

$myData = $_GET[ information ];  // get input from the user
echo ("You have inputted: ". $myData); // show input value

?>
</body>
</html>
(Assume that you input “Hallo” and enter. )
Output:

Explanation:

action="getDemo. php " specifies getDemo. php as action file.

“method="get"” specifies “get” method to send data to the server.

“name="information"” specifies “information” as a key , specifies the contents you input as a value , and send the Key-Value pairs to the server.

$myData = $_GET[ information ] gets the value of “information” from an html form, and assign the value to $myData.

Form Works with PHP

$myData=$_POST[ data ];

$myData=$_POST[ data ]: obtains data from an html form and assigns its value to $myData. (Note: form method =”post”).

Example 4.10
(postDemo. php)
<html>
<body>
<form action="postDemo. php "  method="post">

<input type="text"  name="information">  <! - -user input - ->

</form>

<?php

$myData = $_POST[ information ];  // get input from user
echo ("You have inputted: ". $myData); // show input

?>
</body>
</html>
(Assume that you input “Hallo” and enter. )
Output:

Explanation:

action="postDemo. php " specifies postDemo. php as action file.

“method="post"” specifies “post” method to send data to the server.

“name="information"” specifies “information” as a key , specifies the contents you input as a value , and send the Key-Value pairs to the server.

$myData = $_POST[ information ] obtains the value of  “information” from an html form, and assign the value to $myData.

Exercise: Radio’s Colors

Radio Demo

Open your favorite PHP editor, write following code to it:

<html>
<p>Please Select Your Favorite Color</p>
<form method=get >
<input type="radio" name="color"

value="Red" >Red<br>    <
!
- - user input by radio - ->

<input type="radio" name="color"
value="Yellow" >Yellow<br>
<input type="radio" name="color"
value="Green" >Green<br>
<br><br>

<input type="submit" value="Submit">  <
!
- - submit - ->

<br><br>
</form>
</html>
<?php
echo "You Select:<br><br>";

$hobby = $_GET['color'];   // get the input from user
echo($hobby);    // show user input

?>

“Save ” the file with name “radioDemo. php”, and run the program.

Output:

Explanation:

<input type="radio" name="color"

value="Red" >Red<br>    <
!
- - user input by radio - ->

$hobby = $_GET['color'];   // gets the input from user

Assume that you selected “Green” radio.

type=”radio” is used to input data by single choice.

name=”color” specifies the inputted data that will be sent to the php file for processing.

value=”Green” specifies one of the optional contents.

On submitting the button, it sends the data as the “key/ value” pairs to PHP file for processing, the input name “color” is the key, and the selected content “Green” is the value.

“$hobby = $_GET['color'];” gets the value of “color” and assigns to $hobby,.

The value of “color” is Green.

Chapter 5

Dynamic Data

Date & Time

date(“M  d  Y”);
date( “h : i : s”);
date(“D  H  A”);

date(“M  d  Y”) displays month, date, year.

date( “h : i : s”) displays hour, minutes, second.

date(“D  H  A”) displays Day, Hour, AM/PM
Example 5.1
$date = date(“M  d  Y ”);
$hour = date( “h : i : s ”);
$week = date(“D  H  A ”);
echo $date;
echo $hour;
echo $week;

Output:      Nov 26 2015 02 : 29 : 02 Thu 14 PM

Explanation:

M: Jan-Dec

d: 01-31

Y: YYYY

h: 01-12

i: 00-59

s:  00-59

D:  Mon-Sun

H:  00-23

A:  AM or PM

String Process

strlen( );
strtoupper( );
strtolower( );

strlen( ) returns a length of strings and spaces.

strtoupper( ) returns an uppercase of strings.

strtolower( ) returns a lowercase of strings.
Example 5.2
$string=”  Hello World!   ”;
echo strlen( $string );
//return string length
echo strtoupper($string);
//return uppercase
echo strtolower($string);
//return lowercase

Output:      16   HELLO WORLD!   hello world!

Explanation:

strlen( $string ) returns 16.    (The length includes spaces. )

strtoupper($string) returns HELLO WORLD!

strtolower($string) returns hello world!

Redirection of Browser

header( “Location : $url”);

header( “Location : $url”) can redirect the browser  to another location.

“$url” specifies the location where to go.
Example 5.3
<?php
header( "Location:http://www. amazon. com") ;  //redirection

?>
<html>
<body>
</body>
</html>
Explanation:
header( "Location:http://www. amazon. com") ;
redirects the browser to www. amazon. com.

Information of Visitor

$_SERVER[“HTTP_USER_AGENT”];

$_SERVER[“REMOTE_ADDR”];

$_SERVER [“HTTP_USER_AGENT”] can identify the browser of visitors

$_SERVER [“REMOTE_ADDR”] can record the IP address of visitors.

Example 5.4
<?php
$browser = $_SERVER["HTTP_USER_AGENT"] ;
$address = $_SERVER["REMOTE_ADDR"] ;
echo "$browser";   echo "$address";
?>
Output:

Mozilla/4. 0 (compatible; MSIE 8. 0)…  80. xxx. xxx. 105

Explanation:

$_SERVER[“HTTP_USER_AGENT”] returns the browser information about the visitor.

$_SERVER[“REMOTE_ADDR”] returns the IP address of the visitor.

Cookie

setcookie ( “name”,  “value” ); // set cookie name and value.

$_COOKIE[“name”];  // get cookie value by cookie name.

A cookie is usually used to identify a user. It is a way to store information across multiple pages.

Example 5.5

<?php   // in a
.
php
setcookie("color", "blue");
//set color as blue
header("location: b. php");

?>

<?php   // in b
.
php

$mycolor = $_COOKIE["color"];
//get the value of color
echo  $mycolor;
?>
Output:    blue
Explanation:

In a. php, setcookie(“color”, “blue”) sets a cookie name as color and value as blue.

In b. php, $_COOKIE[“color”] gets a value “blue” by color.

Session
session is usually used to identify a user. It is a way to store information across multiple pages in a website.

SID is a constant containing a unique session id, which creates a group of 32 hexadecimal numbers like: 88d600a79be7ed38112b65863e17fa6f

“session_start()” starts a session.

“session_id()” get the session id.

Example:

// firstPage
.
php

<?php session_start() ?>   // start php session

Here is "First Page". <br><br>

Send Out a Session ID<br><br>

<a href = "secondPage
.
php? <?php echo(SID );?>">To Second Page </a>

<
!
- - pass session id to secondPage
.
php- ->

Output:

Please click the link “To Second Page ”.

//secondPage
.
php

<?php session_start() ?>  //start php session
Here is "Second Page". <br><br>
The Sesson Id is: <br><br>

<?php echo(session_id() );   //show session id

?>

Output:

Explanation:

A session makes data accessible across the multiple pages in a whole website.

“SID” creates a group of numbers as session IDs.

“session_start()” starts a session.

“session_id()” gets the session id.

Click the “To Second Page ”, the session id in the firstPage. php will be passed to the secondPage. php.

Session Usage

session_start( );  // begin to use session

$_SESSION[“name”]=value;  // set session name & value.

$_SESSION[“name”];  // get session value by name.

A session is usually used to identify a user. It is a way to store information across multiple pages.

Example 5.6

<?php  session_start( );    // in a
.
php

$_SESSION ["color"] = "green";    // set color as green
header("location: b. php");

?>

<?php  session_start( );    // in b
.
php

$carColor = $_SESSION ["color"] ;   //get the value of color
echo $carColor;
?>
Output:      green
Explanation:

In a. php, “$_SESSION[“color”] = “green”” set a session name as color and value as green.

In b. php, $_SESSION [“color”] gets a valuable green in color.

Open a File

fopen ($filename, mode);

fopen ($filename, mode) opens a file or URL.

Mode

Operation

r

open file for reading only, read from beginning.

w

open file for writing only, clear original content.

a

open file for writing only, append new content.

x

create a new file for writing only.

Important Notice: If above modes with “+ ” sign, means opening the file for reading and writing. e. g. r+, w+, a+, x+

Example 5.7

$filename = “myfile. txt”;
fopen( $filename, r );
// open the file for reading only
fopen( $filename, w );
// open the file for writing only

Explanation:

“fopen( $filename, r )” opens myfile. txt for reading only, and reads from the beginning.

“fopen( $filename, w )” opens myfile. txt for writing only, and clear the original contents.

Read a File

fread( $openfile, length );

“fread()” reads the content of a file.

“$openfile” specifies the opened file to read.

“length” specifies the maximum number of bytes to read.

Example 5.8

// The content of myfile
.
txt : “PHP is very good
!
”

<?php
$filename = "myfile. txt";
$openfile = fopen( $filename, r );

$content = fread( $openfile, 20 );    /* read 20 bytes from myfile
.
txt */
echo "$content";

?>

Output:      PHP is very good!

Explanation:

“fread( $openfile, 20 )” reads 20 bytes from myfile. txt, and read from the beginning.

$content = fread( ) assigns the reading contents to $content.

Write a File

fwrite( $openfile, “string”);

“fwrite( )” writes the contents to a file.

“$openfile” specifies the opened file to write.

“string” specifies the string to write.
Example 5.9
<?php
$filename = "myfile. txt";
$openfile = fopen( $filename, w );

$content = fwrite( $openfile, "Hello World! " );   /* write text to myfile
.
txt */

?>

Result:

“Hello World! ” is written into myfile. txt.

Explanation:

“fwrite( $openfile, “Hello World! ” )” clears the original content first, and writes “Hello World! ” at the beginning of the specified file.

Close a File

fclose ($openfile);

“$openfile” specifies the file that has been opened.

It is good practice to close the opened file after using that. You can release the memory, other processes may be able to use that file.

Example:

fcolse($openfile);   // close the opening file

Explanation:

After using the file myfile. txt, fclose( $openfile ) closes the opened file.

Exercise: Extract Sth
.

substr( ) Demo

Open your favorite PHP editor, write following codes to it:

<html>

<?php
echo 'substr("JavaScript in 8 Hours! ",4,6)  returns: '. "<br>";
echo substr("JavaScript in 8 Hours! ",4,6). "<br><br>";
echo 'substr("JavaScript in 8 Hours! ",11)  returns: '. "<br>";
echo substr("JavaScript in 8 Hours! ",11). "<br><br>";

?>

</html>

“Save ” the file with name “substrDemo. php”, and run the program.

Output:

substr("JavaScript in 8 Hours! ",4,6) returns:

Script
substr("JavaScript in 8 Hours! ",11) returns:

in 8 Hours!

Explanation:

substr(string, start, length) retrieves a substring by the specified parameters
substr("JavaScript in 8 Hours! ",4,6). " retrieves a substring from the original string “JavaScript in 8 Hours”, starting from index 4, the length of substring is 6 characters.

substr("JavaScript in 8 Hours! ",11). " retrieves a substring from the original string “JavaScript in 8 Hours”, starting from index 11, the length of the substring is from index 11 to the end.

Chapter 6

Class & Object

Class Definition

A class is a template for an object, and creates an object.

class  class-name{
var $variable;
function function-name ( ){ }
}

“class class-name {……}” is used to define a class.

“var” defines a variable in class. Variable is also known as “property”.

“function” defines a function in a class. The function is also known as “method”.

Example 6.1
class Color {   // define a class “Color”

var c1; var c2;    // declare two variable members
function brightness ( ) {…}   // declare a method member

}

Explanation:

“class Color” defines a class named “Color”. “var” defines two variables named “c1” and “c2”. “function” defines a function named “brightness”.

Object Declaration

Object is an instance of a class.

$object = new class-name;
$object -> variable;
$object -> function-name( );

“$object = new class-name;” creates a new object named “$object”.

“$object -> variable;” means that $object references a variable. The “variable” cannot have the symbol “$”.

“$object -> function-name ( );” means that $object calls a function.

Example 6.2

$obj = new Color;
//create an object  “$obj”

$obj -> c1;       // the object references the variable

$obj -> brightness ( );     // the object references the method

Explanation:

“$obj = new Color;” creates an object named” $obj”.

“ $obj -> c1” means $obj references variable “c1”.

“$obj -> brightness ( );” means that “$obj” references the function brightness( ){…}.

Note: in” $obj -> c1;”, the “c1” has no “$” symbol.

Class & Object
Example:
<?php
class color {        // define a class
var $c = "A default color";
}
$obj = new color();    // create an object
echo $obj -> c;    // an object references a variable

?>

Output:

A default color

Explanation:

“class color” defines a class “color”.

“$obj= new color();” creates an object “obj”.

“$obj -> c;” means that an object references a variable.

$this -
> variable

$this -> variable;

“$this -> variable;” is used to access the variable in the current class. $this represents the current object.

Note that a variable has no “$”.
Example 6.3
<?php
class color{        // define a class “color”
var $c = "a default color";
function brightness() {
echo $thi s
-
> c ;     // $this represents $obj

}}
$obj= new color();    // create an object
$obj -> brightness();
?>
Output:     a default color
Explanation:

“$this -> c” access the variable “c” in current class. $this represents “$obj”.

Note: in”$this -> c”, the “c” has no “$”.

Constructor (1)

When a function name is the same as a class name, the function is known as a constructor.

The constructor is used to initialize the class’s variable when create a new object.

Example 6.4
<?php
class color{
var $c1;
var $c2;
function color( $arg ) {  // This is a constructor

$this -> c1= $arg;  // constructor is used to initialize variabl e
.

echo $this -> c1;
} }
$obj= new color( yellow );
?>
Output:      yellow
Explanation:

“function color( $arg ) {  $this -> c1= $arg;  }” is a constructor.

When creating an object $obj, color(yellow) calls the constructor, and passes the argument “yellow” to constructor by $arg, than $arg assigns the value to “c1”.

“this” represents “$obj”.

Constructor (2)

You can use __construct( ) to work as a constructor.

__construct( );

The constructor is used to initialize the class’s variable when create a new object.

Example 6.5
<?php
class color{
var $c1; var $c2;
function __construct( $arg ) {  // This is a constructor

$this -> c1= $arg;  //constructor is used to initialize variable.

echo $this -> c1;
}}
$obj= new color( yellow );
?>
Output:      yellow
Explanation:

“function __construct ( $arg ) {  $this -> c1= $arg;  }” is a constructor.

When creating an object $obj, color(yellow) calls the constructor, and passes the argument “yellow” to constructor by $arg, than $arg assigns the value to “c1”.

“this” represents “$obj”.

Destructor

__destruct( ) can work as destructor to destroy an object.

__destructor( );

When ending a class instance, _destructor can be used.

Example 6.6
<?php
class color{
var $c1;
var $c2;
function __construct( $arg ) {  //
This is a constructor

$this -> c1= $arg;
echo $this -> c1;
}

function __destruct( ) {  //
This is a destructor
echo "<br> Using destructor... ";
}}
$obj= new color( yellow );
?>
Output:     yellow
Using destructor…
Explanation:

“function __destructor” is a destructor, which ends a class instance.

Extend Class

When a subclass extends a parent class, subclass obtains the variable and function from parent class.

class sub-class extends parent-class {……}

Example 6.7
class animal{
// parent class definition
}
class dog extends animal{    // inheritance

//
Subclass definition

}

class monkey extends animal{   // inheritance

//
Subclass definition
.

}

Explanation:

Class dog and class monkey are two subclass, they extend their parent class “animal”, including its variable and function.

Inheritance

The object of subclass can use the variable and function of the parent class.

Example 6.8
<?php
class animal{     // parent class
var $head;
function tail( ) {
echo "Dog's tail is small";
}}

class dog extends animal{    // subclass inheritance

}

$d = new dog( );

$d -> head = "big";   //references a variable of parent class.

echo "Dog's head is ". $d -> head. "<br>";

$d -> tail( );    //calls a function of the parent class.

?>

Output:

Dog's head is big

Dog's tail is small

Explanation:

$d is an object of the subclass.

“$d -> head” references a variable of the parent class.

“$d -> tail( );” calls a function of the parent class.

Class:: method ( )

Class can use:: to calls a function directly.

class-name :: function( );

Example 6.9
<?php
class A{
function display( ) {
echo "A function is called <br>";
}}
class B extends A{
function show(){

A :: display( );    // class A calls a function
echo "B function is called <br>";
}}
B :: show( );     // class B calls a function
?>
Output:      A function is called
B function is called
Explanation:

“A :: display( );” : Class A calls display( ).

“B:: show( );” : Class B calls show( ).

Exercise: Appointment

Class & Object

Open your favorite PHP editor, write following codes to it:

<html>
<?php
class setDate{    // define a class “setDate”

var $day;      // declare three variable members
var $month;
var $year;
function __construct($m,$d,$y){    // constructor

$this -> month=$m;      // initialization
$this -> day=$d;
$this -> year=$y;
echo "Constructor is called! <br><br>";
echo "The date is: ". $this -> month. "/". $this -> day. "/". $this -> year;
echo "<br><br>";
}
function __destruct(){    // destructor
echo "Destructor is called! ";
}
}

$obj=new setDate("12","6","2015");   /* create an object, and call constructor automatically */

?>

</html>

“Save ” the file with name “ClassObject. php”, and run the program.

Output:

Constructor is called!

The date is: 12/6/2015

Destructor is called!

Explanation:

“class setDate” creates a class “setDate”.

“var $day; var $month; var $year;” defines three member variables.

function __construct($m,$d,$y){ ……} defines a constructor, which is used to initialize the variables.

“$this -> variable;” is used to access the variable in the current class. $this represents the current object.

“function __destruct()” defines a destructor, which is used to end a class instance, release the variable memory.

“$obj=new setDate("12","6","2015")” creates an object $obj, automatically calls the constructor, and sends three parameters to the constructor for initializing variables.

The values of “$this -> month; $this -> day; $this -> year;” are 12, 6 and 2015 respectively.

Chapter 7

MySQL Basic

What is MySQL?

MySQL is a database which is composed of one or more tables; the table arranges the data into organized rows and columns. The table of database looks like this:

MySQL Data Type

Type

Explanation

int

An integer

decimal

A floating point number

date

A date in YYYY-MM-DD format

time

A time in HH:MM:SS format

year

A year in YYYY format

char( )

A string of defined fixed length

varchar( )

A string of defined changeable length

text

A string from 0 to 65535 characters

Example 7.1

/* When creating a database, you type following data: */
id int,
color varchar(20)
Explanation:

“id int ”: the column name is “id”, the data type is “int”..

“color varchar(20) ”: The column name is “color”, the data type is “varchar(20)”, which is a string of defined changeable length 20.

Column Modifiers

Modifiers

Explanation

auto_increment

automatically increase a value

not null

must contain data

unique

must be only one of its kind

primary key(arg)

specifies its argument as primary key

Example 7.2

/* When creating a database, you type following data: */
id int auto_increment ,
color varchar(20) not null,
primary key (id)
Explanation:

“id int auto_increment ”: The value id can automatically increase than the previous value.

“color varchar(20) not null ”: The data in “color” column must exist.

“primary key (id)” specifies “id” as a primary key.

phpMyAdmin

If you have installed “AppServ” to your computer, you can run “phpMydmin ”. “phpMyAdmin” is a popular visual MySQL software, Many experienced programmers usually use phpMyAdmin to execute MySQL.

Note:
phpMyAdmin’s appearance may be different in various versions, but the usage is the same
.

Run phpMyAdmin
Start a browser, enter an address:
http://localhost/phpmyadmin
username: root ,     password: 12345678

You can see the page like this: ( Maybe different
! )

Show Databases

Show Databases

show databases;

“show databases;” displays all existing databases currently.

Note: phpMyAdmin’s appearance may be different in various versions, but the usage is the same.

Example 7.3

Please click the “SQL” tag in the ToolBar as following:

Or click the third button “SQL ”.

You can see a “Run SQL query/queries window” like this:

(The above window is called “Run SQL query/queries window”, which is usually used to enter MySQL commands)

Please enter a command:

show databases;
then click the button “Go”.

Output:

Explanation:

“show databases;” displays four existing databases currently.   They are “information_schema”, “mysql”, “phpmyadmin” and “test”. (There are four databases in my computer server. )

Note:

When you want to use “Run SQL query/queries window” again to enter other MySQL commands, please click the “SQL ” tag in the TaskBar.

You can click “Edit” to re-enter MySQL commands.

Create a Database

create database databaseName;

“create database databaseName” can create a database.

“databaseName” specifies a database name.

Example 7.4

Please click the “SQL ” tag in the TaskBar as following:

Open “Run SQL query/queries window” like this:

Please enter:

create database study;

Click button “Go”.

Output:

Explanation:

“create database study;” creates a database named “study”.

You can click “Edit” to re-enter MySQL commands.

Select a Database

use databaseName;

Once you get connected with the MySQL server, it is required to select a particular database to work with.

“use databaseName”  command can select a database.

Example 7.5

Please click the “SQL ” tag in the TaskBar as following:

Open “Run SQL query/queries window” like this:

Please enter:

use study;
then click the button “Go”.

Output:

Explanation:

“use study;” select to use an existing database “study”.

You can click “Edit” to re-enter MySQL commands.

Create a table

create table table-name(column name  data type,…);

“create table table-name” can create a table.

“column name  data type,…” specifies the column name and its data type.

Example 7.6

Please click “SQL” to open “Run SQL query/queries window” , and enter:

use study;
create table colortable(id int auto_increment, color1 varchar(20), color2 varchar(20), color3 varchar(20), primary key(id));

Click “Go”.

Output:

Explanation:

“create table colortable ” creates a table named “colortable ”.

“id int” specifies a column named “id”, data type as ”int”.

“color1 varchar(20)” specifies a column named “color1”, data type as “varchar(20)”.

You can click “Edit” to re-enter MySQL commands.

Show Table

show tables;

“show tables” can show all tables in the current database.

Example 7.7

Please click “SQL” to open “Run SQL query/queries window” , and enter:

use study;
show tables;
Output:

Explanation:

“show tables;” shows a new table “colortable” in database “study. ”

Insert Data to Table

insert into table-name ( column1, column 2, column3 ) values (value1, value2, value3);

“column1, column 2, column3” will be respectively inserted data by “value1, value2, value3”

Example 7.8

Please click “SQL” to open “Run SQL query/queries window” , and enter:

use study;
insert into colortable (color1, color2, color3) values (“red”, “yellow”, “green”);

Output:

(To browse the table, please see next page. )

Explanation:

“color1, color 2, color3” will be respectively inserted data by “red, yellow, green”.

Browse Table

select * from table-name;

“select * from table-name;” can browse a specified table.

“*” represents all columns in the table.

Example 7.9

Please click “SQL” to open “Run SQL query/queries window” , and enter:

use study;
select * from colortable;
Output:
colortable

Explanation:

“select * from colortable;” shows all column data in “colortable”

Alter a table

alter table table-name add columnName type;

New column can be added to a table by using the “alter” command.

Example 7.10

Please click “SQL” to open “Run SQL query/queries window” , and enter:

use study;
alter table colortable add color4 varchar(20);

Output:    (Please use following command to browser table. )

use study;   select * from colortable;

Explanation:

“add color4 varchar(20)” adds a new column named color4.

Update Data

update table-name set column-name=value where id=int;

A value can be changed in a column by its id.

Example 7.11

Please click “SQL” to open “Run SQL query/queries window” , and enter:

use study;
update colortable set color4=”blue” where id=1;

Output:

(Please use following command to browser table. )

use study;   select * from colortable;

Explanation:

“set color4=”blue” where id=1” can update the value null to blue in the row where id is 1.

Select Queries

select column-name from table-name;

“select column-name from table-name” can show a specified column data in the table.

Example 7.12

Please click “SQL” to open “Run SQL query/queries window” , and enter:

use study;
select color2 from colortable;
Output:

Explanation:

“select color2 from colortable” shows data of color2 only from colortable.

Database Commands

MySQL Commands

Descriptions

CREATE DATABASE database-name

create database

USE database-name

use a database

SHOW database-name

show a database

DROP database-name

remove a database

Table Commands

MySQL Commands

Descriptions

CREATE TABLE  table-name

create table

SHOW TABLE

show all tables

DESCRIBE

show fields property

SHOW COLUMNS FROM table-name

show a field property

SHOW INDEX FROM table-name

list index field property

ALTER TABLE table-name

change data of a field

DROP TABLE table-name

remove a table

OPTIMIZE table-name

optimize a table

Field Modifiers

Modifier

Descriptions

AUTO_INCREMENT

automatically generate a serial number

NUT NULL

cannot be empty value

NULL

can be empty value

UNIQUE

cannot not duplicate any entry

PRIMARY KEY

specify as a primary key

DEFAULT

specify a default value for a field

INDEX

specify an index field for table

Operation Commands

Modifier

USE

SELECT field FROM table WHERE condition

query data

INSERT INTO table ( field ) VALUES (value)

insert data

DELETE FROM table WHERE condition

delete data

UPDATE table SET field = value WHERE condition

update data

PEPLACE INTO table (field ) VALUES (value)

replace data

Exercise: Set Database

Create a database with a table

(1)

Open phpMyAdmin
.

(2)

Enter username:
root
,   password:
12345678.

(3)

Click
“SQL”
to open
“Run SQL query/queries window”, create a database named “ mydb
”, enter a command:

create database mydb;

(4)

Click
“SQL”
to open
“Run SQL query/queries window”, create a table named “ mytable
”, enter a command:

use mydb;
create table mytable(id int auto_increment, book1 varchar(20), book2 varchar(20), book3 varchar(20), primary key(id));

(5)

Click
“SQL”
to open
“Run SQL query/queries window”, insert some data into the table “ mytable
”, enter command:

use mydb;
insert into mytable (book1, book2, book3) values (“PHP”, “JSP”, “ASP”);
insert into mytable (book1, book2, book3) values (“LAMP”, “J2EE”, “HTLM”);

(6)

Click
“SQL”
to open
“Run SQL query/queries window”
,  to browse the table, please enter:

use mydb;
select * from mytable;

(7)

You can see a new database “ mydb
” with a table “ mytable
” as follows
.

Chapter 8

MySQL & PHP

Connect MySql Server

mysqli_connect( “host”, “username”, “password” );

“mysqli_connect( ) lets PHP connect MySql server.

“host”: specifies a host name.

“username”: specifies a MySql user name.

“password”: specifies a MySql password.

Example 8.1

<?php

$con= mysqli_connect( "localhost", "root", "12345678" ) ;
if( $con ) {    // if connect MySQL server successfully
echo  " Connect successfully! ";

}

?>

Output:

Connect successfully!

Explanation:

“$con=mysqli_connect( “localhost”, “root”, “12345678” )” try to make PHP connect MySql server. If successful, it returns true, if failed, it returns false.

“if ( $con )” can test $con true or false.

Select Database

MySqli_select_db( $con, “database-name” );

The mysqli_select_db( ) is used to select a database for the connection.

“$con” is the connection to MySql server. (See previous page).

“database-name” specifies the name of the database.

Example 8.2
<?php
$select=mysqli_select_db( $con, "study" );
if( $select ) {   // if select database “study” successfully
echo  " Select db successfully! ";

}

?>

Output:

Select db successfully!

Explanation:

$select=mysqli_select_db( $con, "study" ); try to make a PHP select MySql database. If succeed it returns true. If fail it returns false.

“if ( $select )” can test $select true or false.

Insert Table Data

$sql=”insert into table-name (columns) value (\”values\”)”;

$query=mysqli_query($con, $sql);

$sql=”insert into table-name (columns) value (\”values\”)” is used to insert table data.

$query=mysqli_query($con, $sql) executes the query.

“$con” is the connection to MySql server. (See previous page).

In the list of MySQL query values, any string data should be enclosed by escaping quotes.

For example:  “\ value1 \”, “\ value2 \”, “\ value3 \”.

Example 8.3

<?php

$sql="insert into colortable (color1, color2, color3, color4) value (\"pink\",\"navy\",\"purple\",\"orange\")";

$query=mysqli_query( $con,$sql);   // run query
if( $query ) {
echo  " Insert data successfully! ";
}
?>
Output:
Insert data successfully!
Check database:

Explanation:

"insert into colortable (color1, color2, color3, color4) value (\"pink\",\"navy\",\"purple\",\"orange\")";” inserts four values into four columns respectively.

“mysqli_query( $con,$sql);” runs the query.

In the list of MySQL query values, any string data should be enclosed by escaping quotes.

For example:  “\ value1 \”, “\ value2 \”, “\ value3 \”.

Alter Table Structure

$sql=”alter table table-name add column data type”;

$query=mysqli_query($con, $sql);

$sql=”alter table table-name add column data type” is used to add a new column.

$query=mysqli_query($con, $sql) executes the query.

“$con” is the connection to MySql server. (See previous page).

Example 8.4

<?php

$sql="alter table colortable add column color5 varchar(20) ";

$query=mysqli_query( $con, $sql);   // run query
if( $query ) {
echo  " Add columns successfully! ";
}
?>
Output:
Add columns successfully!
Check database:

Explanation:

“alter table colortable add column color5 varchar(20)” adds a new column “color5” to table “colortable”.

mysqli_query( $sql, $con) performs the query.

Update Table Data

$sql=”update table-name set column-name where id = int”;

$query=mysqli_query($con, $sql);

“update table-name set column-name where id = int” can update the table data.

Example 8.5

<?php

$sql="update colortable set color5='sky' where id =1 ";

$sql="update colortable set color5='olive' where id =2 ";

$query=mysqli_query( $con, $sql);   // run query
if( $query ) {
echo  " update successfully! ";
}
?>
Output:          update successfully!
Check database:

Explanation:

"update colortable set color5='sky' where id =1 " renews the color5 data to “sky” where the id is 1 in “colortable”.

Retrieve Table Data

$sql=”select column from table-name”;

$query=mysqli_query($con, $sql);

$sql=”select column from table-name” is used to retrieve table data by the column name from a table.

$query=mysqli_query($con, $sql) executes the query.

“$con” is the connection to MySql server. (See previous page).

“mysqli_fetch_array($query))” returns an array which contains the data of query.

Example 8.6

Given colortable

<?php

$sql="select id, color1 from colortable ";

$query=mysqli_query( $con,$sql );   // run query
if( $query ) {
echo  " Retrieve data successfully! <br>";
}

while($row = mysqli_fetch_array($query)){   //return an array
echo("<br> ID: ". $row["id"]);    //array named $row
echo("<br> color1: ". $row["color1"]);   //array named $row

}
?>
Output:

Explanation:

“select id, color1 from colortable” retrieves table data by the id and color1 from the colortable.

mysqli_query($con, $sql) performs the query.

“mysqli_fetch_array($query))” returns an array which contains the data of query.

mysqli_fetch_row( )

mysqli_fetch_row( );

“mysqli_fetch_row( )” returns an indexed array of the row. Its key is always a number type.   e. g. [ number ] => value.

Example 8.7

Given colortable

<?php

$sql="select * from colortable";  //
* represents all columns

$query=mysqli_query( $con, $sql);

$array=mysqli_fetch_row ($query) ;
print_r($array);    // print_r( ) is used to print the array

?>

Output:

Array ( [0] => 1   [1] => red    [2] => yellow     [3] => green

[4] => blue     [5] => sky)

Explanation:

mysqli_fetch_row( ) returns an array of the row, its key is always number type.

print_r( ) is used to print array.

mysqli_fetch_assoc( )

mysqli_fetch_assoc( );

“mysqli_fetch_assoc( )” returns an assoc array of the row. Its key is always a string type.   e. g. [ string ]=> value.

Example 8.8

Given colortable

<?php

$sql="select * from colortable";  // * represents all columns

$query=mysqli_query( $con, $sql);

$array=mysqli_fetch_assoc ($query) ;
print_r($array);    // print_r( ) is used to print the array

?>

Output:

Array ( [id] => 1   [color1] => red  [color2] => yellow   [color3] => green  [color4] => blue  [color5] => sky)

Explanation:

mysqli_fetch_assoc( ) returns an array of the row, its key is always a string type.

print_r( ) is used to print the array.

mysqli_fetch_array( )

mysqli_fetch_array( );

“mysqli_fetch_array( )” returns both indexed and associative array of the row. Their keys are both number type and string type.   e. g. [number]=>value    [ string ]=>value.

Example 8.9

Given colortable

<?php

$sql="select * from colortable";  //
* represents all columns

$query=mysqli_query( $con, $sql);

$array=mysqli_fetch_array ($query);
print_r($array);    // print_r( ) is used to print array

?>
Output:
Array (
[0] => 1             [id] => 1
[1] => red         [color1] => red
[2] => yellow      [color2] => yellow
[3] => green       [color3] => green
[4] => blue         [color4] => blue
[5] => sky           [color5] => sky)
Explanation:

mysqli_fetch_array( ) returns an array of the row, their keys are always both number type and string type.

mysqli_num_rows( )

mysqli_num_rows( $query );

mysqli_num_rows( $query) returns the total number of rows from $query, which is generated by mysqli_query( ).

Example 8.10

Given colortable

<?php

$sql = "select * from colortable";  //
* represents all columns

$query = mysqli_query($con, $sql);
$row_number = mysqli_num_rows( $query );
echo  $row_number;
?>
Outputs:
2
Explanation:

$row_number=mysqli_num_rows( $query ) returns the total number of rows from $query. Because there are two rows in colortable, the output is 2.

mysqli_close( )

mysqli_close( );

Close a previously opened database connection to MySql server.

Example 8.11

<?php

$con= mysqli_connect( “localhost”, “root”, “12345678” );

//
....
some PHP code
...

mysqli_close($con) ;
?>
Explanation:

mysqli_close($con) closes $con connection to the MySql server.

It is a good practice to close the connection explicitly when the script ends is execution.

mysqli_xxx_xxx (  ) Summary

Commands

Description

mysqli_affected_row ( )

Returns the number of row affected by query

mysqli_close ( )

Closes the connection with MySQL server

mysqli_connect ( )

Creates an initial connection with MySQL server

mysqli_create_db ( )

Creates a database on the MySQL server

mysqli_data_seek ( )

Adjusts the result pointer to a random row in the results

mysqli_db_query ( )

This function was deprecated in PHP
5
.
3
.
0

mysqli_error ( )

Returns a string with the error description

mysqli_fetch_array ( )

Returns an array of strings associated with fetched row

mysqli_fetch_assoc ( )

Returns an associative array of strings of fetched row

mysqli_fetch_row ( )

Returns an indexed array of strings of the fetched row

mysqli_free_result ( )

Clears the system memory associated with the result

mysqli_get_server_info ( )

Returns a string with the MySQL server version

mysqli_num_rows ( )

Returns the number of rows in the result set

mysqli_query( )

Submits a query to the database on the server

mysqli_real_escape_string ( )

Escapes special characters in a string for MySQL

mysqli_result ( )

Returns a string of one cell from a MySQL result set

mysqli_select_db ( )

Selects the database to use by database name

Exercise: Work Together
PHP with MySQL
Open an editor, write following code to it:
<?php

$con = mysqli_connect ( "localhost", "root", "12345678" );
if ($con) {  // connect MySQL server
echo " Connect successfully! ";
}
$select = mysqli_select_db ( $con, "mydb" );
if ($select) {  //
“mydb” has been created in chapter 6
echo " Select db successfully! <br><br>";
}
?>
<?php

$sql="select id, book1, book2, book3 from mytable";

$query=mysqli_query( $con,$sql );  // run query
if( $query ) {
echo  " Retrieve data successfully! <br>";
}

while($row = mysqli_fetch_array($query)){  //return an array
echo("<br><br> ID: ". $row["id"]);   //array named $row
echo("<br> book1: ". $row["book1"]);
echo("<br> book2: ". $row["book2"]);
echo("<br> book3: ". $row["book3"]);
}
?>

“Save ” the file with name “phpwithmysql. php”, run the program, and see the output:

Output:

Explanation:

“mysqli_connect ( "localhost", "root", "12345678" )" connects a MySQL server by using hostname, username and password.

“mysqli_select_db ( $con, "mydb" )” selects a database by specifying a server and database name.

“select id, book1, book2, book3 from mytable” retrieves table data by the id, book1, book2,  and color3 from mytable.

“mysqli_query( $con,$sql )” executes the query.

“mysqli_fetch_array($query)” returns an array which contains the data of query.

Appendix 1

PHP Security Projects

Why Security Code?

It is very important to ensure the safety of PHP website on Internet. There are various dangerous attacks from anonymous hackers. These risks are listed as follows:

Name

Malicious Behaviors

Cross-Site Scripting

Steal user information

Spoofed Forms

Remove client-side data

SQL Injection

Ruin database data

Remote Code Injection

Controlled by attacker

Command Injection

Execute bad commands

Session Fixation

Set another person's SID

Session Hijack

Hijack user session key

……

……

Attacker inputs malicious codes in HTML form.
<input type=”password” name= “password ”>
<input type= “text” name= “characters ” />

<textarea name = “words ” rows= size1 cols= size2>

1:  Filter Malicious Password

ctype_alnum( $_POST[ “password ” ])

“ctype_alnum ( )” only accepts a to z characters and 0 to 9 numbers, and returns true. Don’t allow <?, <%, <! , #, $, %, ^, &, * and any other symbols.

Example a1

To filter malicious password, the PHP codes look like this:

<form action="" method="post">
<input type="password" name="password" >
</form>
<?php

$clean = array( );         // defines an array
if ( ctype_alnum ( $_POST["password"]))   // filter

$clean ["password"] = $_POST["password"];
echo $clean ["password"];
?>
Explanation:

“$clean = array( );” defines an array named “$clean”.

“ctype_alnum ( $_POST[“password”])” only allows a to z and 0 to 9, and return true.

“$clean [“password”]” stores the characters or numbers, without other symbols such as @, #, $, %, &, <?, <%, <! …….

2:  Filter Malicious Characters

ctype_alpha( $_POST[ “characters” ])

“ctype_alpha( )” only accepts a to z characters, and returns true. Don’t allow 0 to 9 numbers and <?, <%, <! , #, $, %, ^, &, and any other symbols.

Example a2

To filter malicious characters, the PHP codes look like this:

<form action="" method="post">
<input type="text" name="characters" >
</form>
<?php

$clean = array( );         // defines an array
if ( ctype_alpha ( $_POST["characters"]))   // filter

$clean ["characters"] = $_POST["characters"];
echo $clean ["characters"];
?>
Explanation:

“$clean = array( );” defines an array named “$clean”.

“ctype_alpha ( $_POST[“characters”])” only allows a to z characters, and return true.

“$clean [“characters”]” stores characters only, without any numbers 0 to 9 and other symbols such as @, #, $, %, &, <?, <%, <! …….

3:  Filter Malicious Input

str_replace("ch1", "ch2 ", $_POST [“text”] )

“str_replace( )” can replace character1 by charcter2 in what user have input.

“$_POST[text]” is the text inputted by user.
Example a3
<form action="" method="post">
<input type="text" name="characters" />
</form>
<?php
$clean = array( );
$text=$_POST[characters];   // user input
switch ($text)     // filter user input “$text”

{
case "malicious": $clean["characters"]=str_replace("malicious", "good", $text); break;    // replace malicious by good
case "@":

$clean["characters"]= str_replace("@", "(at)", $text);
break;     // replace @ by at
case "%":

$clean["characters"]= str_replace("%", "percent", $text); break;     // replace % by percent

}

echo $clean["characters"];

?>

Result:

When entering “malicious”, it returns “good”.

When entering “@”, it returns “(at)”.

When entering “%”, it returns “percent”.

Explanation:

“str_replace("malicious", " good ", $_POST[text]” replaces “malicious” by a “good” string.

“$str_replace("@", "(at)", $_POST[text]);” replaces @ by “(at)”.

“str_replace("%", "percent", $_POST[text]);” replaces % by “percent”.

$clean[“text”] stores the text you need.

4:  Limit Specified Input

in_array( $_POST [“words”], myarray )

“in_array ( )” can limit the inputted words from users. Allow specified characters or numbers that can be inputted, and returns true.

Example a4

<form action="" method="post">

<input type="text" name="words" />  <! - - user input- ->

</form>
<?php
$clean = array( );    // define an array

$myarray = array( "Rose", "Andy", "Judy", "Tomy" );
if ( in_array( $_POST["words"],  $myarray ) ){ //filter

$clean["words"] = $_POST["words"];   // user input

}
echo $clean["words"];
?>
Result:
Rose, Andy, Judy, Tomy
Explanation:

“$myarray = array( “Rose”, “Andy”, “Judy”, “Tomy” );” specifies  the inputted words that are one of the “Rose”, “Andy”, “Judy”, “Tomy” only.

“in_array( $_POST[“words”],  $myarray)” checks the inputted word to see if it accords with the specified character or numbers in $myarray.

“$clean[“words”]” stores the specified words only.

5:  Escape Output

“Escape Output” means encoding the output so that the original meaning is preserved, which can prevent the user from potentially damaging commands.

htmlentities( );
htmlspecialchars( );

“htmlentities( );” and “htmlspecialchars( )” can convert characters to HTML entities in source code.

Note: To check the source code with IE browser:

view -> source
Example a5
<?php
$str = "< © Ray >";
echo htmlentities ( $str );   // escape output

?>
Output:
View source code:   &lt;&copy;Ray;&gt;
Explanation

“htmlentities($str)” converts the "< © Ray >" to html entities.

“&lt;” are html entities, meaning “<”.

“&copy” are html entities, meaning “©”.

“&gt” are html entities, meaning “>”.

htmlspecialchars( ) is almost the same as htmlentities( ).

To check the source code in IE browser: view -> source

6:  Protect Database

mysql_real_escape_string( )

“mysql_real_escape_string( )” can eliminate the risk of SQL injection attacks.

“$cleanVariable = mysqli_real_escape_string($con, $_POST['input']);” can escape the input values.

Example a6
<form action="" method="post">
<input type="text" name="color1"><br>
<input type="text" name="color2"><br>
<input type="text" name="color3"><br>
<input type="text" name="color4"><br>
<input type="text" name="color5"><br>
<input type="submit" value="submit">

</form>  <
!
- - user input data by the form - ->

<?php

$con= mysqli_connect( "localhost", "root", "12345678" );
if( $con ) {
echo  " Connect successfully! <br><br>";
}
$select=mysqli_select_db( $con, "study" );
if( $select ) {
echo  " Select db successfully!!! <br><br>";

}    // “$_POST['color']” is an input from the user
.

$clean1 = mysqli_real_escape_string ($con, $_POST['color1']);    // filter

$clean2 = mysqli_real_escape_string ($con, $_POST['color2']);    // filter

$clean3 = mysqli_real_escape_string ($con, $_POST['color3']);     // filter

$clean4 = mysqli_real_escape_string ($con, $_POST['color4']);     // filter

$clean5 = mysqli_real_escape_string ($con, $_POST['color5']);     // filter

$sql="INSERT INTO colortable (color1, color2, color3, color4, color5)

VALUES ('$clean1', '$clean2', '$clean3','$clean4', '$clean5')";
mysqli_query($con,$sql)    // insert clean values to the database

?>

(Assume input: white, black, copper, silver, golden)

Output:

Connect successfully
!
Select db successfully
!!!

Check database:

Explanation:

“ mysql_real_escape_string(  )” can escape the input for database, and prevent the attack of SQL injection.

“$_POST['color']” is an input from user.

'$clean1', '$clean2', '$clean3','$clean4', '$clean5' have been escaped, they are clean variables now.

Appendix 2

Tests & Answers

Tests
Please choose the correct answer.
(1)
<?php
fill in here multiply($x, $y){   // defines a function
calculate($x, $y);

}

fill in here calculate($a, $b){   // defines a function

$result = $a * $b;
echo("The value is $result");
}
?>
<?php
multiply(10,20);
?>

1. void     B. int    C. def     D. function

(2)
<?php
echo "while statement: <br>";
$value1=1;
fill in here ($value1<=10){   // loop statement
echo $value1. "&nbsp;";
$value1++;
}
echo "<br><br>";
echo "do... while statement: <br>";
$value2=1;
fill in here {   // loop statement
echo $value2. "&nbsp;";
$value2++;
}while($value2<=10);
echo "<br><br>";
echo "for statement: <br>";
fill in here ($i=1;$i<=10;$i++){    // loop statement

$value3=$i;
echo $value3. "&nbsp;";
}
?>

1. while      do      for
2. switch      for      while
3. while      switch     for
4. for      do      while

(3)
<html>
<body>
<?
$a = array("zero", "one", "two");
echo "In array('zero', 'one', 'two'): <br><br>";
fill in here ($a as $key => $v){    // iterates through array
echo "The number ". $key. " element:  <br>";
echo "key is: ". $key. ",   ";
echo "value is: ". $v. "<br><br><br>";
}
?>
</body>
</html>

1. while       B. do      C. foreach       D. for

(4)
<html>
<p>Please Select Your Favorite Color</p>
<form method=get >
<input type="radio" name="color"
value="Red" >Red<br>
<input type="radio" name="color"
value="Yellow" >Yellow<br>
<input type="radio" name="color"
value="Green" >Green<br>
<br><br>
<input type="submit" value="Submit">
<br><br>
</form>
</html>
<?php
echo "You Select:<br><br>";

$hobby = fill in here ['color'];   // gets submitted data
echo($hobby);

?>

1. $_POST     B. $_GET     C. $_FILES    D. $_ENV

(5)

<?php
fill in here ( "Location: http://www. amazon. com") ;

// redirects the browser to www
.
amazon
.
com
.

?>

1. url        B. redirect       C. function        D. header

(6)
<?php
class color{        //class definition
var $c = "a default color";
function brightness() {
echo $this -> c;     // $this represents $obj
}
}

$obj= fill in here color();    // creates an object

$obj -> brightness();

?>

1. Object      B. create     C. new      D. Class

(7)

MySQL Commands

Description

SELECT field fill in here table WHERE condition

query data

INSERT fill in here table ( field ) VALUES (value)

insert data

UPDATE table fill in here field = value WHERE condition

update data

1. INTO         FROM       SET
2. FROM       INTO         SET
3. INTO         SET           FROM
4. SET           FROM       INTO

(8)

<?php

$con= fill in here ( "localhost", "root", "12345678" );

// connects MySQL server
if( $con ) {
echo  " Connect successfully! ";
}
?>

1. mysqli_connect       B. mysqli      C. connect      D. server

(9)
<?php
$select = fill in here ( $con, "study" );

// selects a database “study”
.

if( $select ) {
echo  " Select db successfully! ";
}
?>

1. mysqli       B. select     C. db.     D. mysqli_select_db

(10)

<?php

$sql=” fill in here into colortable (color1, color2, color3, color4) value (\"pink\",\"navy\",\"purple\",\"orange\")";

// inserts table data
$query=mysqli_query( $con,$sql);
if( $query ) {
echo  " Insert data successfully! ";
}
?>

1. add       B. put      C. insert     D. include

(11)
<?php
function test ($a, $b, $c) {
$sum=$a+$b+$c;
echo $sum;
}

fill in here
(3, 6, 9) ;     // call the function test

?>

1. call      B. test      C. function     D. return

(12)
<?php
$number=20;
fill in here ( $number ) {   // evaluate the variable $number
case 10 : echo “Running case 10”;  break;
case 20 : echo “Running case 20”;  break;
case 30 : echo “Running case 30”;  break;
default
:   echo “Running default code”;  break;  }

?>

1. switch       B
.
for       C
.
while       D
.
do

(13)

<?php

$color =array("yellow", "red", "blue", "white");
fill in here
( $color ) ;     // sort array elements
foreach( $color as $value ) { echo "$value ";}

?>

1. array_sort        B. arrange      C. $sort      D. sort

(14)

<form  fill in here =”myfile. php”  method=”get”>

// specifies “myfile
.
php” to processes data

<input type=”text”  name=”information”>

</form>

1. name        B. action     C. act      D. id

(15)
<?php
$filename = "myfile. txt";
$openfile = fopen( $filename, w );

$content = fill in here ( $openfile, "Hello World! " );

// writes “Hello World
!
” to specified file
.

?>

1. write     B. input      C. fwrite     D. enter

(16)
class animal{
// parent class definition
}

class dog fill in here animal{    // inheritance

// sub class definition

}

class monkey fill in here animal{      // inheritance

// sub class definition.

}

1. extends       B. inheritance      C. inherit     D. extend

(17)

MySQL Commands

Descriptions

fill in   DATABASE databaseName

create database

fill in databaseName

use a database

fill in databaseName

show a database

fill in databaseName

remove a database

1. DROP          SHOW         USE          CREATE

2. USE             CREATE     SHOW       DROP

3. CREATE      USE             DROP       SHOW

4. CREATE      USE             SHOW       DROP

(18)

<?php

$sql=" fill in table colortable add column color5 varchar(20) ";

// adds a new column “color5” to table “colortable”

$query=mysqli_query( $con, $sql);
if( $query ) {
echo  " Add columns successfully! ";
}
?>

1. add       B. alter       C. modify      D. change

(19)
use study;      # use database “study”
fill in color2 from colortable;

# shows data of color2 only from colortable
.

1. show      B. alter      C. select      D. update

(20)

<?php

$con= mysqli_connect( “localhost”, “root”, “12345678” );

// .... some PHP code...

fill in here
($con
)
;    // close a previously opened database connection to MySql server
.

?>

1. close      B. end      C. exit      D. mysqli_close

(21)

<?php
function test( fill in here
) {    /*  declare a function with arguments   */
echo (“$arg”);

}

test(“display a sample”) ;  // call the function, pass args
.

?>

A. $argument        B. $arg        C. &argument      D. &arg

(22)
<?php
function multiply($x, $y){
fill in here
$x * $y;
// pass the result value to caller

}
?>
<?php

$result = multiply(10,20);    // this is a caller
echo $result;

?>

A. pass        B. send       C. return        D. continue

(23)
<?php
$array1=array ("A", "B", "C");
$array2=array ("D", "E", "F");

$array = fill in here ( $array1, $array2 );   // merge arrays
foreach( $array as $value) { echo("$value " );}

?>

A. merge     B. array. merge     C. array_merge     D. combine

(24)
<html>
<body>
<form action="postDemo. php "  method="post">

<input type="text"  name="information">  <! - -user input - ->

</form>

<?php

$myData = fill in here [ information ];  // get input from user
echo ("You have inputted: ". $myData); // show input

?>
</body>
</html>

A. $_POST     B. $_GET     C. $_FILES    D. $_ENV

(25)

// firstPage
.
php

<?php fill in here
() ?>   // start php session

Here is "First Page". <br><br>

Send Out a Session ID<br><br>

<a href = "secondPage
.
php? <?php echo(SID );?>">To Second Page </a>

<! - - pass session id to secondPage. php- ->

A. session     B. start     C. session. start     D. session_start

(26)
<?php
class color{
var $c1; var $c2;
function fill in here( $arg ) {  // This is a constructor

$this -> c1= $arg;   //constructor is used to initialize variable.

echo $this -> c1;
}}
$obj= new color( yellow );
?>
A.   construct
B.   __construct
C.   constructor
D.   __constructor
(27)

MySQL Commands

Descriptions

fill in here TABLE  table-name

create table

fill in here TABLE

show all tables

fill in here TABLE table-name

change data of a field

fill in here TABLE table-name

remove a table

A.   CREATE        SHOW      CHANGE      REMOVE

B.   NEW        DISPLAY         ALTER         DELETE

C.   NEW        DISPLAY        ALTER         REMOVE

D.   CREATE       SHOW        ALTER         DROP

(28)
<?php
$sql="select * from colortable";
$query=mysqli_query( $con, $sql);

$array=mysqli_fetch_ fill in here
($query) ;

// return an array, its key is always int type
print_r($array);

?>

A. index      B. array       C. row       D. assoc

(29)
<?php
$filename = "myfile. txt";
$openfile = fopen( $filename, r );

$content = fill in here ( $openfile, 20 );    /* read 20 bytes from myfile. txt */
echo "$content";

?>

A. read      B. fread      C. readFile      D. fileRead

(30)
<?php
class A{
function display( ) {
echo "A function is called <br>";
}}
class B extends A{
function show(){

A fill in here display( );    // class A calls a function
echo "B function is called <br>";

}}

B fill in here show( );     // class B calls a function

?>

A.
::           B.
->          C. :         D.
.

(31)

SQL Modifier

Descriptions

fill in here

can be empty value

fill in here

cannot not duplicate any entry

fill in here

specify a default value for a field

fill in here

specify an index field for table

A.   EMPTY        EXCLUSIVE       DEFAULT      KEY

B.   BLANK         UNIQUE           VALUE            INDEX

C.   NULL            SOLE               DEFAULT        KEY

D.   NULL            UNIQUE           DEFAULT        INDEX

(32)

<?php

$sql="select * from colortable";   // * represents all columns

$query=mysqli_query( $con, $sql);

$array=mysqli_fetch_ fill in here
($query) ;

// return an array, its key is always string type
print_r($array);    // print_r( ) is used to print array

?>

A. index      B. array       C. row       D. assoc

Answers

01

D

17

D

02

A

18

B

03

C

19

C

04

B

20

D

05

D

21

B

06

C

22

C

07

B

23

C

08

A

24

A

09

D

25

D

10

C

26

B

11

B

27

D

12

A

28

C

13

D

29

B

14

B

30

A

15

C

31

D

16

A

32

D

Note:

This book is only for beginners, it is not suitable for experienced programmers.

Source Code Download Link:

https://forms
.
aweber
.
com/form/50/1828597050
.
htm

Source Code Download
Ray Yao’s eBooks & Books on Amazon
Advanced C++ Programming by Ray Yao
Advanced Java Programming by Ray Yao
AngularJs Programming by Ray Yao
C# Programming by Ray Yao
C# Interview & Certification Exam
C++ Programming by Ray Yao
C++ Interview & Certification Exam
Django Programming by Ray Yao
Go Programming by Ray Yao
Html Css Programming by Ray Yao
Html Css Interview & Certification Exam
Java Programming by Ray Yao
Java Interview & Certification Exam
JavaScript Programming by Ray Yao
JavaScript 50 Useful Programs
JavaScript Interview & Certification Exam
JQuery Programming by Ray Yao
JQuery Interview & Certification Exam
Kotlin Programming by Ray Yao
Linux Command Line
Linux Interview & Certification Exam
MySql Programming by Ray Yao
Node.Js Programming by Ray Yao
Php Interview & Certification Exam
Php MySql Programming by Ray Yao
PowerShell Programming by Ray Yao
Python Programming by Ray Yao
Python Interview & Certification Exam
R Programming by Ray Yao
Ruby Programming by Ray Yao
Rust Programming by Ray Yao
Scala Programming by Ray Yao
Shell Scripting Programming by Ray Yao
Visual Basic Programming by Ray Yao
Visual Basic Interview & Certification Exam
Xml Json Programming by Ray Yao
Source Code Download Link:

https://forms
.
aweber
.
com/form/50/1828597050
.
htm