TERAEXE › ebooks › The_Easiest_Way_to_Learn_PHP... · The Easiest Way to Learn PHP & MySQL...
Transcript of TERAEXE › ebooks › The_Easiest_Way_to_Learn_PHP... · The Easiest Way to Learn PHP & MySQL...
Author: Alvaro J. Gene
Alias: Socket_0x03
Website: www.teraexe.com
Email: [email protected]
© Copyright 2014. Alvaro J. Gene. All rights reserved
The Easiest Way to Learn PHP & MySQL
Version 1.2
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
1
TABLE OF CONTENT
Introduction .................................................................................................................................................................... 8
Basic Concepts ................................................................................................................................................................. 9
PHP: Basic Applications ............................................................................................................................................. 10
Exercise One: PHP – Printing Text ............................................................................................................................... 10
Exercise Two: PHP – A Second Method to Print Text.................................................................................................. 11
Exercise Three: PHP – A Line Break ............................................................................................................................ 11
Exercise Four: PHP – Declaring Variables.................................................................................................................... 12
Exercise Five: PHP – Declaring Variables – Method Two ........................................................................................... 13
Exercise Six: PHP – Information about Server ............................................................................................................. 13
Exercise Seven: PHP – Declaring Variables – Variable Scope ..................................................................................... 14
Exercise Eight: PHP – Variable Scope – The Global Keyword .................................................................................... 15
Exercise Nine: PHP – Variable Scope – The Global Keyword – Part 2 ....................................................................... 16
Exercise Ten: PHP – Variables – The Static Keyword ................................................................................................. 17
Exercise Eleven: PHP – Booleans ................................................................................................................................. 19
Exercise Twelve: PHP – If Statement............................................................................................................................ 20
Exercise Thirteen: PHP – If-else Statement .................................................................................................................. 21
Exercise Fourteen: PHP – elseif Statement ................................................................................................................... 22
Exercise Fifteen: PHP – The NULL Value ................................................................................................................... 23
Exercise Sixteen: PHP – The Switch Statement ............................................................................................................ 25
Exercise Seventeen: PHP – The Switch Statement – The Default Case ....................................................................... 26
Exercise Eighteen: PHP – Declaring Functions ............................................................................................................ 27
Exercise Nineteen: PHP – Function Arguments ............................................................................................................ 28
Exercise Twenty: PHP – Function Arguments – Part 2................................................................................................. 29
Exercise Twenty-One: PHP – Function – Default Argument........................................................................................ 30
Exercise Twenty-Two: PHP – Function – Return ......................................................................................................... 31
Exercise Twenty-Three: PHP – The While Loop Statement ......................................................................................... 32
Exercise Twenty-Four: PHP – Do-While-Loop Statement ........................................................................................... 33
Exercise Twenty-Five: PHP – For-Loop Statement ...................................................................................................... 34
Exercise Twenty-Six: PHP – The Foreach-Loop Statement ......................................................................................... 35
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
2
Exercise Twenty-Seven: PHP – The Array Function: Indexed Arrays ......................................................................... 36
Exercise Twenty-Eight: PHP – The Array Function: Using Count ............................................................................... 37
Exercise Twenty-Nine: PHP – The Array Function: For-Loop Statement .................................................................... 38
Exercise Thirty: PHP – The Array Function: Associative ............................................................................................. 39
Exercise Thirty-One: PHP – The Array Function: Associative and Loop .................................................................... 40
Exercise Thirty-Two: PHP – Sorting Arrays – Ascending Order: Words ..................................................................... 41
Exercise Thirty-Three: PHP – Sorting Arrays – Ascending Order: Numbers ............................................................... 42
Exercise Thirty-Four: PHP – Sorting Arrays – Descending Order: Words ................................................................... 43
Exercise Thirty-Five: PHP – Sorting Arrays – Descending Order: Numbers ............................................................... 44
Exercise Thirty-Six: PHP – Sorting Arrays: The asort Function................................................................................... 45
Exercise Thirty-Seven: PHP – Sorting Arrays: The ksort Function .............................................................................. 46
Exercise Thirty-Eight: PHP – Sorting Arrays: The arsort Function .............................................................................. 47
Exercise Thirty-Nine: PHP – Sorting Arrays: The krsort Function ............................................................................... 48
Exercise Forty: PHP – Define Function and Constants ................................................................................................. 49
Exercise Forty-One: PHP – Arithmetic Operators – Adding ........................................................................................ 50
Exercise Forty-Two: PHP – Arithmetic Operators – Subtracting ................................................................................. 50
Exercise Forty-Three: PHP – Arithmetic Operators – Multiplying ............................................................................... 51
Exercise Forty-Four: PHP – Arithmetic Operators – Dividing ..................................................................................... 51
Exercise Forty-Five: PHP – Arithmetic Operators – Remainder .................................................................................. 52
Exercise Forty-Six: PHP – Assignment Operators – The Equal Sign ........................................................................... 52
Exercise Forty-Seven: PHP – Assignment Operators – Addition ................................................................................. 53
Exercise Forty-Eight: PHP – Assignment Operators – Subtraction .............................................................................. 53
Exercise Forty-Nine: PHP – Assignment Operators – Multiplication ........................................................................... 54
Exercise Fifty: PHP – Assignment Operators – Division .............................................................................................. 54
Exercise Fifty-One: PHP – Assignment Operators – Modulus ..................................................................................... 55
Exercise Fifty-Two: PHP – String Operators – Concatenation ..................................................................................... 55
Exercise Fifty-Three: PHP – String Operators – Concatenation Assignment ............................................................... 56
Exercise Fifty-Four: PHP – Increment Operator – Pre-Increment ................................................................................ 57
Exercise Fifty-Five: PHP – Increment Operator – Post-Increment ............................................................................... 58
Exercise Fifty-Six: PHP – Decrement Operators – Pre-Decrement .............................................................................. 59
Exercise Fifty-Seven: PHP – Decrement Operator – Post-Decrement .......................................................................... 60
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
3
Exercise Fifty-Eight: PHP – Comparison Operator – Equal ......................................................................................... 61
Exercise Fifty-Nine: PHP – Comparison Operator – Identical...................................................................................... 62
Exercise Sixty: PHP – Comparison Operator – Not-Equal ........................................................................................... 63
Exercise Sixty-One: PHP – Comparison Operator – Not-Equal – Part 2 ...................................................................... 64
Exercise Sixty-Two: PHP – Comparison Operator – Not-Identical .............................................................................. 65
Exercise Sixty-Three: PHP – Comparison Operator – Greater-Than ............................................................................ 66
Exercise Sixty-Four: PHP – Comparison Operator – Less-Than .................................................................................. 67
Exercise Sixty-Five: PHP – Greater Than or Equal to Operator ................................................................................... 68
Exercise Sixty-Six: PHP – Less Than or Equal to Operator .......................................................................................... 69
Exercise Sixty-Seven: PHP – The And Logical Operators............................................................................................ 70
Exercise Sixty-Eight: PHP – The Or Logical Operators ............................................................................................... 71
Exercise Sixty-Nine: PHP – The Xor Logical Operators .............................................................................................. 72
Exercise Seventy: PHP – The And Logical Operators – Method 2 ............................................................................... 73
Exercise Seventy-One: PHP – The Or Logical Operators – Method 2 ......................................................................... 74
Exercise Seventy-Two: PHP – The Not Logical Operators .......................................................................................... 75
Exercise Seventy-Three: PHP – The Union Array Operator ......................................................................................... 76
Exercise Seventy-Four: PHP – The Equality Array Operators ...................................................................................... 77
Exercise Seventy-Five: PHP – The Identity Array Operators ....................................................................................... 79
Exercise Seventy-Six: PHP – The Inequality Array Operators ..................................................................................... 81
Exercise Seventy-Seven: PHP – The Non-Identity Array Operators ............................................................................ 83
Exercise Seventy-Eight: PHP – The $_SERVER Superglobal Variable P1 ................................................................. 85
Exercise Seventy-Nine: PHP – The $_SERVER Superglobal Variable – P2 ............................................................... 87
Exercise Eighty: PHP – The $_SERVER Superglobal Variable – P3 ........................................................................... 89
Exercise Eighty-One: PHP – The $_SERVER Superglobal Variable – P4 ................................................................... 90
Exercise Eighty-Two: PHP – Multidimensional Arrays – 2D-Array ............................................................................ 92
Exercise Eighty-Three: PHP – Multidimensional Arrays – 3D-Array .......................................................................... 94
Exercise Eighty-Four: PHP – Printing Date and Time .................................................................................................. 95
Exercise Eighty-Five: PHP – Printing Date and Time – Part 2 ..................................................................................... 97
Exercise Eighty-Six: PHP – Printing Date and Time – Time-zone ............................................................................... 98
Exercise Eighty-Seven: PHP – Date and Time – The mktime Function ....................................................................... 99
Exercise Eighty-Eight: PHP – Date and Time – The strtotime Function ...................................................................... 99
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
4
Exercise Eighty-Nine: PHP – The strtotime Function – Future Time ......................................................................... 100
Exercise Ninety: PHP – The Include Statement .......................................................................................................... 101
Exercise Ninety-One: PHP – The Require Statement ................................................................................................. 103
Exercise Ninety-Two: PHP – The Readfile Function .................................................................................................. 104
Exercise Ninety-Three: PHP – The Fopen Function ................................................................................................... 105
Exercise Ninety-Four: PHP – The Fopen Function – Creating a File ......................................................................... 106
Exercise Ninety-Five: PHP – The fwrite Function ...................................................................................................... 107
Exercise Ninety-Six: PHP – The Fget Function .......................................................................................................... 108
Exercise Ninety-Seven: PHP – The feof Function ...................................................................................................... 109
Exercise Ninety-Eight: PHP – The fgetc Function ...................................................................................................... 110
Exercise Ninety-Nine: PHP – Creating a Cookie ........................................................................................................ 111
Exercise 100: PHP – Retrieving the Value of a Cookie .............................................................................................. 112
Exercise 101: PHP – Printing all your Cookies ........................................................................................................... 112
Exercise 102: PHP – Cookies in your PC .................................................................................................................... 113
Exercise 103: PHP – Deleting a Cookie ...................................................................................................................... 113
Exercise 104: PHP – The $_SESSION Superglobal Variable ..................................................................................... 114
An HTML Review ...................................................................................................................................................... 115
An HTML Review: Exercise I: Creating an HTML Document .................................................................................. 115
An HTML Review: Exercise II: Heading Size ............................................................................................................ 117
An HTML Review: Exercise III: HTML Links........................................................................................................... 118
An HTML Review: Exercise IV: HTML Images ........................................................................................................ 118
An HTML Review: Exercise V: HTML – Elements and Lines .................................................................................. 119
An HTML Review: Exercise VI: HTML – The Title Element ................................................................................... 120
An HTML Review: Exercise VII: HTML – Text Formatting ..................................................................................... 120
An HTML Review: Exercise VIII: Comments ............................................................................................................ 122
An HTML Review: Exercise IX: The Title Attribute.................................................................................................. 123
An HTML Review: Exercise X: The Size Attribute.................................................................................................... 124
An HTML Review: Exercise XI: The Alt Attribute .................................................................................................... 124
An HTML Review: Exercise XII: HTML and CSS .................................................................................................... 125
An HTML Review: Exercise XIII: HTML and Links – Part 1 ................................................................................... 128
An HTML Review: Exercise XIV: HTML and Links – Part 2 ................................................................................... 131
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
5
An HTML Review: Exercise XV: HTML Images – The Map Element ..................................................................... 133
An HTML Review: Exercise XVI: HTML Tables ...................................................................................................... 136
An HTML Review: Exercise XVII: HTML Tables & CSS ........................................................................................ 138
An HTML Review: Exercise XVIII: HTML Lists ...................................................................................................... 145
An HTML Review: Exercise XIX: Ordered HTML Lists ........................................................................................... 147
An HTML Review: Exercise XX: HTML Description Lists ...................................................................................... 150
An HTML Review: Exercise XXI: An HTML Nested List ........................................................................................ 151
An HTML Review: Exercise XXII: HTML Blocks .................................................................................................... 152
An HTML Review: Exercise XXIII: HTML Blocks and Classes ............................................................................... 153
An HTML Review: Exercise XXIV: HTML Layouts ................................................................................................. 154
An HTML Review: Exercise XXV: HTML Forms ..................................................................................................... 157
PHP Forms ................................................................................................................................................................. 159
Exercise 105: PHP Forms – Sending Data through $_POST ...................................................................................... 159
Exercise 106: PHP Forms – Sending Data through $_GET ........................................................................................ 161
Exercise 107: PHP Forms – The PHP_SELF Parameter ............................................................................................. 163
Exercise 108: PHP Forms – A Simple PHP Form ....................................................................................................... 164
Exercise 109: PHP Forms – A Simple PHP Form – Part 2 ......................................................................................... 166
Socket Programming ................................................................................................................................................. 168
Exercise 110: PHP – Socket Programming – Client and Server ................................................................................. 168
Hacking Tools ............................................................................................................................................................. 172
Exercise 111: PHP – Hacking Tools: Port Checker .................................................................................................... 172
Exercise 112: PHP – Hacking Tools: Port Scanner ..................................................................................................... 173
Exercise 113: PHP – Hacking Tools: HTTP Checker ................................................................................................. 174
MySQL ........................................................................................................................................................................ 175
Exercise 114: MySQL – An Introduction to the MySQL Commands ........................................................................ 175
Exercise 115: MySQL – The CREATE TABLE Statement ........................................................................................ 177
Exercise 116: MySQL – The INSERT INTO Statement ............................................................................................. 179
Exercise 117: MySQL – The DESCRIBE Statement .................................................................................................. 181
Exercise 118: MySQL – The WHERE Clause ............................................................................................................ 182
Exercise 119: MySQL – The ORDER BY Command ................................................................................................ 184
Exercise 120: MySQL – The UPDATE Statement ..................................................................................................... 185
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
6
Exercise 121: MySQL – The DELETE Statement ...................................................................................................... 187
Exercise 122: MySQL – The AUTO_INCREMENT Attribute .................................................................................. 189
PHP & MySQL .......................................................................................................................................................... 191
Exercise 123: PHP & MySQL – The mysqli_connect Function ................................................................................. 191
Exercise 124: PHP & MySQL – The mysqli_close Function ..................................................................................... 193
Exercise 125: PHP & MySQL – The CREATE DATABASE Statement ................................................................... 194
Exercise 126: PHP & MySQL – The CREATE TABLE Statement ........................................................................... 196
Exercise 127: PHP & MySQL – The INSERT INTO Statement ................................................................................ 198
Exercise 128: PHP & MySQL – The SELECT Statement .......................................................................................... 200
Exercise 129: PHP & MySQL – The WHERE Clause ................................................................................................ 202
Exercise 130: PHP & MySQL – The ORDER BY Command .................................................................................... 203
Exercise 131: PHP & MySQL – The UPDATE Statement ......................................................................................... 204
Exercise 132: PHP & MySQL – The DELETE Statement .......................................................................................... 205
Exercise 133: PHP & MySQL – The MYSQL_NUM_ROWS Function .................................................................... 206
Exercise 134: PHP & MySQL – The MYSQL_FETCH_ARRAY Function .............................................................. 208
A JavaScript Review .................................................................................................................................................. 211
JavaScript – Exercise I: Changing the Content of an HTML Element ........................................................................ 211
JavaScript – Exercise II: Changing the Value of an HTML Attribute ........................................................................ 213
JavaScript – Exercise III: Changing the Style of an HTML Element ......................................................................... 215
JavaScript – Exercise IV: Declaring Variables ............................................................................................................ 217
JavaScript – Exercise V: JavaScript Arrays ................................................................................................................ 218
JavaScript – Exercise VI: JavaScript Objects .............................................................................................................. 219
JavaScript – Exercise VII: JavaScript Function .......................................................................................................... 220
JavaScript – Exercise VIII: Functions and Variable Scope ......................................................................................... 222
JavaScript – Exercise IX: Variables and Arithmetic Operators .................................................................................. 224
JavaScript – Exercise X: The Date Object................................................................................................................... 226
JavaScript – Exercise XI: The Date-Get-Methods of JavaScript ................................................................................ 228
JavaScript – Exercise XII: The Date-Set-Methods of JavaScript ................................................................................ 231
JavaScript – Exercise XIII: Conditional Operator – The If Statement ........................................................................ 237
JavaScript – Exercise XIV: Conditional Operator – The else Statement .................................................................... 238
JavaScript – Exercise XV: Conditional Operator – The else-if Statement .................................................................. 240
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
7
JavaScript – Exercise XVI: The Switch Statement ..................................................................................................... 242
JavaScript – Exercise XVII: Comparison Operators ................................................................................................... 244
JavaScript – Exercise XVIII: The For-Loop Statement............................................................................................... 253
JavaScript – Exercise XIX: The Math Object ............................................................................................................. 256
JavaScript – Exercise XX: An Introduction to JQuery ................................................................................................ 269
JavaScript – Exercise XXI: JQuery – Mouse Events .................................................................................................. 271
JavaScript – Exercise XXII: JQuery – The hover Method .......................................................................................... 272
JavaScript – Exercise XXIII: JQuery – Focus & Blur ................................................................................................. 274
JavaScript – Exercise XXIV: JQuery – The toggle Method ........................................................................................ 276
An XML Review......................................................................................................................................................... 278
An XML Review: Exercise I: The XMLHttpRequest Object ..................................................................................... 281
An XML Review: Exercise II: Loading an XML Document ...................................................................................... 288
An XML Review: Exercise III: Loading an XML String ............................................................................................ 289
An XML Review: Exercise IV: The LoadXMLDoc Function .................................................................................... 290
An XML Review: Exercise V: Gaining Access to Nodes ........................................................................................... 292
An XML Review: Exercise VI: NodeName & NodeType .......................................................................................... 294
An XML Review: Exercise VII: Using Loop and Length ........................................................................................... 296
An XML Review: Exercise VIII: Node Navigation Commands ................................................................................. 298
An XML Review: Exercise IX: Changing Nodes ....................................................................................................... 301
PHP Projects .............................................................................................................................................................. 304
Exercise 135: PHP Projects: A Webcam Project v.1 ................................................................................................... 304
Exercise 136: PHP Projects: A Webcam Project v.2 ................................................................................................... 311
Exercise 137: PHP Projects: Creating a Login System v.1 ......................................................................................... 315
Exercise 138: PHP Projects: Creating a Login System v.2 ......................................................................................... 318
Exercise 139: PHP Projects: Medical Record Form v.1 .............................................................................................. 323
Exercise 140: PHP Projects: Medical Record Form v.2 .............................................................................................. 327
Conclusion .................................................................................................................................................................. 333
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
8
INTRODUCTION
Why should you learn about PHP and MySQL? Learning about PHP and MySQL is very important to start
developing a great variety of web-applications, such as blogs, forums, chats, security tools, port scanners, and more.
Furthermore, if you are interested in the field of computer security, you should learn about PHP and MySQL because
there are a great variety of web-applications with vulnerabilities or security flaws, including stores and banks.
In the Easiest Way to Learn PHP and MySQL, a newbie in the field of computer programming can start
learning about PHP and MySQL from zero. However, the only requirement to start learning about web-development
through this PDF is knowing how to install PHP and MySQL on your computer; then, you can start learning about
computer programming and databases thanks to this tutorial.
The Easiest Way to Learn PHP and MySQL has more than one hundred exercises; therefore, in this tutorial,
you will find more than one hundred source codes and outputs. What is a source code? When you are developing a
computer application, you have to type some codes that are known as the source code of your application. What is an
output? After running a computer application, you will notice a result or effect that is known as the output of an
application.
What kind of exercises and applications will you find in The Easiest Way to Learn PHP and MySQL? In this
tutorial, you are going to find a great variety of exercises and computer applications:
• First, you will find basic information about PHP, such as variables, statements, operators, and basic functions.
• Second, because an individual can use PHP with other languages, you will find a review about HTML,
JavaScript, and XML. In those reviews, you will also learn about CSS, JQuery, and Ajax.
• Third, you will find some exercises and applications about socket programming; therefore, you are going to learn
how to develop a client and a server.
• Fourth, you will find some exercises and tools about hacking, including a port scanner and an HTTP checker.
• Finally, you are going to find some exercises and computer programs about different kinds of PHP projects,
including some exercises and applications about webcams, login systems, and patient record forms.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
9
BASIC CONCEPTS
Before starting with the first exercise, I am going to explain some basic concepts about computer
programming and information technology:
• PHP: PHP is a computer programming language that an individual can use to develop different kinds of
programs; for instance, a coder can use PHP to develop forums, chats, weblogs, port-scanners, security tools, and
many other web-applications. One of the most interesting points that you should know about PHP is that this
computer programming language is free; furthermore, PHP is an open-source software (OSS), which means that
you can see its source code.
• MySQL: MySQL is a database management system that an individual can use with PHP to store and retrieve
information.
• Interpreter: An interpreter is a computer program that can be used to read line by line different kinds of codes and
execute some instructions. As you can see, those are some of the most popular interpreters: PHP, Python, and
Perl.
• Compiler: A compiler is a computer program that can be used to convert some codes into an executable file, also
known as .exe. Sometimes, when you are developing an application, you have to convert your source code into an
executable file; in those cases, you can use a compiler like C/C++ to convert your source code into an executable.
• Source Code: When you are developing a computer program, you have to type different kinds of codes that are
going to be interpreted/compiled to execute a function or task; basically, those codes and commands that you are
typing to create your computer program are the source code of your application.
• Input: The input is one of those places that a coder can use to include or put different kinds of codes before
compiling/interpreting a computer program.
• Output: After developing a computer application or typing a source code, a coder can use a compiler or interpreter
to see the result of his/her program; basically, the result of a computer program is known as the output.
• Script: In computer programming, a script is a sequence or group of codes, characters, and/or commands.
Furthermore, an interpreter like PHP can read a script to execute a function, such as adding some numbers or
scanning some ports.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
10
Exercise One: PHP – Printing Text
Theory:
• The Opening Tag: When an individual or coder wants to start developing a PHP application, he/she has to use the
<?php opening tag because the <?php opening tag is going to tell to a PHP-interpreter to start reading a source
code or script developed on PHP. In addition to the <?php opening tag, an individual can use other opening tags
when he/she wants to start typing a PHP script; for example, some of the opening tags that a coder can use to start
building a PHP application are known as <?, <%, and <script language=“php”>.
• The Closing Tag: At the end of a PHP application, an individual can use the ?> closing tag to close an application
developed on PHP. The closing tag will tell to a PHP-interpreter to stop reading or interpreting a PHP script. Not
only does a coder can use the ?> closing tag, but also an individual can use other closing tags; for example, a
coder can use the %> closing tag when he/she wants to close an application developed on PHP.
• The Print Statement: A coder can use the print statement to build an application that is going to show or print a
message through a browser; in other words, a coder can use the print statement to display text or information
inside of a browser. First, an individual has to type the print keyword. Then, a coder has to type a message inside
of some parenthesis. Finally, a PHP developer has to type a semicolon at the end of his/her statement.
• The Double Slash (//): A coder can use the double slash to type a message or comment that will not be interpreted
by a PHP-interpreter. In other words, an individual can use the double slash when he/she wants to leave some
information related to his/her source code; for example, a coder may leave some notes related to one of the
commands, functions, or statements that he/she is using inside of a source code.
Practice:
<?php print "The Easiest Way To Learn PHP & MySQL by Alvaro J. Gene (Socket_0x03)"; // I am typing a note =)
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
11
Exercise Two: PHP – A Second Method to Print Text Theory: • The Echo Statement: Not only does a coder can use the print statement, but also a coder can use the echo
statement when he/she wants to print or show some information inside of a browser. To put it another way, the
print statement is similar to the echo statement because an individual or coder can use both statements when
he/she wants to display text through a browser.
Practice:
<?php echo "The Easiest Way To Learn PHP & MySQL by Alvaro J. Gene (Socket_0x03)"; ?>
Result:
Exercise Three: PHP – A Line Break
Theory:
• A Line Break: Sometimes, when a coder is using PHP to develop an application, he/she has to insert a line break;
to put it another way, sometimes, a coder has to move to the next line when he/she is using some commands like
print or echo. In this case, I am going to use PHP and HTML to insert a line break.
Practice:
<?php print "This is the first line.". "<br>"; print "This is the second line."; ?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
12
Exercise Four: PHP – Declaring Variables Theory:
• Variable: You can use the PHP variables to store and retrieve information; more specifically, you can use the PHP
variables to store information or data inside of a container that is known as zval, and you can also use the PHP
variables to retrieve or show information inside of the navigator of an individual. When you want to declare a
variable, you can use the dollar sign ($). As you can see, those are some of the most common variables that you
can store and retrieve when you are using PHP:
o Integers: An integer is a whole number; in other words, an integer is a number without a point. As you can see,
this is an example of an integer: 23.
o Floating-Point Numbers: Also known as doubles. Doubles are numbers with a point or decimal values. As you
can see, this is an example of a floating-point number: 5.20
o String: A string is a group or sequence of characters; in other words, a string is a sequence or group of letters,
words, digits, symbols, and/or punctuation marks. As you can see, this is an example of a string: The Easiest Way
to Learn PHP & MySQL by Alvaro J. Gene (Socket_0x03).
Practice:
<?php $Teraexe_Integer_Variable = 23; //Notice that I am not using quotes. $Teraexe_Double_Variable = 5.21; $Teraexe_String_Variable = "The Easiest Way to Learn PHP & MySQL"; //Now, I am using quotes. echo "As you can see, this is an integer variable: "; print ($Teraexe_Integer_Variable) . "<br>"; //In this case, I am using a code to insert a line break. echo "As you can see, this is a double variable: "; print ($Teraexe_Double_Variable) . "<br>"; //In this case, I am inserting a line break. echo "As you can see, this is a string variable: "; print ($Teraexe_String_Variable); //In this case, I am not inserting a line break. ?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
13
Exercise Five: PHP – Declaring Variables – Method Two
• In the next exercise, you will see a method that a coder can use to print text and variables without using a lot of
codes. Furthermore, you will notice that a coder can use a point (.) to print different kinds of variables and text in
only one line when he/she is using the print function.
Practice:
<?php $a = 5; $b = 10; print ("First variable: " . $a . "<br>" . "Second Variable: " . $b); ?>
Result:
Exercise Six: PHP – Information about Server
Theory: • The phpinfo Function: A coder can use the phpinfo function when he/she wants to print or show information
related to his/her PHP configuration. After using this command, a coder will see some information like his/her
PHP version.
Practice:
<?php phpinfo(); ?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
14
Exercise Seven: PHP – Declaring Variables – Variable Scope Theory: • Variable Scope: The location or area of a variable is called variable scope. Some of the most important variable
scopes that a coder can use when he/she is programming in PHP are known as local and global. On the one hand,
a local scope variable is one of those variables that a coder has been defined and used inside of a function; on the
other hand, a global scope variable is one of those variables that a coder has been defined and used outside of a
function. In the first exercise, I am going to develop a computer application with a global scope variable; then, in
the second exercise, I will develop an application with a local scope variable.
Practice – First Exercise: <?php $Teraexe_A = 23; // A Global Scope Variable print $Teraexe_A; ?> Result – First Exercise:
Practice – Second Exercise: <?php function Teraexe() { $Teraexe_A = 23; // A Local Scope Variable print $Teraexe_A; } Teraexe(); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
15
Exercise Eight: PHP – Variable Scope – The Global Keyword Theory:
• The Global Keyword: One of the most important points that a coder should know about global/local variables is
that a programmer cannot access to a global variable when he/she is coding inside of a function unless he/she is
using the global keyword. Therefore, when a coder wants to use a global variable inside of a function, he/she has
to use the global keyword. In the first exercise, the computer application will not print anything because I am not
using the global keyword to access to a global variable; then, in the second exercise, the computer application will
print 12 because I am using the global keyboard to access to a global variable.
Practice – First Exercise: <?php $Gene_Variable=12; function Teraexe() { print $Gene_Variable; } Teraexe(); ?>
Result – First Exercise:
Practice – Second Exercise:
<?php $Gene_Variable=12; function Teraexe() { global $Gene_Variable; print $Gene_Variable; } Teraexe(); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
16
Exercise Nine: PHP – Variable Scope – The Global Keyword – Part 2 Theory: • The GLOBALS[index]: When an individual is coding inside of a function, he/she can use the GLOBALS[index]
to store different kinds of variables; then, he/she can print the values of those variables outside of a function. One
of the advantages of the GLOBALS[index] is that a programmer can start using the values of some variables at
the beginning of an application, then, he/she can update some variables and use other values. In the next exercise,
the Gene_B variable has a value of 12 at the beginning of the application; then, the Gene_B variable has a value
of 23 at the end of the application.
Practice – First Exercise: <?php $Gene_A = 11; $Gene_B = 12; function Teraexe() { $GLOBALS['Gene_B'] = $GLOBALS['Gene_A'] + $GLOBALS['Gene_B']; } Teraexe(); print $Gene_B; ?> Result – First Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
17
Exercise Ten: PHP – Variables – The Static Keyword Theory: • The Static Keyboard: When a function is executed, a local scope variable loses its final value if a coder does not
use the static keyword. In the first exercise, the computer application will print 3 three times because there is not a
static keyword and the local scope variable does not lose its final value; on the other hand, in the second exercise,
the computer application will print 3, 4, and 5 because there is a static keyword and the local scope variable does
not lose its final value.
Practice – First Exercise: <?php function Teraexe() { $Gene_A = 3; print $Gene_A; $Gene_A++; } Teraexe(); print "<br>"; Teraexe(); print "<br>"; Teraexe(); print "<br>"; ?> Result – First Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
18
Practice – Second Exercise: <?php
function Teraexe()
{
static $Gene_A = 3;
print $Gene_A;
$Gene_A++;
}
Teraexe();
print "<br>";
Teraexe();
print "<br>";
Teraexe();
print "<br>";
?>
Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
19
Exercise Eleven: PHP – Booleans Theory: • Booleans: There are only two Boolean values. On the one hand, a Boolean value can be true; on the other hand, a
Boolean value can be false. The Boolean values can be used with some statements, such as the if-statement or if-
else statement. In the next exercise, you will notice that a true value will print one (1); moreover, you are going to
notice that a false value will not print anything.
Practice: <?php
$true_value = true;
$false_value = false;
print ($true_value);
print ($false_value);
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
20
Exercise Twelve: PHP – If Statement Theory: • If Statement: If something is true, the application will print an instruction. In the next example, if the variable
my_name is Socket_0x03, the application will print Hello Socket_0x03.
o As you can see, this is the syntax of the if-statement:
If (condition)
{
//A Code will be executed if a condition is true
}
Practice: <?php
$my_name = "Socket_0x03";
if ( $my_name == "Socket_0x03" )
{
print "Hello Socket_0x03";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
21
Exercise Thirteen: PHP – If-else Statement Theory: • If-else Statement: If something is true, the application will print an instruction; however, if something is not true,
the application will print other instruction. In the next example, the application will print Hello User because the
variable my_name is different than Socket_0x03.
a) As you can see, this is the syntax of the if-else statement:
If (condition) {
//A Code will be executed if a condition is true } Else {
//A Code will be executed if a condition is not true }
Practice: <?php $my_name = "Socket_0x03"; if ( $my_name == "Other_than_Socket_0x03" ) { print "Hello Socket_0x03"; } else { print "Hello User"; } ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
22
Exercise Fourteen: PHP – elseif Statement Theory: • elseif Statement: If something is true, the application will print an instruction through the if-statement. However,
if something is not true, the computer application will use the elseif-statement to check a condition; then, if
something is true, the elseif-statement will print an instruction. On the other hand, if something is not true, the
computer application will continue checking through different kinds of elseif-statement, or it may continue
checking through a final else-statement. One of the best ways to understand the functionality of the elseif
statement is seeing an example or a source code; therefore, I am going to provide an example of the elseif
statement in the next source code.
Practice:
<?php $Teraexe_Members = "Moderator"; if ($Teraexe_Members == "Admin") { print "Hello Admin"; } elseif ($Teraexe_Members == "User") { print "Hello User"; } elseif ($Teraexe_Members == "Moderator") { print "Hello Moderator"; } else { print "Hello Guest"; } ?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
23
Exercise Fifteen: PHP – The NULL Value Theory: • The NULL Value: Also known as the unknown value. If you assign the value of NULL to one of your variables,
this variable will not have any kind of value. One of the most interesting points that you should know about the
NULL value is that the NULL value is not case sensitive, which means that you can use NULL or null when you
are developing a computer application in PHP. When can you use the NULL value? You can use the unknown
value in a scenario similar to this:
a) You are modifying the source code of a computer application.
b) You want to test your computer program without the behavior of a variable; in other words, you want to
run your program without the functionality of a variable.
c) In this case, you have to change the value of that variable to NULL; then, you can compile and run your
application with the absence of that variable.
In addition to that scenario, you can also use the NULL character when some unnecessary variables are using
a lot of memory in a computer.
Practice – Part One:
As you can see, this is a program with two variables; in this case, there is not a NULL character:
<?php $Teraexe_Variable_A = 1; $Teraexe_Variable_B = 2; print($Teraexe_Variable_A); print($Teraexe_Variable_B); ?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
24
Result – Part One:
Practice – Part Two:
As you can see, this is the previous application; however, in this case, there is a NULL character:
<?php
$Teraexe_Variable_A = NULL;
$Teraexe_Variable_B = 2;
print($Teraexe_Variable_A);
print($Teraexe_Variable_B);
?>
Result – Part One:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
25
Exercise Sixteen: PHP – The Switch Statement Theory: • The Switch Statement: A coder can use the switch statement when he/she wants to develop a computer
application that can be used to choose different kinds of alternatives or options.
Practice: <?php
$Teraexe_Product = "Laptop";
print "Choose a Product: ";
switch ($Teraexe_Product)
{
case "Pendrive":
print "Pendrive: $80";
break;
case "Desktop":
print "Desktop: $500";
break;
case "Laptop":
print "Laptop: $300";
break;
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
26
Exercise Seventeen: PHP – The Switch Statement – The Default Case Theory: • The Default case: A coder can use the default case when a variable does not match with any condition or case. In
the next example, the variable Keyboard does not match with any case; therefore, you are going to see the
message: This variable does not match with any case…
Practice: <?php
$Teraexe_Product = "Keyboard";
switch ($Teraexe_Product)
{
case "Pendrive":
print "Pendrive: $80";
break;
case "Desktop":
print "Desktop: $500";
break;
case "Laptop":
print "Laptop: $300";
break;
default:
print "This variable does not match with any case...";
break;
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
27
Exercise Eighteen: PHP – Declaring Functions Theory:
• Declaring Functions: If you want to declare different kinds of functions, you can use a command that is known as
function. As you can see, this is the syntax of the function:
function Name_of_a_function()
{
The codes of a function; those codes will be executed if this function is called…
}
After declaring a function, a coder has to type the name of that function when he/she wants to start using its
codes. When a coder is calling a function, he/she has to include two parentheses after the name of that function.
Furthermore, when a coder is typing the name of a function, he/she cannot start with a number; therefore, a
programmer who is typing the name of a function has to start with a letter or an underscore (_). In addition, one of
the most important points that a coder should know about the name of a function is that its name is not case-
sensitive, so a programmer has to pay close attention to the uppercase and lowercase letters.
Practice: <?php function Teraexe_Function() //Here, we are typing the name of a function. { print "The function of the Teraexe_Function is to show this message."; } Teraexe_Function(); //Here, we are calling the function Teraexe_Function. ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
28
Exercise Nineteen: PHP – Function Arguments Theory:
• Function arguments: When a coder is using a function, he/she can include different kinds of arguments inside of
the function. After typing the name of a function, a coder can type an argument that is going to be similar to a
variable.
Practice:
<?php
function Teraexe_Tools($Tool_Names)
{
print "Teraexe Tool: $Tool_Names" . "<br>" ;
}
Teraexe_Tools("Network Traffic Monitor");
Teraexe_Tools("Trojan");
Teraexe_Tools("Keylogger");
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
29
Exercise Twenty: PHP – Function Arguments – Part 2 Theory:
• Function arguments: When a coder is using a function, he/she can include different kinds of arguments inside of
the function. In the next exercise, you are going to see the function command with two arguments.
Practice: <?php
function Teraexe_Tools($Tool_Names, $Realese_Day)
{
print "Teraexe Tool: $Tool_Names" . "<br>" ;
print "Release: $Realese_Day" . "<br><br>" ;
}
Teraexe_Tools("Network Traffic Monitor.", "January 29, 2009.");
Teraexe_Tools("Trojan.", "May 20, 2010.");
Teraexe_Tools("Keylogger.", "November 5, 2008.");
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
30
Exercise Twenty-One: PHP – Function – Default Argument Theory:
• Default Argument: When a coder is declaring an argument, he/she can declare a default argument…
Practice: <?php
function Teraexe_Tools($Tool_Names=Nothing) //The default argument for Tool_Names will be Nothing…
{
print "Teraexe Tool: $Tool_Names" . "<br>" ;
}
Teraexe_Tools("Network Traffic Monitor");
Teraexe_Tools(); //This command will print the default argument, which is Nothing…
Teraexe_Tools("Keylogger");
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
31
Exercise Twenty-Two: PHP – Function – Return Theory:
• Return: While a coder is using a command that is known as function, he/she can also use return when he/she
wants to return different kinds of values.
Practice: <?php
function Teraexe_Adding_Numbers($a,$b)
{
$c=$a+$b;
return $c;
}
print "5 + 5 = " . Teraexe_Adding_Numbers(5,5);
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
32
Exercise Twenty-Three: PHP – The While Loop Statement Theory: • The While Loop: A coder can use the while-loop statement when he/she wants to test a condition and execute
some codes. The while-loop statement can be used to check if a condition is true; then, if a condition is true, the
while-loop will execute some codes. As you can see, this is the syntax of the while loop statement:
While (if a condition is true, the while-loop will execute some codes)
{
The codes that a while-loop will execute;
}
++: In the next exercise, I am going to use this symbol (++) to increase the value of Teraexe; therefore, the value
of Teraexe will increase by one each time that the while-loop statement is executed.
Practice: <?php $Teraexe = 1; while($Teraexe<=7) //If Teraexe is equal or less than ten, the loop will execute some codes. { print "The value of Teraexe is: $Teraexe" . "<br>"; $Teraexe++; } ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
33
Exercise Twenty-Four: PHP – Do-While-Loop Statement Theory: • The Do-While Loop Statement: A coder can use the do-while-loop statement when he/she wants to execute some
codes and test a condition. First, the do-while-loop statement will execute some codes; then, if a condition is true,
the do-while-loop statement will execute its instructions. As you can see, this is the syntax of the do-while-loop
statement:
do { The codes that a do-while-loop statement will execute; } While (If a condition is true, the do-while-loop statement will execute some codes);
Practice: <?php do { print "The value of Teraexe is: $Teraexe" . "<br>"; $Teraexe++; } while ($Teraexe<=7); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
34
Exercise Twenty-Five: PHP – For-Loop Statement Theory: • The For-Loop Statement: A coder can use the for-loop statement when he/she wants to print a variable several
times. Usually, a programmer who is using the for-loop statement knows how many times he/she is going to print
a variable or run a code. As you can see, this is the syntax of the for-loop statement:
for (first-expression; second-expression; third-expression) { The codes that a for-loop will execute; }
First-expression: In the first expression, a coder may include the initial value of a variable.
Second-expression: In the second expression, a coder may include some codes that will evaluate some
variables/numbers. If a variable or number is true, the loop will continue running or executing its codes; on the
other hand, the loop will end if a variable or number is false.
Third-expression: In the third expression, a programmer may include those kinds of codes that are going to
increase a number or variable.
Practice:
<?php for ($Teraexe=0; $Teraexe<=7; $Teraexe++) { print "The value of Teraexe is: $Teraexe" . "<br>"; } ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
35
Exercise Twenty-Six: PHP – The Foreach-Loop Statement Theory: • The Foreach-Loop Statement: A coder can use the foreach-loop statement when he/she is working with arrays.
What is an array? An array is a sequence/group of objects; in other words, an array is a sequence/group of
numbers, words, or other characters. Usually, when a computer application is going to print an array of words or
numbers, those words or numbers are printed in rows or columns. An array will hold the values of a variable; for
example, the values of software can be firewall, antivirus, and scanner. As you can see, in the next example, I am
using an array to hold the values of Teraexe_Software, which are Trojan, Keylogger, Antivirus, Firewall, and
Port-Scanner; then, I am using the foreach-loop statement to print those values.
Practice:
<?php
$Teraexe_Softwares = array("Trojan","Keylogger","Antivirus","Firewall","Port-Scanner");
//As you can see, I am using the word array to define the values of Teraexe_Softwares; in this case,
//the values of Teraexe_Software are Trojan, Keylogger, Antivirus, Firewall, and Port-Scanner.
foreach ($Teraexe_Softwares as $value)
{
print "$value" . "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
36
Exercise Twenty-Seven: PHP – The Array Function: Indexed Arrays Theory: • The Array Function: As previously mentioned, a coder can use an array to hold the values of a variable. In the
next exercise, an array is holding the values of Gene_Tools, which are Antivirus, Firewall, and Port-Scanner. In
this case, the elements of Gene_Tools are Antivirus, Firewall, and Port-Scanner.
• The Indexed Arrays: When a coder is using indexed arrays, he/she assigns a value to each element; then, a
programmer only has to use numbers when he/she wants to use one of the array elements. For example, in the
next exercise, I am printing the first element of an array (Antivirus) using the number zero (0) after the name of
the variable Gene_Tools.
Practice:
<?php
$Gene_Tools = array("Antivirus","Firewall","Port-Scanner");
print "Teraexe Softwares: " . $Gene_Tools[0] . ", " . $Gene_Tools[1] . ", and " . $Gene_Tools[2] . ".";
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
37
Exercise Twenty-Eight: PHP – The Array Function: Using Count Theory: • The Count() Function: A coder can use the count function when he/she wants to print the number of the array
elements. For example, if an array has three elements, the count function will print the number 3 because there are
three elements inside of an array. In the next exercise, the Gene_Tools variable has three elements, which are
Antivirus, Firewall, and Port-Scanner; therefore, the count function will print three (3) because the array of
Gene_Tools is holding three elements.
Practice:
<?php
$Gene_Tools = array("Antivirus","Firewall","Port-Scanner");
print count($Gene_Tools);
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
38
Exercise Twenty-Nine: PHP – The Array Function: For-Loop Statement Theory: • The array function and the for-loop statement: A programmer can use the array function and the for-loop
statement when he/she wants to print the elements of an array.
Practice:
<?php
$Teraexe_Products = array("Pendrive","Keyboard","Computer");
$Array_Count = count($Teraexe_Products);
for ($a=0; $a<$Array_Count; $a++)
{
print $Teraexe_Products[$a] . "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
39
Exercise Thirty: PHP – The Array Function: Associative Theory: • Associative: When a coder is using the array function, he/she can associate some elements.
Practice:
<?php
$Teraexe_Products = array("Pen"=>"23 dollars.","Keyboard"=>"25 dollars.","PC"=>"30 dollars.");
print "The pendrive cost is: " . $Teraexe_Products['Pen'] . "<br>";
print "The keyboard cost is: " . $Teraexe_Products['Keyboard'] . "<br>";
print "The computer cost is: " . $Teraexe_Products['PC'];
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
40
Exercise Thirty-One: PHP – The Array Function: Associative and Loop Theory: • Associative and foreach-loop statement: When a coder is using the array function, he/she can associate some
elements while he/she is using the foreach-loop statement.
Practice:
<?php
$Teraexe_Products = array("Pendrive"=>"23 dollars.","Keyboard"=>"25 dollars.","PC"=>"300 dollars.");
foreach ($Teraexe_Products as $a=>$product_cost)
{
print "Product Name: " . $a . ", Product Cost: " . $product_cost;
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
41
Exercise Thirty-Two: PHP – Sorting Arrays – Ascending Order: Words Theory: • Sorting Arrays – Ascending Order: A coder can use sort() when he/she wants to organize in ascending order those
kinds of elements that are inside of an array. In the next example, I am going to use sort() to organize three
alphabetic elements, which are Mouse, VR-Glasses, and Keyboard.
Practice: <?php
$Gene_Store = array ("Mouse","VR-Glasses","Keyboard");
sort ($Gene_Store);
$Gene_Store_Length = count ($Gene_Store);
for ($a=0; $a<$Gene_Store_Length; $a++)
{
print $Gene_Store[$a];
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
42
Exercise Thirty-Three: PHP – Sorting Arrays – Ascending Order: Numbers Theory: • Sorting Arrays – Ascending Order: A coder can use sort() when he/she wants to organize in ascending order those
kinds of elements that are inside of an array. In the next example, I am going to use sort() to organize three
numerical elements, which are 1, 2, and 3.
Practice: <?php
$Gene_Numbers = array ("2","3","1");
sort ($Gene_Numbers);
$Gene_Numbers_Length = count ($Gene_Numbers);
for ($a=0; $a<$Gene_Numbers_Length; $a++)
{
print $Gene_Numbers[$a];
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
43
Exercise Thirty-Four: PHP – Sorting Arrays – Descending Order: Words Theory: • Sorting Arrays – Descending Order: A coder can use rsort() when he/she wants to organize in descending order
those kinds of elements that are inside of an array. In the next example, I am going to use rsort() to organize three
alphabetic elements, which are Mouse, VR-Glasses, and Keyboard.
Practice: <?php
$Gene_Store = array ("Mouse","VR-Glasses","Keyboard");
rsort ($Gene_Store);
$Gene_Store_Length = count ($Gene_Store);
for ($a=0; $a<$Gene_Store_Length; $a++)
{
print $Gene_Store[$a];
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
44
Exercise Thirty-Five: PHP – Sorting Arrays – Descending Order: Numbers Theory: • Sorting Arrays – Descending Order: A coder can use rsort() when he/she wants to organize in descending order
those kinds of elements that are inside of an array. In the next example, I am going to use rsort() to organize three
numerical elements, which are 1, 2, and 3.
Practice: <?php
$Gene_Numbers = array ("2","3","1");
rsort ($Gene_Numbers);
$Gene_Numbers_Length = count ($Gene_Numbers);
for ($a=0; $a<$Gene_Numbers_Length; $a++)
{
print $Gene_Numbers[$a];
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
45
Exercise Thirty-Six: PHP – Sorting Arrays: The asort Function Theory: • Sorting Arrays – The asort() Function: A coder can use asort() when he/she wants to organize in ascending order
those kinds of associative elements that are inside of an array. In the next example, I am going to use asort() to
organize three alphabetic elements, which are going to be organized according to their value/cost.
Practice: <?php
$Teraexe_Products = array("Mouse"=>"20 dollars.","VR-Glasses"=>"300 dollars.","Keyboard"=>"19 dollars.");
asort($Teraexe_Products);
foreach ($Teraexe_Products as $a=> $product_cost)
{
print "Product Name: " . $a . ", Product Cost: " . $product_cost;
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
46
Exercise Thirty-Seven: PHP – Sorting Arrays: The ksort Function Theory: • Sorting Arrays – The ksort() Function: A coder can use ksort() when he/she wants to organize in ascending order
those kinds of associative elements that are inside of an array. In the next example, I am going to use ksort() to
organize three alphabetic elements, which are going to be organized according to their letters/key.
Practice: <?php
$Teraexe_Products = array("Mouse"=>"15 dollars.","VR-Glasses"=>"300 dollars.","Keyboard"=>"19 dollars.");
ksort($Teraexe_Products);
foreach ($Teraexe_Products as $a=> $product_cost)
{
print "Product Name: " . $a . ", Product Cost: " . $product_cost;
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
47
Exercise Thirty-Eight: PHP – Sorting Arrays: The arsort Function Theory: • Sorting Arrays – The arsort() Function: A coder can use arsort() when he/she wants to organize in descending
order those kinds of associative elements that are inside of an array. In the next example, I am going to use
arsort() to organize three alphabetic elements, which are going to be organized according to their value/cost.
Practice: <?php
$Teraexe_Products = array("Mouse"=>"15 dollars.","VR-Glasses"=>"300 dollars.","Keyboard"=>"19 dollars.");
arsort($Teraexe_Products);
foreach ($Teraexe_Products as $a=> $product_cost)
{
print "Product Name: " . $a . ", Product Cost: " . $product_cost;
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
48
Exercise Thirty-Nine: PHP – Sorting Arrays: The krsort Function Theory: • Sorting Arrays – The krsort() Function: A coder can use krsort() when he/she wants to organize in descending
order those kinds of associative elements that are inside of an array. In the next example, I am going to use
krsort() to organize three alphabetic elements, which are going to be organized according to their letter/key.
Practice: <?php
$Teraexe_Products = array("Mouse"=>"15 dollars.","VR-Glasses"=>"300 dollars.","Keyboard"=>"19 dollars.");
krsort($Teraexe_Products);
foreach ($Teraexe_Products as $a=> $product_cost)
{
print "Product Name: " . $a . ", Product Cost: " . $product_cost;
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
49
Exercise Forty: PHP – Define Function and Constants
Theory: • Using the define function to set constants: A coder can use the define function when he/she wants to define a
constant. As you can see, this is the syntax of the define function:
define (constant name, constant value, case-sensitive/case-insensitive)
Constant Name: In the first parameter, a coder has to type the name of a constant. A constant name is required,
which means that a coder cannot leave a blank space.
Constant Value: In the second parameter, a programmer has to type the constant value, which is required.
Case-Sensitive/Case-Insensitive: In the third parameter, a coder has to type true if he/she wants a case-insensitive
constant; on the other hand, if a coder does not type anything, he/she will have an application with a case-
sensitive constant.
In the first exercise, I am leaving a blank space because I want to develop an application with a case-sensitive
constant; then, in the second exercise, I am typing true because I want to develop an application with a case-
insensitive constant.
Practice – First Exercise (a case sensitive constant): <?php define ("Teraexe", "Hello Socket_0x03!"); print Teraexe; ?> Practice – Second Exercise (a case insensitive constant): <?php define ("Teraexe", "Hello Socket_0x03!", true); print teraexe; ?> Result – First and Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
50
Exercise Forty-One: PHP – Arithmetic Operators – Adding
Theory: • The Plus Sign (+): The plus sign (+) can be used to add numbers. Practice: <?php $Teraexe_A = 11; $Teraexe_B = 12; $Teraexe_Total = $Teraexe_A + $Teraexe_B; print "Teraexe_A + Teraexe_B = $Teraexe_Total"; ?> Result:
Exercise Forty-Two: PHP – Arithmetic Operators – Subtracting
Theory: • The Minus Sign (-): The minus sign (-) can be used to subtract numbers. Practice: <?php $Teraexe_A = 30; $Teraexe_B = 7; $Teraexe_Total = $Teraexe_A - $Teraexe_B; print "Teraexe_A - Teraexe_B = $Teraexe_Total"; ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
51
Exercise Forty-Three: PHP – Arithmetic Operators – Multiplying
Theory: • The Asterisk Sign (*): The asterisk sign (*) can be used to multiply numbers. Practice: <?php $Teraexe_A = 5; $Teraexe_B = 5; $Teraexe_Total = $Teraexe_A * $Teraexe_B; print "Teraexe_A * Teraexe_B = $Teraexe_Total"; ?> Result:
Exercise Forty-Four: PHP – Arithmetic Operators – Dividing
Theory: • The Slash Sign (/): The slash sign (/) can be used to divide numbers. Practice: <?php $Teraexe_A = 25; $Teraexe_B = 5; $Teraexe_Total = $Teraexe_A / $Teraexe_B; print "Teraexe_A / Teraexe_B = $Teraexe_Total"; ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
52
Exercise Forty-Five: PHP – Arithmetic Operators – Remainder
Theory: • The Percent Sign (%): The percent sign (%) is also known as the modulus. A coder can use the modulus when
he/she wants to obtain the remainder of a division.
Practice: <?php $Teraexe_A = 100; $Teraexe_B = 52; $Teraexe_Total = $Teraexe_A % $Teraexe_B; print "Teraexe_A % Teraexe_B = $Teraexe_Total"; ?> Result:
Exercise Forty-Six: PHP – Assignment Operators – The Equal Sign
Theory: • The Equal Sign (=): A coder can use the equal sign (=) to assign a value to an operator. In the next exercise, I am
assigning the value of one hundred (100) to the left operator, which is Teraexe_A.
Practice: <?php $Teraexe_A = 100; print "Teraexe_A = $Teraexe_A"; ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
53
Exercise Forty-Seven: PHP – Assignment Operators – Addition
Theory: • The Addition Assignment Operator (+=): A coder can use the addition assignment operator (+=) when he/she
wants to add some values to an operator.
Practice: <?php $Teraexe_A = 100; $Teraexe_A += 200; print "Teraexe_A = $Teraexe_A"; ?> Result:
Exercise Forty-Eight: PHP – Assignment Operators – Subtraction
Theory: • The Subtraction Assignment Operator (-=): A coder can use the subtraction assignment operator (-=) when
he/she wants to subtract some values to an operator.
Practice: <?php $Teraexe_A = 300; $Teraexe_A -= 200; print "Teraexe_A = $Teraexe_A"; ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
54
Exercise Forty-Nine: PHP – Assignment Operators – Multiplication
Theory: • The Multiplication Assignment Operator (*=): A coder can use the multiplication assignment operator (*=) when
he/she wants to multiply some values to an operator.
Practice: <?php $Teraexe_A = 23; $Teraexe_A *= 23; print "Teraexe_A = $Teraexe_A"; ?> Result:
Exercise Fifty: PHP – Assignment Operators – Division
Theory: • The Division Assignment Operator (/=): A coder can use the division assignment operator (/=) when he/she wants
to divide some values to an operator.
Practice: <?php $Teraexe_A = 100; $Teraexe_A /= 2; print "Teraexe_A = $Teraexe_A"; ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
55
Exercise Fifty-One: PHP – Assignment Operators – Modulus
Theory: • The Modulus Assignment Operator (%=): A coder can use the modulus assignment operator (%=) when he/she
wants to obtain the remainder of a division.
Practice: <?php $Teraexe_A = 99; $Teraexe_A %= 2; print "Teraexe_A = $Teraexe_A"; ?> Result:
Exercise Fifty-Two: PHP – String Operators – Concatenation
Theory: • The Concatenate String Operator (.): A coder can use the concatenate string operator (.) when he/she wants to
concatenate some characters; in other words, a coder can use the concatenate string operator (.) when he/she
wants to put together a group of words or characters. In the next exercise, the Teraexe_B variable will has a value,
which is I am using the concatenate string operator.
Practice: <?php $Teraexe_A = "I am using the"; $Teraexe_B = $Teraexe_A . " concatenate string operator."; print $Teraexe_B; ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
56
Exercise Fifty-Three: PHP – String Operators – Concatenation Assignment Theory: • The Concatenation Assignment Operator (.=): A coder can use the concatenate assignment operator (.=) when
he/she wants to concatenate some characters; in other words, a coder can use the concatenate assignment
operator (.=) when he/she wants to put together a group of words or characters. In the next exercise, the
Teraexe_A variable will has a value, which is I am using the concatenate string operator.
Practice: <?php
$Teraexe_A = "I am using the";
$Teraexe_A .= " concatenate string operator.";
print $Teraexe_A;
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
57
Exercise Fifty-Four: PHP – Increment Operator – Pre-Increment
Theory: • Increment Operator (++): A coder can use the increment operator (++) when he/she wants to increment a value.
In the next exercise, the application will use a pre-increment operator (++$Teraexe_A) to increment the value of
Teraexe_A by one, then, the application will return the value of Teraexe_A.
Practice: <?php
$Teraexe_A = 1;
print "Teraexe_A = " . ++$Teraexe_A;
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
58
Exercise Fifty-Five: PHP – Increment Operator – Post-Increment
Theory: • Increment Operator (++): A coder can use the increment operator (++) when he/she wants to increment a value.
In the next exercise, the application will use a post-increment operator ($Teraexe_A++) to increment the value of
Teraexe_A by one. Then, the application will return the first value of Teraexe_A; finally, the application will
return the last value of Teraexe_A, which is 2.
Practice: <?php
$Teraexe_A = 1;
print "Teraexe_A, first value = " . $Teraexe_A++ . "<br>";
print "Teraexe_A, second value = " . $Teraexe_A;
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
59
Exercise Fifty-Six: PHP – Decrement Operators – Pre-Decrement
Theory: • Decrement Operator (--): A coder can use the decrement operator (--) when he/she wants to decrement a value. In
the next exercise, the application will use a pre-decrement operator (--$Teraexe_A) to decrement the value of
Teraexe_A by one, then, the application will return the value of Teraexe_A.
Practice: <?php
$Teraexe_A = 1;
print "Teraexe_A = " . --$Teraexe_A;
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
60
Exercise Fifty-Seven: PHP – Decrement Operator – Post-Decrement
Theory: • Decrement Operator (--): A coder can use the decrement operator (--) when he/she wants to decrement a value. In
the next exercise, the application will use a post-decrement operator ($Teraexe_A--) to decrement the value of
Teraexe_A by one. Then, the application will return the first value of Teraexe_A; finally, the application will
return the last value of Teraexe_A, which is 0.
Practice: <?php
$Teraexe_A = 1;
print "Teraexe_A, first value = " . $Teraexe_A-- . "<br>";
print "Teraexe_A, second value = " . $Teraexe_A;
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
61
Exercise Fifty-Eight: PHP – Comparison Operator – Equal
Theory: • The Equal Comparison Operator (==): A coder can use the equal comparison operator (==) when he/she wants to
test if two variables have the same value. After testing a value, the application will print true if both variables
have the same value; on the other hand, the application will print false if both variables have different values. In
the next exercise, the application will use an equal comparison operator (==) to test if two variables have the
same value; as a result, the application will print true because Teraexe_A and Teraexe_B have the same value,
which is 23.
Practice: <?php
$Teraexe_A = 23;
$Teraexe_B = "23";
var_dump($Teraexe_A == $Teraexe_B);
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
62
Exercise Fifty-Nine: PHP – Comparison Operator – Identical
Theory: • The Identical Comparison Operator (===): A coder can use the identical comparison operator (===) when he/she
wants to test if two variables are identical. After testing a variable, the application will print true if both variables
are identical; on the other hand, the application will print false if both variables are different. In the first exercise,
the application will print false because both variables are different; then, in the second exercise, the application
will print true because both variables are identical.
Practice – First Exercise: <?php $Teraexe_A = 23; $Teraexe_B = "23"; var_dump($Teraexe_A === $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A === $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
63
Exercise Sixty: PHP – Comparison Operator – Not-Equal
Theory: • The Not-Equal Comparison Operator (!=): A coder can use the not-equal comparison operator (!=) when he/she
wants to test if the value of two variables are not equal. After testing a variable, the application will print true if
both variables are not-equal; on the other hand, the application will print false if both variables are equal. In the
first exercise, the application will print false because both variables are equal; then, in the second exercise, the
application will print true because both variables are different.
Practice – First Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A != $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 25; var_dump($Teraexe_A != $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
64
Exercise Sixty-One: PHP – Comparison Operator – Not-Equal – Part 2
Theory: • The Not-Equal Comparison Operator (<>): A coder can use the not-equal comparison operator (<>) when he/she
wants to test if the value of two variables are not equal. After testing a variable, the application will print true if
both variables are not-equal; on the other hand, the application will print false if both variables are equal. In the
first exercise, the application will print false because both variables are equal; then, in the second exercise, the
application will print true because both variables are different.
Practice – First Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A <> $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 25; var_dump($Teraexe_A <> $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
65
Exercise Sixty-Two: PHP – Comparison Operator – Not-Identical
Theory: • The Not-Identical Comparison Operator (!==): A coder can use the not-identical comparison operator (!==) when
he/she wants to test if two variables are not identical. After testing a variable, the application will print true if both
variables are not identical; on the other hand, the application will print false if both variables are identical. In the
first exercise, the application will print false because both variables are identical; then, in the second exercise, the
application will print true because both variables are not-identical.
Practice – First Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A !== $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; $Teraexe_B = "23"; var_dump($Teraexe_A !== $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
66
Exercise Sixty-Three: PHP – Comparison Operator – Greater-Than
Theory: • The Greater-Than Comparison Operator (>): A coder can use the greater-than comparison operator (>) when
he/she wants to test if a variable is greater than other variable. After testing a variable, the application will print
true if a variable is greater than other variable; on the other hand, the application will print false if a variable is not
greater than other variable. In the first exercise, the application will print false because a variable is greater than
other variable; then, in the second exercise, the application will print true because a variable is not greater than
other variable.
Practice – First Exercise: <?php $Teraexe_A = 11; $Teraexe_B = 12; var_dump($Teraexe_A > $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 12; $Teraexe_B = 11; var_dump($Teraexe_A > $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
67
Exercise Sixty-Four: PHP – Comparison Operator – Less-Than
Theory: • The Less-Than Comparison Operator (<): A coder can use the less-than comparison operator (<) when he/she
wants to test if a variable is less than other variable. After testing a variable, the application will print true if a
variable is less than other variable; on the other hand, the application will print false if a variable is not less than
other variable. In the first exercise, the application will print false because a variable is not less than other
variable; then, in the second exercise, the application will print true because a variable is less than other variable.
Practice – First Exercise: <?php $Teraexe_A = 12; $Teraexe_B = 11; var_dump($Teraexe_A < $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 11; $Teraexe_B = 12; var_dump($Teraexe_A < $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
68
Exercise Sixty-Five: PHP – Greater Than or Equal to Operator
Theory: • The Greater Than or Equal to Operator (>=): A coder can use the greater than or equal to operator (>=) when
he/she wants to test if a variable is greater than or equal to other variable. After testing a variable, the application
will print true if a variable is greater than or equal to other variable; on the other hand, the application will print
false if a variable is not greater than or equal to other variable. In the first exercise, the application will print false
because a variable is not greater than or equal to other variable; then, in the second exercise, the application will
print true because a variable is greater than or equal to other variable.
Practice – First Exercise: <?php $Teraexe_A = 11; $Teraexe_B = 12; var_dump($Teraexe_A >= $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 12; $Teraexe_B = 11; var_dump($Teraexe_A >= $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
69
Exercise Sixty-Six: PHP – Less Than or Equal to Operator
Theory: • The Less Than or Equal to Operator (<=): A coder can use the less than or equal to operator (<=) when he/she
wants to test if a variable is less than or equal to other variable. After testing a variable, the application will print
true if a variable is less than or equal to other variable; on the other hand, the application will print false if a
variable is not less than or equal to other variable. In the first exercise, the application will print false because a
variable is not less than or equal to other variable; then, in the second exercise, the application will print true
because a variable is less than or equal to other variable.
Practice – First Exercise: <?php $Teraexe_A = 12; $Teraexe_B = 11; var_dump($Teraexe_A <= $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 11; $Teraexe_B = 12; var_dump($Teraexe_A <= $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
70
Exercise Sixty-Seven: PHP – The And Logical Operators
Theory: • The And Logical Operator (and): A coder can use the and logical operator (and) when he/she wants to test if two
variables are true; in other words, a programmer can use the and logical operator (and) when he/she wants to
know or test if a computer application has two variables. After using the and logical operator (and), the
application will print true if both variables exist; on the other hand, the application will print false if there is a
variable that does not exist. In the first exercise, the application will print false because a variable does not exist;
then, in the second exercise, the application will print true because both variables exist.
Practice – First Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A and $Teraexe_C); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A and $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
71
Exercise Sixty-Eight: PHP – The Or Logical Operators
Theory: • The Or Logical Operator (or): A coder can use the or logical operator (or) when he/she wants to test if at least
one of the two variables is true; to put it another way, a programmer can use the or logical operator (or) when
he/she wants to know or test if a computer application has at least one of the two variables that he/she is testing.
After using the or logical operator (or), the application will print true if at least one variable exists; on the other
hand, the application will print false if both variables do not exist. In the first exercise, the application will print
false because both variables do not exist, in other words, the program will print false because both variables are
not true; then, in the second exercise, the application will print true because at least one of the two variables is
true.
Practice – First Exercise:
<?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_C or $Teraexe_D); ?> Result – First Exercise:
Practice – Second Exercise:
<?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A or $Teraexe_D); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
72
Exercise Sixty-Nine: PHP – The Xor Logical Operators
Theory: • The Xor Logical Operator (xor): A coder can use the xor logical operator (xor) when he/she wants to test if only
one variables is true, but not both; to put it another way, a programmer can use the xor logical operator (xor)
when he/she wants to know or test if a computer application has only one variable, but not both variables. After
using the xor logical operator (xor), the application will print true if only one variable exists; on the other hand,
the application will print false if both variables exist. In the first exercise, the application will print false because
both variables exist, in other words, the program will print false because both variables are true; then, in the
second exercise, the application will print true because only one variable exists.
Practice – First Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A xor $Teraexe_B); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A xor $Teraexe_C); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
73
Exercise Seventy: PHP – The And Logical Operators – Method 2
Theory: • The And Logical Operator (&&): A coder can use the and logical operator (&&) when he/she wants to test if two
variables are true; in other words, a programmer can use the and logical operator (&&) when he/she wants to
know or test if a computer application has two variables. After using the and logical operator (&&), the
application will print true if both variables exist; on the other hand, the application will print false if there is a
variable that does not exist. In the first exercise, the application will print false because a variable does not exist;
then, in the second exercise, the application will print true because both variables exist.
Practice – First Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A && $Teraexe_C); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A && $Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
74
Exercise Seventy-One: PHP – The Or Logical Operators – Method 2
Theory: • The Or Logical Operator (||): A coder can use the or logical operator (||) when he/she wants to test if at least one
of the two variables is true; to put it another way, a programmer can use the or logical operator (||) when he/she
wants to know or test if a computer application has at least one of the two variables that he/she is testing. After
using the or logical operator (||), the application will print true if at least one variable exists; on the other hand,
the application will print false if both variables do not exist. In the first exercise, the application will print false
because both variables do not exist, in other words, the program will print false because both variables are not
true; then, in the second exercise, the application will print true because at least one of the two variables is true.
Practice – First Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_C || $Teraexe_D); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; $Teraexe_B = 23; var_dump($Teraexe_A || $Teraexe_D); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
75
Exercise Seventy-Two: PHP – The Not Logical Operators
Theory: • The Not Logical Operator (!): A coder can use the not logical operator (!) when he/she wants to test if a variable
is not true; to put it another way, a programmer can use the not logical operator (!) when he/she wants to know or
test if a computer application has not a variable inside of its source code. After using the not logical operator (!),
the application will print true if a variable does not exist; on the other hand, the application will print false if a
variable exists. In the first exercise, the application will print false because a variable exists, in other words, the
program will print false because a variable is true; then, in the second exercise, the application will print true
because a variable does not exist.
Practice – First Exercise: <?php $Teraexe_A = 23; var_dump(!$Teraexe_A); ?> Result – First Exercise:
Practice – Second Exercise: <?php $Teraexe_A = 23; var_dump(!$Teraexe_B); ?> Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
76
Exercise Seventy-Three: PHP – The Union Array Operator
Theory: • The Union Array Operator (+): A coder can use the union array operator (+) when he/she wants add the elements
of two arrays. In the next exercise, there will be a union of Gene_A and Gene_B; in other words, the elements of
Gene_A and Gene_B will be added inside of a new variable that is known as Gene_C.
Practice: <?php
$Gene_A = array("A" => "Keyboard", "B" => "Pendrive"); // first array
$Gene_B = array("C" => "Mouse", "D" => "Laptop"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_C);
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
77
Exercise Seventy-Four: PHP – The Equality Array Operators
Theory: • The Equality Array Operator (==): A coder can use the equality array operator (==) when he/she wants to test if
an array has the same elements than other array; to put it another way, a programmer can use the equality array
operator (==) when he/she wants to know or test if a computer application has two arrays with the same words
and values. After using the equality array operator (==), the application will print true if an array has the same
elements than other array; on the other hand, the application will print false if an array does not have the same
elements than other array. In the first exercise, the application will print false because an array does not have the
same elements than other array, in other words, the computer application will print false because there are two
arrays without the same words/values; then, in the second exercise, the application will print true because an array
has the same elements than other array.
Practice – First Exercise: <?php
$Gene_A = array("Pendrive" => "50", "Laptop" => "300"); // first array
$Gene_B = array("Keyboard" => "23", "Mouse" => "25"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_A == $Gene_B);
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
78
Result – First Exercise:
Practice – Second Exercise: <?php
$Gene_A = array("Keyboard" => "23", "Mouse" => "25"); // first array
$Gene_B = array("Keyboard" => "23", "Mouse" => "25"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_A == $Gene_B);
?>
Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
79
Exercise Seventy-Five: PHP – The Identity Array Operators
Theory: • The Identity Array Operator (===): A coder can use the identity array operator (===) when he/she wants to test if
an array has exactly the same elements than other array; to put it another way, a programmer can use the equality
array operator (===) when he/she wants to know or test if a computer application has two arrays with the same
words and values in the same order. After using the identity array operator (===), the application will print true if
an array has the same elements in the same order than other array; on the other hand, the application will print
false if an array does not have the same elements in the same order than other array. In the first exercise, the
application will print false because an array does not have the same elements in the same order than other array;
then, in the second exercise, the application will print true because an array has the same elements in the same
order than other array.
Practice – First Exercise: <?php
$Gene_A = array("Keyboard" => "23", "Mouse" => "25"); // first array
$Gene_B = array("Mouse" => "25", "Keyboard" => "23"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_A === $Gene_B);
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
80
Result – First Exercise:
Practice – Second Exercise: <?php
$Gene_A = array("Keyboard" => "23", "Mouse" => "25"); // first array
$Gene_B = array("Keyboard" => "23", "Mouse" => "25"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_A === $Gene_B);
?>
Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
81
Exercise Seventy-Six: PHP – The Inequality Array Operators
Theory: • The Inequality Array Operator (!=): A coder can use the inequality array operator (!=) when he/she wants to test
if an array does not have the same elements than other array; to put it another way, a programmer can use the
inequality array operator (!=) when he/she wants to know or test if a computer application does not have two
arrays with the same words and values. After using the inequality array operator (!=), the application will print
true if an array does not have the same elements than other array; on the other hand, the application will print
false if an array has the same elements than other array. In the first exercise, the application will print false
because an array has the same elements than other array, in other words, the computer application will print false
because there are two arrays with the same words/values; then, in the second exercise, the application will print
true because an array does not have the same elements than other array. An important point that a coder should
know about the inequality array operator is that he/she can use two different kinds of symbols (!= or <>) when
he/she is testing an array.
Practice – First Exercise: <?php
$Gene_A = array("Keyboard" => "23", "Mouse" => "25"); // first array
$Gene_B = array("Keyboard" => "23", "Mouse" => "25"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_A != $Gene_B);
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
82
Result – First Exercise:
Practice – Second Exercise: <?php
$Gene_A = array("Pendrive" => "50", "Laptop" => "300"); // first array
$Gene_B = array("Keyboard" => "23", "Mouse" => "25"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_A != $Gene_B);
?>
Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
83
Exercise Seventy-Seven: PHP – The Non-Identity Array Operators
Theory: • The Non-Identity Array Operator (!==): A coder can use the non-identity array operator (!==) when he/she wants
to test if an array does not have exactly the same elements than other array; to put it another way, a programmer
can use the equality array operator (!==) when he/she wants to know or test if a computer application does not
have two arrays with the same words and values in the same order. After using the non-identity array operator
(!==), the application will print true if an array does not have the same elements in the same order than other
array; on the other hand, the application will print false if an array has the same elements in the same order than
other array. In the first exercise, the application will print false because an array has the same elements in the
same order than other array; then, in the second exercise, the application will print true because an array does not
have the same elements in the same order than other array.
Practice – First Exercise: <?php
$Gene_A = array("Keyboard" => "23", "Mouse" => "25"); // first array
$Gene_B = array("Keyboard" => "23", "Mouse" => "25"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_A !== $Gene_B);
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
84
Result – First Exercise:
Practice – Second Exercise: <?php
$Gene_A = array("Keyboard" => "23", "Mouse" => "25"); // first array
$Gene_B = array("Mouse" => "25", "Keyboard" => "23"); //second array
$Gene_C = $Gene_A + $Gene_B; // union of Gene_A and Gene_B
var_dump($Gene_A !== $Gene_B);
?>
Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
85
Exercise Seventy-Eight: PHP – The $_SERVER Superglobal Variable P1 Theory: • The $_SERVER Superglobal Variable: A coder can use the $_SERVER Superglobal variable when he/she wants
to print information about his/her server, including information about server name, headers, and more. As you can
see, those are some of the most important elements that a coder can use inside of the $_SERVER Superglobal
variable:
a) $_SERVER['PHP_SELF']: A programmer can use this code when he/she wants to see or print the filename that
he/she is opening through his/her navigator. For example, if a coder is opening a website like
www.teraexe.com/test.php, the application will print /test.php.
b) $_SERVER[‘GATEWAY_INTERCAFE’]: When a coder wants to print the common gateway interface (CGI)
and its respective version, he/she can use the GATEWAY_INTERFACE element.
c) $_SERVER[‘SERVER_ADDR’]: When a coder wants to develop a computer application that is going to show
the IP address of a server, he/she can use the SERVER_ADDR element. In this case, the application will show the
server IP address, such as 50.63.210.1.
d) $_SERVER[‘SERVER_NAME’]: A PHP-developer can use this code when he/she wants to see the server name.
In the next source code, the computer application will print the server name, which is www.teraexe.com
e) $_SERVER[‘SERVER_SOFTWARE’]: A programmer can use the SERVER_SOFTWARE element to print the
name of an HTTP server, which can be Apache, IIS, or other. For example, in the next source code, the
application will print Apache because the name of the HTTP server is Apache.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
86
Practice: <?php
print "Filename: " . $_SERVER['PHP_SELF'] . "<br>";
print "CGI Version: " . $_SERVER['GATEWAY_INTERFACE'] . "<br>";
print "Server Address: " . $_SERVER['SERVER_ADDR'] . "<br>";
print "Server Name: " . $_SERVER['SERVER_NAME'] . "<br>";
print "Server Software: " . $_SERVER['SERVER_SOFTWARE'];
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
87
Exercise Seventy-Nine: PHP – The $_SERVER Superglobal Variable – P2 Theory: f) $_SERVER['SERVER_PROTOCOL']: A programmer can use the SERVER_PROTOCOL element when he/she
wants to see or print the server protocol and its respective version, which can be HTTP/1.0, HTTP/1.1, or other.
For example, in the next source code, the application will print the server protocol and its respective version,
which is HTTP/1.1.
g) $_SERVER['REQUEST_METHOD']: A coder can use the REQUEST_METHOD element inside of the $_Server
Superglobal variable when he/she wants to print a request method. What is a request method? When a client is
visiting a website, he/she can use different kinds of methods to visit a web page, such as GET and POST. On the
one hand, a GET request method is when a client is retrieving information or data from a specific server;
therefore, in a GET request method, a server only has to show information or data to a client. On the other hand, a
POST request method is when a client is requesting to an HTTP server to accept information or data that may be
store inside of a database; therefore, in a POST request method, a client only has to post or submit a message to
an HTTP server.
h) $_SERVER['REQUEST_METHOD']: A coder can use the REQUEST_TIME element when he/she wants to
calculate the loading time of a website or file. Furthermore, the loading time is going to be shown in floats with
microseconds—a microsecond is equal to 1/1,000,000 seconds; furthermore, a microsecond is equal to 1/1,000
nanoseconds or milliseconds.
i) $_SERVER['HTTP_ACCEPT']: A coder can use the HTTP_ACCEPT element when he/she wants to print the
Accept headers of an HTTP server.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
88
j) $_SERVER['HTTP_HOST']: A PHP-developer can use the HTTP_HOST element inside of the $_Server
Superglobal variable when he/she wants to print the server name. In the next source code, the computer
application will print the server name, which is www.teraexe.com
Practice: <?php
print "Server Protocol: " . $_SERVER['SERVER_PROTOCOL'] . "<br>";
print "Request Method: " . $_SERVER['REQUEST_METHOD'] . "<br>";
print "Request Name: " . $_SERVER['REQUEST_TIME'] . "<br>";
print "HTTP Accept: " . $_SERVER['HTTP_ACCEPT'] . "<br>";
print "HTTP HOST: " . $_SERVER['HTTP_HOST'];
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
89
Exercise Eighty: PHP – The $_SERVER Superglobal Variable – P3 Theory: k) $_SERVER['SCRIPT_FILENAME']: A programmer can use the SCRIPT_FILENAME element inside of the
$_Server Superglobal variable when he/she wants to print the pathname of a script or file; to clarify, a coder can
use the SCRIPT_FILENAME element to see the directory or location of a file, also known as script. As you can
see, in the next exercise, the application will print the name and directory of a script, which is
/var/chroot/home/content/02/8654202/html/test.php
l) $_SERVER['SERVER_ADMIN']: A coder can use the SERVER_ADMIN element inside of the $_Server
Superglobal variable when he/she wants to print the server admin email address. For example, in the next
exercise, the computer application will print [email protected] because that is the server admin email
address.
m) $_SERVER['REMOTE_ADDR']: A coder can use the REMOTE_ADDR element when he/she wants to print the
IP address of a server; for example, in the next exercise, the computer application will print the IP address of a
server, which is 75.74.151.8.
n) $_SERVER['REMOTE_PORT']: A coder can use the REMOTE_PORT element when he/she wants to print the
client port; to put it another way, an administrator can use the REMOTE_PORT element to print the port that an
internaut or client is using to communicate to an HTTP server or website. For example, in the next exercise, the
computer application will print the port that I am using to make a connection to the web page, which is 1185.
o) $_SERVER['SERVER_PORT']: A coder can use the SERVER_PORT element inside of the $_Server Superglobal
variable when he/she wants to print the server port; in other words, a coder can use the SERVER_PORT element
to print the port that a server is using to make different kinds of connections to its clients. For example, in the next
exercise, the computer application will print the port that my HTTP server is using to communicate to its clients,
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
90
which is the port 80. As you should know, usually, an HTTP server is going to use the port 80 to provide server to
its clients.
Practice: <?php
print "Script Filename: " . $_SERVER['SCRIPT_FILENAME'] . "<br>";
print "Server Admin: " . $_SERVER['SERVER_ADMIN'] . "<br>";
print "Remote Address: " . $_SERVER['REMOTE_ADDR'] . "<br>";
print "Remote Port: " . $_SERVER['REMOTE_PORT'] . "<br>";
print "Server Port: " . $_SERVER['SERVER_PORT'];
?>
Result:
Exercise Eighty-One: PHP – The $_SERVER Superglobal Variable – P4 Theory: p) $_SERVER['SERVER_SIGNATURE']: A coder can use the SERVER_SIGNATURE element inside of the
$_Server Superglobal variable when he/she wants to print the server signature, which includes the server name,
URL, and port. As you can see, in the next exercise, the computer application will print the server signature,
which is Apache Server at www.teraexe.com Port 80.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
91
q) $_SERVER['SCRIPT_NAME']: A coder can use the SCRIPT_NAME element inside of the $_Server Superglobal
variable when he/she wants to print the name of a script; in other words, a programmer can use the
SCRIPT_NAME element to print the script name that an internaut is opening through a navigator. As you can see,
in the next exercise, the application will print the script name, which is /test.php.
r) $_SERVER['SCRIPT_URI']: A coder can use the SCRIPT_NAME element inside of the $_Server Superglobal
variable when he/she wants to print the uniform resource identifier (URI); to clarify, a programmer can use the
SCRIPT_NAME element to print the location and name of a script or file that is on the internet. For example, in
the next exercise, the application will print the URI, which is http://www.teraexe.com/test.php.
Practice: <?php
print "Server Signature: " . $_SERVER['SERVER_SIGNATURE'] . "<br>";
print "Script Name: " . $_SERVER['SCRIPT_NAME'] . "<br>";
print "Script URI: " . $_SERVER['SCRIPT_URI'];
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
92
Exercise Eighty-Two: PHP – Multidimensional Arrays – 2D-Array Theory: • Overview of the Array Function: As previously mentioned, a coder can use an array to hold the values of a
variable, and he/she only has to type a line similar to this: $Gene_Tools = array("Antivirus","Firewall","Port-
Scanner");. As you can see in the previous line, an array is holding the values of Gene_Tools, which are
Antivirus, Firewall, and Port-Scanner; in addition, in that particular case, the elements of Gene_Tools are
Antivirus, Firewall, and Port-Scanner.
• Multidimensional Arrays: When a coder is programming or typing an array of arrays, he/she is developing or
declaring a two-dimensional array; in other words, when a coder is programming or typing an array inside of
other array, he/she is developing or declaring a two-dimensional array because an array is inside of the function of
other array. Furthermore, when a programmer is coding an array of array of arrays, he/she is defining or declaring
a three-dimensional array. Therefore, a multidimensional array is a two-dimensional, three-dimensional, four-
dimensional, or X-dimensional array in which X can be two, three, four, five, or more. In the next exercise, I am
going to develop a two-dimensional array because there are some arrays that are inside of other array. In addition,
I am going to show you how to print the elements of an array while I am using different kinds of numbers to call
some rows and columns; for example, I am going to use the number zero (0) for the first row, and I am going to
use the number one (1) for the second row; similarly, I am going to use the number zero (0) for the first column,
and I am going to use the number one (1) for the second column.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
93
Practice:
<?php
//A two-dimensional array, also known as a 2D-array.
$Teraexe_Tools = array // The first array, which contains two arrays.
(
array("Port Scanner",3,5), //This array is inside of the first array.
array("Network Traffic Monitor",4,5), //this array is inside of the first array.
);
print $Teraexe_Tools[0][0]; // First row, First column (Port Scanner).
print ": Previous Cost: ";
print $Teraexe_Tools[0][1]; // First row, Second column (3).
print ". Current Cost: ";
print $Teraexe_Tools[0][2]; // First row, Third column (5).
print ".<br>";
print $Teraexe_Tools[1][0]; // Second row, First column (Netwok Traffic Monitor).
print ": Previous Cost: ";
print $Teraexe_Tools[1][1]; // Second row, Second column (4).
print ". Current Cost: ";
print $Teraexe_Tools[1][2]; // Second row, Second column (5).
print ".<br>";
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
94
Exercise Eighty-Three: PHP – Multidimensional Arrays – 3D-Array Theory: • Three-Dimensional Array: In the next exercise, I am going to show you how to develop a three-dimensional
array, also known as an array of array of arrays.
Practice:
<?php //A three-dimensional array, also known as a 3D-array. $Teraexe_Tools = array // The first array ( array // The Second Array ( array("Port Scanner",3,5), //This array is inside of the second array. array("Network Traffic Monitor",4,5), //this array is inside of the second array. ) ); print $Teraexe_Tools[0][0][0]; // Third Array: First row, First column (Port Scanner). print ": Previous Cost: "; print $Teraexe_Tools[0][0][1]; // Third Array: First row, Second column (3). print ". Current Cost: "; print $Teraexe_Tools[0][0][2]; // Third Array: First row, Third column (5). print ".<br>"; print $Teraexe_Tools[0][1][0]; // Third Array: Second row, First column (Netwok Traffic Monitor). print ": Previous Cost: "; print $Teraexe_Tools[0][1][1]; // Third Array: Second row, Second column (4). print ". Current Cost: "; print $Teraexe_Tools[0][1][2]; // Third Array: Second row, Second column (5). print ".<br>"; ?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
95
Exercise Eighty-Four: PHP – Printing Date and Time
Theory:
• Printing Date and Time: When a coder wants to print the timestamp of a computer/application/file, he/she can use
the date function. What is a timestamp? It is the date/time of an event that is happening or happened inside of a
computer, and this event is usually recorded by a computer or computer application. Therefore, the timestamp can
be the creation time of a file; furthermore, the timestamp can be the current local time of a computer. As you can
see, this is the syntax of the date function:
Date (Format of Date/Time, Timestamp);
a) Format of Date/Time: A coder can use this element when he/she wants to specify the format of date/time; in other
words, a programmer can use this element to specify the way in which the timestamp will be showed to other
internauts or clients of a website. As you can see, those are some of the most common characters that you can use
when you are formatting the date/time while you are using the date function:
o d = A coder can use this character to specify the day.
o m = A coder can use this character to specify the month.
o Y = A coder can use this character to specify the year.
o l = A coder can use this character to specify the day of a week.
In addition to those four characters, a coder can also use other characters among d/m/Y/l, such as a point (.), a
slash (/), or a dash (-). The point/slash/dash can be used to format a date; for example, a coder can use a slash to
format a date in this way: 05/20/14.
b) Timestamp: A coder can use this element when he/she wants to specify the timestamp, which can be date or time.
If a programmer does not specify anything, the timestamp will be the current date and time.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
96
Practice: <?php
print date ("m/d/Y"); // Output: 08/18/2014
print "<br>";
print date ("l" ); // Output: Monday
print "<br>";
print date ("M" ); // Extra - Output: Aug
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
97
Exercise Eighty-Five: PHP – Printing Date and Time – Part 2
Theory: • Printing Date and Time – Part 2: Not only does a coder can use those kinds of characters that we saw in the
previous exercise (d, m Y, and l), but also a coder can use other characters to format the date/time. As you can
see, those are some of the most common characters that a coder can use to format the time:
o h = A coder can use this character to specify the hour.
o i = A coder can use this character to specify the minutes.
o s = A coder can use this character to specify the seconds.
o a = A coder can use this character to specify the ante-meridiem (am) or post-meridiem (pm).
Practice: <?php
print date ("h:i:s a"); // Example of output: 09
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
98
Exercise Eighty-Six: PHP – Printing Date and Time – Time-zone
Theory: • Printing the Time of a Specific Location: A coder can use the date_default_timezone_set function when he/she
wants to print the time of a specific location, such as Detroit, New York, Los Angeles, or other place. As you can
see, this is the syntax of the date_default_timezone_set function:
date_default_timezone_set (location);
Location: In this element, a coder has to type a specific location, which can be a state or country. As you can see,
those are some of the locations or codes that a coder can use:
o America/Detroit
o America/New_York
o America/Los_Angeles
o America/Chicago
o America/North_Dakota/Center
Practice: <?php
date_default_timezone_set("America/Detroit");
print date("h:i:s a");
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
99
Exercise Eighty-Seven: PHP – Date and Time – The mktime Function
Theory: • Creating Date and Time with the mktime Function: A coder can use the mktime function when he/she wants to
develop an application that will show a specific date and/or time to those internauts or clients who are visiting
his/her website. As you can see, this is the syntax of the mktime function:
mktime (hour, minute, second, month, day, year);
Practice: <?php $Teraexe = mktime(3, 23, 59, 5, 20, 2014); print date("Y-m-d h:i:s a", $Teraexe); ?> Result:
Exercise Eighty-Eight: PHP – Date and Time – The strtotime Function Theory: • Creating Date and Time with the strtotime Function: In addition to the mktime function that we saw in the
previous exercise, a coder can also use the strtotime function when he/she wants to create a specific time. As you
can see, this is the syntax of the strtotime function:
strtotime (time, now)
Practice: <?php $Teraexe = strtotime("12:00pm May 20 2014"); print date("Y-m-d h:i:sa", $Teraexe); ?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
100
Result:
Exercise Eighty-Nine: PHP – The strtotime Function – Future Time Theory: • The strtotime Function – Future Time: A coder can use the strtotime function when he/she wants to print a future
time; for example, a coder can use the strtotime function to print the time of the next hour/day/week/month/year.
Practice: <?php $Teraexe = strtotime("next Monday"); print "Next Monday: " . date("Y-m-d h:i:sa", $Teraexe) . "<br>"; $Teraexe = strtotime("+1 hour"); print "+1 hour: " . date("Y-m-d h:i:sa", $Teraexe) . "<br>"; $Teraexe = strtotime("+3 days"); print "+3 days: " . date("Y-m-d h:i:sa", $Teraexe) . "<br>"; $Teraexe = strtotime("+1 week"); print "+1 week: " . date("Y-m-d h:i:sa", $Teraexe) . "<br>"; $Teraexe = strtotime("+6 Months"); print "+6 months: " . date("Y-m-d h:i:sa", $Teraexe) . "<br>"; ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
101
Exercise Ninety: PHP – The Include Statement
Theory:
• The Include Statement: When a coder wants to include the content of a file inside of other file, he/she can use the
include statement. As you can see, this is the syntax of the include statement:
Include (“The name of a File”);
Practice 1 (First File: message.php):
First, you have to create a file called message.php; then, you have to include this code:
<?php
print "This information is inside of a file that is called message.php" . "<br>";
?>
Practice 2 (Second File: index.php):
Finally, you have to create a file called index.php, and you have to include this code:
<?php
include("message.php");
print "This information is inside of a file that is called index.php";
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
102
Result:
Practice 2 (Deleting message.php):
• What happens if you delete the file message.php? In this case, you will see an error; furthermore, you are going to
see all the information that is inside of the file index.php, which is something that does not happens when you are
using other commands similar to include, such as the require command that I am going to show you in the next
exercise.
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
103
Exercise Ninety-One: PHP – The Require Statement
Theory: • The Require Statement: A coder can use the require statement to include the content of a file on other file.
Practice 1 (First File: message.php):
First, you have to create a file called message.php; then, you have to include this code: <?php print "This information is inside of a file that is called message.php" . "<br>"; ?> Practice 2 (Second File: index.php): Finally, you have to create a file called index.php, and you have to include this code:
<?php
require("message.php");
print "This information is inside of a file that is called index.php";
?>
Result:
Practice 2 (Deleting message.php): • What happens if you delete the file message.php? In this case, you will see an error; furthermore, you are not
going to see all the information that is inside of the file index.php,
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
104
Exercise Ninety-Two: PHP – The Readfile Function
Theory: • The Readfile Function: When a coder wants to open the content of a file and print this content inside of a php file,
he/she can use the readfile function. Not only does the readfile function will open the content of a php file, but
also it will show the number of bytes of that file. In the next exercise, the readfile function is going to open a file
called Gene.txt; furthermore, the readfile function will show the number of bytes of Gene.txt, which is 69 bytes.
Practice: <?php
print readfile("Gene.txt");
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
105
Exercise Ninety-Three: PHP – The Fopen Function Theory: • The fopen Function: In addition to the readfile function, a coder can use the fopen function to open the content of
a file. When a coder is using the fopen function to interact with a file, he/she can use different kinds of “modes”
to interact with that file that is inside of his/her server. As you can see, those are some of the most common
modes that a coder can use when he/she is interacting with a file through the fopen function:
o r = A coder has to type “r” when he/she wants to read a file.
o w = A coder has to type “w” when he/she wants to create a new file or erase the content of a file.
o r+ = A coder has to type “r+’ when he/she wants to read/write a file.
• The fread Function: A coder can use the fread function to read a file.
• The fclose Function: A coder can use the fclose function to close a file.
Practice:
First, you have to create the Gene.txt file; then, you have to include this content inside of that file: The Easiest Way to
Learn PHP & MySQL by Alvaro J. Gene (Socket_0x03). Finally, you have to include the next source code inside of
the index file:
<?php $Gene_File = fopen("Gene.txt", "r" ); print fread($Gene_File,filesize("Gene.txt")); fclose($Gene_File); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
106
Exercise Ninety-Four: PHP – The Fopen Function – Creating a File Theory: • Creating a File with the fopen Function: A coder can use the fopen function with the mode “w” when he/she
wants to create a new file. For example, in the next exercise, I am going to use the fopen function with its
parameter “w” to create a text file called Teraexe.txt.
Practice: <?php
$Gene_File = fopen("Teraexe.txt", "w");
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
107
Exercise Ninety-Five: PHP – The fwrite Function Theory: • Writing a File with the fwrite Function: When a coder is using the fopen function, he/she can also use the fwrite
function to start adding content or characters inside of a text file. For instance, in the next exercise, I am going to
create the Teraexe.txt file; furthermore, I am going to include this line inside of the Teraexe.txt file: The Easiest
Way to Learn PHP & MySQL by Alvaro J. Gene (Socket_0x03). An important point that a coder should know
about this function is that if he/she is using the fwrite function in the same way that I am using it, the fwrite
function is going to erase everything inside of a text file while this function is adding new characters to a file. As
previously stated, the “w” mode of the fopen function will erase everything inside of a file before creating a new
file.
Practice: <?php $Gene_File = fopen ("Teraexe.txt", "w"); $Gene_Write = "The Easiest Way to Learn PHP & MySQL by Alvaro J. Gene (Socket_0x03)"; fwrite ($Gene_File, $Gene_Write); fclose ($Gene_File); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
108
Exercise Ninety-Six: PHP – The Fget Function
Theory: • The fget Function: When a coder is using the fopen function, he/she can use the fget function to read the first line
of a file.
Practice:
First, you have to create the Gene.txt file; then, you have to include this content inside of that file:
First Line…
Second Line…
Third Line…
Then, you have to include the next source code inside of the index file:
<?php
$Gene_File = fopen("Gene.txt", "r" );
print fgets($Gene_File);
fclose($Gene_File);
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
109
Exercise Ninety-Seven: PHP – The feof Function Theory: • The feof Function: Also known as the end of file function. A coder can use the feof function when he/she wants
to test the end of a file, so a coder may test if the end of a file is true or false. In the next exercise, the information
inside of the Gene.txt file will be true and printed as long as the end of file (EOF) is false; then, at the end of the
Gene.txt file, the feof function will stop printing because the end of file (EOF) is true, which means that there is
not more information inside of the Gene.txt file.
Practice:
First, you have to create the Gene.txt file; then, you have to include this content inside of that file:
First Line…
Second Line…
Third Line…
Then, you have to include the next source code inside of the index file:
<?php $Gene_File = fopen("Gene.txt", "r" ); while(!feof($Gene_File)) { print fgets($Gene_File); print "<br>"; } fclose($Gene_File); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
110
Exercise Ninety-Eight: PHP – The fgetc Function Theory: • The fgetc Function: When a coder is using the fopen and feof function, he/she can also use the fgetc function to
open a file and print its characters vertically. To put it another way, a coder can use the fgetc function to open a
file and read character by character while this function is printing character by character for each single line.
Practice – Part 1:
First, you have to create the Gene.txt file; then, you have to include this content inside of that file:
First.
Then, you have to include the next source code inside of the index file:
<?php $Gene_File = fopen("Gene.txt", "r" ); while(!feof($Gene_File)) { print fgetc($Gene_File); print "<br>"; } fclose($Gene_File); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
111
Exercise Ninety-Nine: PHP – Creating a Cookie Theory: • Creating a Cookie: In the next example, you can learn how to create a cookie in PHP. If you want to create a
cookie in PHP, you can use the setcookie command; then, you have to type the name of a cookie and its value. As
you can see, Teraexe_User is the cookie’s name; in addition, Socket_0x03 is a value of that cookie.
• Time: You can use the time command to choose a time in which a cookie is going to expire. In the next example,
I am using +3600 because the cookie will expire in 3600 seconds; in other words, the cookie is going to expire in
one hour.
Practice:
<?php setcookie("Teraexe_User", "Socket_0x03", time()+3600); ?> Result 1:
• You can see your results using IECookiesView, which is a tool that you can use to see your cookies.
Result 2:
• If you want to see your cookie in Internet Explorer 6, click on Tools, internet options, settings, and view files.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
112
Exercise 100: PHP – Retrieving the Value of a Cookie
Theory: • Retrieving the value of a cookie: In the previous exercise, we learned how to create a cookie. Now, we are going
to learn how to retrieve the value of that cookie.
Practice:
<?php print $_COOKIE["Teraexe_User"]; ?> Result:
Exercise 101: PHP – Printing all your Cookies
Theory: • We can use the print_r command to see the value of our cookies.
Practice:
<?php print_r($_COOKIE); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
113
Exercise 102: PHP – Cookies in your PC
Theory: • Command isset: You can use this command to find out if a cookie has been set.
Practice:
<?php if (isset($_COOKIE["Teraexe_User"])) print "You are a member of this website..." . $_COOKIE["Socket_0x03"]; else print "You are only a guest."; ?> Result:
Exercise 103: PHP – Deleting a Cookie
Theory: • In the next exercise, we are going to learn how to delete a cookie in PHP.
Practice:
<?php setcookie("Teraexe_User", "" , time()-3600); ?> Result: • As you can see, the cookie Teraexe_User has been deleted.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
114
Exercise 104: PHP – The $_SESSION Superglobal Variable Theory: • The $_SESSION Superglobal Variable: A coder can use the $_SESSION Superglobal variable when he/she wants
to store/retrieve a session, such as a session ID. What is a session ID? Also known as a session token or session
identifier. A session token is a unique identification number (UID) that identifies a specific
system/browser/client/user with an HTTP server or website; furthermore, this unique identification number (UID)
is going to be stored “temporally” inside of a cookie, or this UID will be stored “temporally” in a URL parameter.
An important point that a PHP-developer should know about this kind of session is that this session is temporal,
which means that this kind of session is going to expire if a user leaves an HTTP server or website. Therefore, if a
coder wants a permanent storage to his/her clients or users, he/she should use a database instead of this kind of
session.
• The session_start function: Before using the $_SESSION Superglobal variable, a coder has to start a session with
the session_start command. An important point that a coder should know about the session_start function is that
this kind of function has to be typed before including the HTML tag. As you can see in the next exercise, I am
using the HTML tag after the session_start function; furthermore, I am using the $_SESSION Superglobal
variable to store a unique identification number (UID) before including the HTML tag.
Practice: <?php session_start(); // start a session $_SESSION['Gene_Variable']=1; // store a session ?> <html> <body> <?php print $_SESSION['Gene_Variable']; // retrieve the UID of a session ?> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
115
HTML Review
Before starting with PHP forms, I am going to provide some information about HTML because one of the best
ways to start developing PHP forms is knowing about HTML. What is HTML? HTML is an abbreviation for the
Hyper-Text Markup Language. Do you know what a markup language is? Basically, a markup language is one of
those computer languages that use different kinds of “tags” in order to create websites or HTML documents. As you
can see, those are some of the most common examples of HTML tags: <html>, <p>, and <br>.
An HTML Review: Exercise I: Creating an HTML Document Theory: • <html>: When an individual or coder wants to start building an HTML document, he/she has to type the <html>
tag at the beginning of his/her form document.
• </html>: When an individual or coder wants to stop building an HTML document, he/she has to type the </html>
tag at the end of his/her form document.
• <body> and </body>: A coder can use the <body> tag when he/she wants to start typing the website body. Then,
after typing the <body> tag, a coder can use the </body> tag to stop typing the website body. As you can see, in
an opening tag a coder does not have to include a slash (/); however, in a closing tag a coder has to include a slash
(/), such as </html> and </body>.
• <h1> and </h1>: A coder can use the heading tags when he/she wants to include a header inside of his/her HTML
document.
• <p> and </p>: A coder can use the paragraph tags when he/she wants to include a paragraph inside of an HTML
document.
• Creating and Opening an HTML Document: If you want to create and open an HTML document, you have to
follow those steps:
o First, you have to create a text document, also known as a block notes. If you are using Windows XP, you
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
116
have to make right-click on a folder; then, you have to select new and click on Text Document.
o Second, you have to include a script or source code inside of a block notes or text file.
o Third, you have to save your script or source code as index.html. If you are using Windows XP, you have to
make a click on File; then, you have to make a click on Save As. Finally, you have to type: index.html.
o Finally, you can open your script through a browser. Usually, when someone wants to open an HTML
document through a browser, he/she has to make double-click on an HTML file. In addition, a coder can use
his/her HTTP server to open an HTML document.
Practice: <html>
<body>
<h1>Socket_0x03 is typing a header</h1>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
117
An HTML Review: Exercise II: Heading Size Theory: • Heading Size: When a coder is typing some headers, he/she can use six heading sizes, also known as heading
levels.
• Practice: <html>
<body>
<h1>Heading Level One</h1>
<h2>Heading Level Two</h2>
<h3>Heading Level Tree</h3>
<h4>Heading Level Four</h4>
<h5>Heading Level Five</h5>
<h6>Heading Level Six</h6>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
118
An HTML Review: Exercise III: HTML Links Theory: • HTML Link: A coder can use the <a> tag when he/she wants to open a new link or website.
Practice:
<html> <body> <a href="http://www.teraexe.com">Teraexe Link</a> </body> </html> Result:
An HTML Review: Exercise IV: HTML Images Theory: • HTML Images: A coder can use the <img> tag when he/she wants to put an image inside of a website.
Practice:
<html> <body> <img src="Teraexe.bmp"> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
119
An HTML Review: Exercise V: HTML – Elements and Lines Theory: • Element: In HTML, an element is composed of three parts: the starting tag, the content, and the ending tag. As
you can see, this is an example of the p element:
o Starting tag: <p>
o Content: This is a paragraph.
o Closing tag: </p>
• The hr element: A coder can use the hr element when he/she wants to create a line inside of a web page; therefore,
the hr element can be used as a paragraph break, or it can also be used to separate different kinds of contents like
paragraphs, images, and more.
Practice:
<html>
<body>
<p>Socket_0x03 is typing the first paragraph</p>
<hr>
<p>Socket_0x03 is typing the second paragraph</p>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
120
An HTML Review: Exercise VI: HTML – The Title Element Theory: • The Title Element: A coder can use the title element when he/she wants to type the title of a website.
Practice:
<html> <body> <title>Socket_0x03 is typing the title of a website</title> </body> </html> Result:
An HTML Review: Exercise VII: HTML – Text Formatting Theory:
• The b element: A coder can use the b element when he/she wants to type bold text.
• The em element: A coder can use the em element when he/she wants to type emphasized text.
• The i element: A coder can use the i element when he/she wants to type italicized text.
• The small element: A coder can use the small element when he/she wants to type small text.
• The strong element: A coder can use the strong element when he/she wants to type strong text.
• The sub element: A coder can use the sub element when he/she wants to type subscripted text.
• The sup element: A coder can use the sup element when he/she wants to type superscripted text.
• The ins element: A coder can use the ins element when he/she wants to type inserted text.
• The del element: A coder can use the del element when he/she wants to type deleted text.
• The mark element: A coder can use the mark element when he/she wants to type market text.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
121
Practice:
<html>
<body>
<p><b>Socket_0x03 is typing bold text.</b></p>
<p><em>Socket_0x03 is typing emphasized text.</em></p>
<p><i>Socket_0x03 is typing italicized text.</i></p>
<p><small>Socket_0x03 is typing small text.</small></p>
<p><strong>Socket_0x03 is typing strong text.</strong></p>
<p><sub>Socket_0x03 is typing <sub>subscripted</sub> and <sup>superscripted</sup> text.</sub></p>
<p><ins>Socket_0x03 is typing inserted text.</ins></p>
<p><del>Socket_0x03 is typing deleted text.</del></p>
<p><mark>Socket_0x03 is typing marked text.</mark></p>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
122
An HTML Review: Exercise VIII: Comments Theory: • Comments: In the next exercise, you are going to learn how to include different kinds of comments or messages
inside of an HTML document. As you should know, those kinds of comments are only for those programmers or
coders who are reading the source code of an HTML document because the browser of an individual is not going
to show those kinds of messages or comments when an internaut is opening a website through a browser.
Practice: <html>
<body>
<!--This is a comment-->
<p>Socket_0x03 is typing a paragraph.</p>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
123
An HTML Review: Exercise IX: The Title Attribute Theory: • The Title Attribute: When a coder wants to provide information about an element, he/she can use different kinds
of attributes. In the next exercise, if an individual places his/her mouse over a paragraph, he/she will notice a text,
which is the paragraph title.
Practice: <html>
<body>
<h1>Teraexe</h1>
<p title="Teraexe">if an individual places his/her mouse over this paragraph,<br>
he/she will see its title.</p>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
124
An HTML Review: Exercise X: The Size Attribute Theory: • The Size Attribute: After using the img element, a coder can use the size attribute (width and height) when he/she
wants to specify the size of an image.
Practice: <html> <body> <img src="Teraexe.bmp" width="370" height="70"> </body> </html> Result:
An HTML Review: Exercise XI: The Alt Attribute Theory: • The Alt Attribute: The alt attribute will show text if an image is not showed inside of a browser.
Practice: <html> <body> <img src="Teraexe.bmp" width="370" height="70"> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
125
An HTML Review: Exercise XII: HTML and CSS Theory: • HTML and CSS: When a coder is using HTML, he/she can use Cascading Style Sheets (CSS) to change the style
of a web-page or sheet. Usually, an individual is going to use CSS inside of an HTML element; for example, a
programmer may use CSS inside of the p element, or a coder may use CSS inside of the h element. There are
three different ways to use CSS:
o Incline: An incline style is when a coder is using CSS inside of an HTML element, such as the p element.
o Internal: An internal style is when a coder is using CSS inside of the style element.
o External: An external style is when a coder is using CSS inside of the link element.
Practice 1 - Incline: <html> <body> <!-- In the next line, I am changing the background color. --> <body style="background-color:lightblue"> <!-- In the next line, I am changing the paragraph color. --> <p style="color:blue;margin-left:23px;">Socket_0x03 is typing a paragraph.</p> <!-- In the next line, I am changing the font-face. --> <p style="font-family:Monotype Corsiva">Socket_0x03 is typing a paragraph.</p> <!-- In the next line, I am changing the font-size. --> <p style="font-size:120%">Socket_0x03 is typing a paragraph.</p> <!-- In the next line, I am changing the text-alignment. --> <p style="text-align:center">Socket_0x03 is typing a paragraph.</p> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
126
Result 1 - Incline:
Practice 2 - Internal: <html>
<body>
<style>
body {background-color:lightblue}
p {color:blue}
</style>
<p>Socket_0x03 is typing a paragraph.</p>
</body>
</html>
Result 2 - Internal:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
127
Practice 3 - External:
First, you have to use a text document or block notes to create this file: styles.css.
Then, you have to put the next code inside of the style.css file:
body {background-color:lightblue}
p {color:blue}
Finally, you have to put the next code inside of the index.html file:
<html>
<body>
<head>
<link rel="stylesheet" href="styles.css"
</head>
<p>Socket_0x03 is typing a paragraph.</p>
</body>
</html>
Result 3 - External:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
128
An HTML Review: Exercise XIII: HTML and Links – Part 1 Theory: • Hyperlink: When a coder is creating an HTML document, he/she can use hyperlinks, which is a
link/element/image/text that an individual can use to open a new HTML document while he/she is clicking on that
particular link/element/image/text. As you can see, this is the syntax of an HTML link: <a href="url">link</a> .
• Opening Local Links: When a coder is opening a local link, he/she don’t have to use http://www.website.com.
Instead of using http://www.website.com, he/she can use only the web page that he/she wants to open. As you can
see, this is an example: <a href="website.html">link</a>. On the other hand, when an individual wants to open
an HTML document that is inside of other website, he/she has to include the URL of that website. As you can see,
this is an example: <a href="http://www.teraexe.com">link</a>. In addition to that example, there is another
example on the source code of the first exercise.
• HTML Colors: When a coder is creating a link, he/she can use different kinds of HTML colors to change the
color of an active/visited link. As you can see, this is an example on the source code of the second exercise.
• Using the Target Attribute: When a coder is creating a link, he/she can use different kinds of target attributes. As
you can see, those are some of the most common attributes that a coder can use when he/she wants to open an
HTML document:
o _top: A coder can use the top value to open an HTML document in all the body of a window.
o _blank: A coder can use the blank value to open an HTML document on a new window.
o _self: A coder can use this kind of value to open an HTML document inside of the same web page.
o _parent: A coder can use this value to open a document in the parent frame.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
129
Practice 1 – Opening Local Links: <html> <body> <!--this is a local link to open a page that is inside of the website or HTTP server--> <a href="website.html">link</a>. <br> <!--this is a local link to open a page that is on other website or HTTP server--> <a href="http://www.teraexe.com">link</a>. </body> </html> Result 1 – Opening Local Links:
Practice 2 – HTML Colors: <html> <body> <style> <heap> a:active {color:#00FF00} a:visited {color:#00FF00} </style> </heap> <a href="website.html">link</a> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
130
Result 2 – HTML Colors:
Practice 3 – Target Attribute: First, you have to create the website.html page.
Then, you have to put this content inside of the website.html page: Hi.
Finally, you have to put the next code inside of the index.html page:
<html> <body> <a href="website.html" target="_top">Value: top</a> <br> <a href="website.html" target="_blank">Value: blank</a> <br> <a href="website.html" target="_self">Value: self</a> <br> <a href="website.html" target="_parent">Value: parent</a> </body> </html> Result 3 – Target Attribute:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
131
An HTML Review: Exercise XIV: HTML and Links – Part 2 Theory: • Images and Links: A coder can use an image instead of text when he/she is creating a link, so an individual has to
click inside of an image to open an HTML file. In the first exercise, you will see an example of this method.
• The id attribute and Links: When a coder is creating a link, he/she can use the id attribute to create a “bookmark”
inside of an HTML document. In HTML, a bookmark is the address of a header/paragraph/file that an individual
can use to gain access to a header/paragraph/file through a click. Therefore, an individual can use bookmarks to
go to a header/paragraph/file quickly.
Practice 1 – Links and Images: <html>
<body>
<a href="website.html">
<img src="teraexe.bmp">
</a>
</body>
</html>
Result 1 – Images and Links:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
132
Practice 2 – The id Attribute and Links:
<html> <body> <p> <a href=#Teraexe_7>Go to Exercise 7.</a> </p> <h1>Exercise 1</h1> <br><br><br><br><br><br><br> <h1>Exercise 2</h1> <br><br><br><br><br><br><br> <h1>Exercise 3</h1> <br><br><br><br><br><br><br> <h1>Exercise 4</h1> <br><br><br><br><br><br><br> <h1>Exercise 5</h1> <br><br><br><br><br><br><br> <h1>Exercise 6</h1> <br><br><br><br><br><br><br> <h1><a id="Teraexe_7">Exercise 7</h1> <br><br><br><br><br><br><br> <h1>Exercise 8</h1> <br><br><br><br><br><br><br> <h1>Exercise 9</h1> <br><br><br><br><br><br><br> <h1>Exercise 10</h1> <br><br><br><br><br><br><br> </body> </html>
Result 2 – The id Attribute and Links:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
133
An HTML Review: Exercise XV: HTML Images – The Map Element Theory: • An Introduction to the HTML Images: As previously stated, a coder can use the <img> tag when he/she wants to
put an image inside of a website. Furthermore, after using the <img> tag, a coder does not have to use the closing
tag (/img) at the end of a line. As you can see, this is the syntax of the HTML image:
<img src="url" alt="text" style="width:100px;height:100px">.
a. The src Attribute: The src attribute specifies the URL of a website.
b. The alt Attribute: As previously stated, when an image is not displayed, the alt attribute will show some text.
c. The style attribute: A coder can use the style attribute to specify the dimensions of an image; in other words, a
coder can use the style attribute to specify the width and height of an image. After specifying the dimensions of
an image through the style attribute, a coder has to type px. As you should know, px is an abbreviation for the
word pixel. Not only does a coder can use the style attribute, but also a coder can use the size attribute when
he/she wants to specify the dimensions of an image.
• The <map> Element: A coder can use the <map> element when he/she wants to create an image with clickable
areas. For example, an individual can create a box with four different colors, such as blue, red, green, and yellow.
If someone clicks on the blue box, he/she will see an HTML document with a bigger blue box. Therefore, if you
are interested in creating a map with different kinds of areas that can be expanded through some clicks, you can
use the <map> element. The map element can be effective when an individual is developing the map of a
country/state/city/region.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
134
Practice – Image Maps:
First, you have to create the box image (box.bmp):
Second, you have to create the bluebox image (bluebox.bmp):
Third, you have to create the index file (index.html); then, you have to put the next code on the index file: <html>
<body>
<img src="box.bmp" alt="Teraexe" usemap="#box1">
<map name="box1">
<area shape="rect" coords="0,0,73,63" alt="bluebox" href="bluebox.html">
</body>
</html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
135
Fourth, you have to create the bluebox file (bluebox.html) and put the next code on the bluebox file: <html>
<body>
<img src="bluebox.bmp">
</body>
</html>
Result – Image Maps: First, you have to open the index.html file:
Then, after clicking on the blue-box, you will see this image:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
136
An HTML Review: Exercise XVI: HTML Tables Theory: • The <table> Element: A coder can use the table element to create an HTML table. When a coder is creating an
HTML table, he/she can use the style attribute to specify a width.
• The <tr> Element: After using the table element, an individual can use the tr element to divide the rows of a table.
• The <td> Element: After using the tr element, a coder can use the td element to divide the columns of a table.
• The border attribute: An individual can use the border attribute when he/she wants to add a border to a table.
Practice 1 – HTML Tables:
<html> <body> <table style="width:50%"> <tr> <td>The United States</td> <td>Washington DC</td> <td>Population: 632,323</td> </tr> <tr> <td>Venezuela</td> <td>Caracas</td> <td>Population: 2,104,000</td> </tr> <tr> <td>China</td> <td>Beijing</td> <td>Population: 11,510,000</td> </tr> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
137
Result 1 – HTML Tables:
Practice 2– The Border Attribute:
<html> <body> <table border="2" style="width:50%"> <tr> <td>The United States</td> <td>Washington DC</td> <td>Population: 632,323</td> </tr> <tr> <td>Venezuela</td> <td>Caracas</td> <td>Population: 2,104,000</td> </tr> <tr> <td>China</td> <td>Beijing</td> <td>Population: 11,510,000</td> </tr> </body> </html>
Result 2– The Border Attribute:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
138
An HTML Review: Exercise XVII: HTML Tables & CSS Theory: • CSS Border: A coder can add CSS borders inside of the style element. In the first exercise, you are going to see
how to add CSS borders to an HTML document.
• CSS Collapse-Border: When a coder is adding CSS borders, he/she can add a border-collapse. In the second
exercise, you will see how to add a border-collapse.
• CSS Padding: When a coder is adding CSS borders, he/she can use the padding property to specify a space. In the
third exercise, you will learn how to use the CSS padding property.
• The th element: When a coder is adding borders to an HTML document, he/she can use the th element to display
some headers inside of his/her table. In the fourth exercise, you will learn how to use the th element.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
139
Practice 1 – CSS Border:
<html> <body> <style> table, th, td { border: 1px solid black; } </style> <table style="width:50%"> <tr> <td>The United States</td> <td>Washington DC</td> <td>Population: 632,323</td> </tr> <tr> <td>Venezuela</td> <td>Caracas</td> <td>Population: 2,104,000</td> </tr> <tr> <td>China</td> <td>Beijing</td> <td>Population: 11,510,000</td> </tr> </body> </html> Result 1 – CSS Border:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
140
Practice 2 – CSS Border-Collapse: <html> <body> <style> table, th, td { border: 1px solid black; border-collapse: collapse; } </style> <table style="width:50%"> <tr> <td>The United States</td> <td>Washington DC</td> <td>Population: 632,323</td> </tr> <tr> <td>Venezuela</td> <td>Caracas</td> <td>Population: 2,104,000</td> </tr> <tr> <td>China</td> <td>Beijing</td> <td>Population: 11,510,000</td> </tr> </body> </html>
Result 2 – CSS Border-Collapse:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
141
Practice 3 – CSS Padding: <html> <body> <style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 10px } </style> <table style="width:50%"> <tr> <td>The United States</td> <td>Washington DC</td> <td>Population: 632,323</td> </tr> <tr> <td>Venezuela</td> <td>Caracas</td> <td>Population: 2,104,000</td> </tr> <tr> <td>China</td> <td>Beijing</td> <td>Population: 11,510,000</td> </tr> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
142
Practice 3 – CSS Padding:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
143
Practice 4 – Headings: <html> <body> <style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 10px } </style> <table style="width:50%"> <tr> <th>Country</th> <th>State</th> <th>Population</th> </tr> <tr> <td>The United States</td> <td>Washington DC</td> <td>632,323</td> </tr> <tr> <td>Venezuela</td> <td>Caracas</td> <td>2,104,000</td> </tr> <tr> <td>China</td> <td>Beijing</td> <td>11,510,000</td> </tr> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
144
Result 4 – Headings:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
145
An HTML Review: Exercise XVIII: HTML Lists Theory: • The <ul> Element: A coder can use the ul element when he/she wants to start a list.
• The <li> Element: After using the ul element, an individual can use the li element to start a bullet list.
• List and Style: When a coder is using the ul element, he/she can use the style attribute to define different kinds of
styles, such as circles, squares, or none.
Practice – List:
<html>
<body>
<ul>
<li>Teraexe Trojan</li>
<li>Teraexe Keylogger</li>
<li>Teraexe Port-Scanner</li>
</ul>
</body>
</html>
Result – List:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
146
Practice – List and Style: <html> <body> <ul style="list-style-type:circle"> <li>Teraexe Trojan</li> <li>Teraexe Keylogger</li> <li>Teraexe Port-Scanner</li> </ul> <ul style="list-style-type:square"> <li>Teraexe Trojan</li> <li>Teraexe Keylogger</li> <li>Teraexe Port-Scanner</li> </ul> <ul style="list-style-type:none"> <li>Teraexe Trojan</li> <li>Teraexe Keylogger</li> <li>Teraexe Port-Scanner</li> </ul> </body> </html>
Result – List and Style:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
147
An HTML Review: Exercise XIX: Ordered HTML Lists Theory: • The <ol> Element: A coder can use the ol element when he/she wants to start a list, which is going to be
organized according to some numbers, letters, or other characters.
• Ordered HTML Lists and Type: After using the ol element, an individual can use the type attribute to define
different kinds of markers. As you can see, those are some of the most common markers that an individual can
use when he/she is using the type attribute:
o type="1": An individual can use the character “1” when he/she wants to display a list with numbers.
o type="A": An individual can use the character “A” when he/she wants to display a list with uppercase letters.
o type="a": An individual can use the character “a” when he/she wants to display a list with lowercase letters.
o type="I": An individual can use the character “I” when he/she wants to display a list with uppercase roman
numbers.
o type="i": An individual can use the character “i” when he/she wants to display a list with lowercase roman
numbers.
Practice 1 – An Ordered List:
<html>
<body>
<ol>
<li>Teraexe Trojan</li>
<li>Teraexe Keylogger</li>
<li>Teraexe Port-Scanner</li>
</ol>
</body>
</html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
148
Result 1 – An Ordered List:
Practice 2 – An Ordered List: <html> <body> <ol type="1"> <li>Teraexe Trojan</li> <li>Teraexe Keylogger</li> </ol> <ol type="A" > <li>Teraexe Trojan</li> <li>Teraexe Keylogger</li> </ol> <ol type="a"> <li>Teraexe Trojan</li> <li>Teraexe Keylogger</li> </ol> <ol type="I" > <li>Teraexe Trojan</li> <li>Teraexe Keylogger</li> </ol> <ol type="i" > <li>Teraexe Trojan</li> <li>Teraexe Keylogger</li> </ol> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
149
Practice 2 – An Ordered List:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
150
An HTML Review: Exercise XX: HTML Description Lists Theory: • The dl Element: A coder can use the dl element when he/she wants to start a description list. As you should know,
a description list is one of those lists where an individual can see a description of each item, feature, or line.
• The dt Element: After using the dl element, a coder can use the dt element to define a name or item.
• The dd element: After using the dl and dt element, a coder can use the dd element to show the description of a
name, item, or feature.
Practice – Description List: <html>
<body>
<dl>
<dt>Teraexe Port-Scanner</dt>
<dd>-Developed on PHP</dd>
<dt>Teraexe Trojan</dt>
<dd>-Developed on C++</dd>
</dl>
</body>
</html>
Result – Description List:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
151
An HTML Review: Exercise XXI: An HTML Nested List Theory: • An HTML Nested List: When a coder wants to start a nested list, he/she can use two elements, which are known
as the ul and li element. In the next exercise, you are going to learn how to develop an HTML nested list.
Practice – Nested List: <html> <body> <ul> <li>Teraexe Port-Scanner <ul> <li>Developed on PHP</li> </ul> </li> <li>Teraexe Trojan <ul> <li>Developed on C++</li> </ul> </li> </ul> </body> </html> Result – Nested List:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
152
An HTML Review: Exercise XXII: HTML Blocks Theory: • The <div> element: When a coder wants to create an HTML block, he/she can use the div element. In the next
exercise, you will learn how to create an HTML block through the div element.
• The <span> element: A coder can use the span element when he/she wants to change the color of some
characters; in other words, an individual can use the span tag to change the color of a text.
• Block-level Element: A block-level element starts a new line; in other words, a block-level element is one of
those elements that can create a line-break to start a new line. As you can see, those are some of the most
common examples of the block-level elements: h1, p, and div.
• Inline Element: An inline element is the opposite of a block-level element because those kinds of elements do not
create a line-break or start a new line. As you can see, those are some of the most common examples of the inline
elements: span, b, and img.
Practice: <html> <body> <div style="background-color:lightblue; color:red; margin:5px; padding:10px;"> <p><span style="color:blue">Socket_0x03</span> is typing inside of an HTML block.</p> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
153
An HTML Review: Exercise XXIII: HTML Blocks and Classes Theory: • HTML Blocks and Classes: When a coder is creating an HTML block, he/she can use the class attribute to define
CSS styles. Defining CSS styles for HTML blocks is a good idea if someone wants to create different kinds of
HTML blocks without typing a lot of codes.
Practice: <html> <head> <style> .teraexe { background-color:lightblue; color: red; margin: 5px; padding: 10px; } span.blue { color:blue; } </style> </head> <body> <div class="teraexe"> <p><span class="blue">Socket_0x03</span> is typing inside of an HTML block.</p> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
154
An HTML Review: Exercise XXIV: HTML Layouts Theory: • HTML Layouts: When a coder is developing an HTML document, he/she can use layouts to set different kinds of
contents inside of a section; more specifically, when an individual is developing an HTML file, he/she can use
HTML layouts to set different kinds of texts/images/buttons inside of the header/navigation-links/footer section.
In the next exercise, you will learn how to use the div element with CSS to create an HTML layout.
Practice: <html> <head> <style> #Teraexe_header { background-color: lightgreen; color: green; text-align: center; padding: 3px; } #Teraexe_nav { line-height: 20px; background-color: silver; height: 200px; width: 125px; float: left; padding: 5px; } #Teraexe_sec { width: 350px; float: left; padding: 10; } #Teraexe_footer { background-color: lightgreen;
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
155
color: green; clear: both; text-align: center; padding: 5px; } </style> </head> <body> <div id="Teraexe_header"> <h1>Teraexe</h1> </div> <div id="Teraexe_nav"> Java <br> C++ <br> PHP <br> </div> <div id="Teraexe_sec"> <h1>Java</h1> <p>The Easiest Way to Learn Java by Socket_0x03</p> </div> <div id="Teraexe_footer"> www.teraexe.com </div> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
156
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
157
An HTML Review: Exercise XXV: HTML Forms Theory: • The form Element: When an individual wants to create an HTML form, he/she can use the form element.
• The input Element: After using the form element, an individual can use the input element to define or create
different kinds of inputs; for example, an individual can use the input element to create buttons, text-fields,
checkboxes, and other inputs.
Practice 1 – Basic Input Elements: <html> <body> <form> <!-- Defining a text-field --> Text: <input type="text" name="text"> <br><br> <!-- Defining a password text-field --> Password: <input type="password" name="pass"> <br><br> <!-- Defining radio buttons --> <input type="radio" name="Teraexe" value="First-Option">First <br> <input type="radio" name="Teraexe" value="Second-Option">Second <br><br> <!-- Defining radio buttons --> <input type="checkbox" name="Teraexe2" value="First-Option">First <br> <input type="checkbox" name="Teraexe2" value="Second-Option">Second <br><br> </form> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
158
Result 1 – Basic Input Elements:
Practice 2 – Submit Button: First, you have to create the teraexe.html file
Then, you have to create the index.html file and put those codes inside of the index file:
<html> <body> <form name="input" action="teraexe.html" method="get"> Text: <input type="text" name="user"> <input type="submit" value"Submit"> </form> </body> </html> Result 2 – Submit Button:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
159
Exercise 105: PHP Forms – Sending Data through $_POST Theory: • The Action Attribute of an HTML Form: When a coder is developing an HTML form, he/she can use the action
attribute to specify the form that is going to receive data or information. For example, in the next exercise, I am
typing action=teraexe.php because I want to send data or information to the teraexe file.
• Sending Data through PHP Forms: In this exercise, you are going to learn how to use PHP and HTML to send
data or information from a PHP form to a new PHP form. Therefore, the information that you are typing inside of
a PHP form (index.php) will be displayed on a different PHP form (teraexe.php) thanks to the post method and
the $_POST superglobal variable.
• The Post method of an HTML Form: An individual can use the post method when he/she wants to send data or
information to a web-page. In the next exercise, I am using the post method on the index file because I want to
send data or information from the index file to the teraexe file.
• The $_POST Superglobal Variable: After summiting some data or information through the post method, an
individual can use the $_POST superglobal variable to collect and display data or information. As you can see in
the next source code, I am using the post method on the index.php file to send data to the teraexe.php file; then, I
am using the $_POST Superglobal variable on the teraexe file to display or show that kind of information that an
individual summited inside of the index file.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
160
Practice:
First, you have to create the index.php file; then, you have to put the next code on the index file:
<html> <body> <!--The action attribute to specify a file; the post method to send data to the teraexe file--> <form action="teraexe.php" method="post"> <!--The input element and its type attribute to create a text field--> Alias: <input type="text" name="alias"> <!--The input element and its type attribute to create a submit button--> <input type="submit" value="Submit"> </form> </body> </html> Second, you have to create the teraexe.php file and put the next source code inside of the teraexe file:
<html> <body> Your alias is: <?php print $_POST["alias"]; ?> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
161
Exercise 106: PHP Forms – Sending Data through $_GET Theory: • The $_GET Superglobal Variable: In addition to the $_POST superglobal variable, an individual can use the
$_GET superglobal variable to send data or information from a PHP form to a new PHP form. Even through an
individual can use GET and POST in a similar way, there are a few differences among those two superglobal
variables:
1) After using the $_POST superglobal variable, an individual is going to notice an URL similar to this:
http://www.website.com/teraexe.php. On the other hand, after using the $_GET superglobal variable, an
individual will notice an URL similar to this: http://www.teraexe.com/teraexe.php?alias=Socket_0x03.
2) The parameters of the $_GET superglobal variable are saved inside of a browser history because this kind of
variable uses the URL parameters to send data or information; on the other hand, the parameters of the $_POST
superglobal variable are not saved inside of a browser history because this kind of variable uses the HTTP POST
method to send data or information. Therefore, when an individual is sending sensitive information or passwords,
he/she should use the $_POST superglobal variable instead of the $_GET superglobal variable.
Practice:
First, you have to create the teraexe.php file and put the next source code inside of the teraexe file:
<html> <body> Your alias is: <?php print $_GET["alias"]; ?> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
162
Second, you have to create the index.php file; then, you have to put the next code on the index file:
<html>
<body>
<!--The get method to send data to the teraexe file-->
<form action="teraexe.php" method="get">
<!--The input element and its type attribute to create a text field-->
Alias: <input type="text" name="alias">
<!--The input element and its type attribute to create a submit button-->
<input type="submit" value="Submit">
</form>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
163
Exercise 107: PHP Forms – The PHP_SELF Parameter Theory: • The Action Attribute of an HTML Form: As previously stated, a coder can use the action attribute to specify the
form that is going to receive data or information. In the next exercise, you will learn how to use the action
attribute to include PHP codes and receive data inside of the same PHP form.
• The $_SERVER Superglobal variable: As you can see in the next source code, after using the $_SERVER
superglobal variable, a coder can use the PHP_SELF parameter when he/she wants to submit data or information
inside of the same PHP form.
Practice:
<html> <body> <form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post"> Alias: <input type="text" name="alias"> <input type="submit" name="submit" value="Submit"> </form> <?php print "Your Alias is: "; print $alias; ?> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
164
Exercise 108: PHP Forms – A Simple PHP Form Theory: • A simple PHP Form: As you can see, this is a continuation to the previous exercise. In this exercise, I am going to
use the same codes; in addition, I am going to add some codes related to the radio buttons. As previously stated,
an individual can use some radio buttons when he/she wants to display different kinds of options, so those clients
who are seeing an HTML form have to choose between two or more options.
Practice:
<html>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
Alias: <input type="text" name="alias">
<input type="submit" name="submit" value="Submit"> <br><br>
<input type="radio" name="position" value="For">For
<input type="radio" name="position" value="Against">Against
</form>
<?php
print "Your Alias is: " . $alias . "<br>";
print "Position: " . $position;
?>
</body>
</html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
165
Result:
First, you have to type an alias; then, you have to choose one of the two options:
Second, you have to click on the submit button; then, you will see an alias and a position similar to this:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
166
Exercise 109: PHP Forms – A Simple PHP Form – Part 2 Theory: • A simple PHP Form: As you can see, this is a continuation to the two previous exercises. In this exercise, I am
going to use the same codes; in addition, I am going to add some codes related to the textarea element, which is
one of those codes that an individual can use inside of the form element when he/she wants to create a comment
field.
Practice:
<html> <body> <form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post"> Alias: <input type="text" name="alias"> <input type="submit" name="submit" value="Submit"> <br><br> <input type="radio" name="position" value="For">For <input type="radio" name="position" value="Against">Against <br><br> Comment: <textarea name="comment" rows="3" cols="23"></textarea> </form> <?php print "Your Alias is: " . $alias . "<br>"; print "Position: " . $position . "<br>"; print "Comment: " . $comment . "<br>"; ?> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
167
Result:
First, you have to type an alias and choose one of the two options; then, you have to leave a comment:
Second, you have to click on the submit button; then, you will see an alias, a position, and a comment:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
168
Exercise 110: PHP – Socket Programming – Client and Server Theory: • Using the Command-Line to Run PHP Scripts: When a coder wants to run a PHP script from the command line,
he/she has to follow those steps:
o First, a coder has to edit or configure his/her php.ini, which is inside of the PHP installation folder and/or the
Windows folder (C:\Windows). After opening the php.ini, a coder has to enable the php_sockets.dll extension.
If a coder wants to enable the php_sockets.dll extension, he/she has to open the php.ini and remove a
semicolon (;) that is in the left-side of this line: extension=php_sockets.dll; then, a coder has to restart his/her
computer.
o Second, a coder has to open the command line, also known as the command prompt. Then, he/she has to go to
the php installation directory.
o Finally, a coder has to type php -f script.php. For example, if a coder wants to run a server, he/she has to type
this line: php -f server.php
• The socket_create Function: A coder can use the socket_create function when he/she wants to create a network
socket. What is a network socket? A network socket is a connection between a client and a server that can be used
to share information and/or files; furthermore, thanks to the network sockets, a client can communicate to a server
while a socket is using an IP address and a port. As you can see, this is the syntax of the socket_create function:
socket_create (protocol family, socket type, socket protocol);
a) Protocol Family: If a coder wants to start working with IP addresses and ports, he/she has to specify a protocol
family, which can be AF_INET, AF_INET6, or AF_UNIX. In the next source code, I am going to use AF_INET
because I want to use the IPv4, which is the fourth version of internet protocol (IP) that can be used by a
computer application to work with 32-bits IP addresses; for example, the IPv4 can be used by a computer
application to work with an IP address like 160.17.232.100. As you should know, AF is an abbreviation for the
Address Family, and INET is an abbreviation for Internet.
b) Socket Type: If a coder wants to start working with IP addresses and ports, he/she has to specify the type of
communication, which can be SOCK_STREAM, SOCK_DGRAM, SOCKRDM, or other. In the next source code, I
am going to use SOCK_STREAM because I want to work with some mechanism and ports, including the
transmission control protocol (TCP).
c) Socket Protocol: In this parameter, a coder may specify a socket protocol, such as TCP/UDP/ICMP. In the next
source code, I am using the value zero (0) because I want to use all those protocols that I specified in the previous
parameters of the socket_create function.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
169
• The socket_bind Function: A coder can use the socket_bind function when he/she wants to bind a socket; to
clarify, a programmer can use the socket_bind function to bind or tie a socket to a specific IP address and port. As
you can see, in the next source code of my server, I am using the socket_bind function to bind a socket to my
localhost (127.0.0.1) and the port 2323. As you can see, this is the syntax of the socket_bind function:
socket_bind (Socket, IP-Address, Port);
a) Socket: In this parameter, a coder has to include a socket, which is the socket that he/she specified in the
socket_create function. Usually, a coder has to create a variable for the socket_create function; then, he/she has to
include that variable in the field of this parameter.
b) IP-Address: In this field, a coder has to specify an address. If a coder is using the AF_INET family, he/she has to
specify an IP-address of 32-bits; for instance, a coder may specify the server IP-address, which can be 127.0.0.1,
localhost, or other.
c) Port: In this parameter, a coder has to specify a port number, such as the server port that will be open and waiting
for a connection.
• The socket_listen Function: A coder can use the socket_listen function when he/she wants to use a socket to start
listening for a connection, such as the client connection. As you can see, this is the syntax of the socket_listen
function:
socket_listen (socket, backlog);
a) Socket: In this parameter, a coder has to include a socket, which is the socket that he/she specified in the
socket_create function. Usually, a coder has to create a variable for the socket_create function; then, he/she has to
include that variable in the field of this parameter.
b) Backlog: In this parameter, a coder has to set or specify the maximum number of incoming connections. For
instance, in the next source code of my server, I specified as three (3) as the maximum number of incoming
connections.
• The socket_accept Function: After using the socket_create function, a coder has to use the socket_accept function
to start accepting incoming connections. As you can see, this is the syntax of the socket_accept function:
socket_accept (socket);
a) Socket: In this parameter, a coder has to include a socket, which is the socket that he/she specified in the
socket_create function.
• The socket_read function: The socket_read function can be used by a computer application to read a number of
characters; furthermore, a coder has to specify the maximum number of characters that the socket_read function
is going to read. As you can see, this is the syntax of the socket_read function:
socket_read (socket, character number);
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
170
a) Socket: In this parameter, a coder has to include a socket, which is the socket that he/she specified in the
socket_create function.
b) Character Number: In this field, a coder has to specify the maximum number of characters that the socket_read
function is going to read. For example, in the next source code of my server, I specify 2048 as the maximum
number of characters that the server.php application will read; therefore, when a client is sending data to my
server, he/she cannot type more than 2048 characters for each message.
• The socket_close Function: After using some functions like socket_create and socket_accept, a coder has to close
those functions using the socket_close function. For example, in the next source code of my server, there is a
variable for the socket_create function that is called AGene_VSocket, and there is a variable for the socket_accept
function that is called AG_SA_Client; hence, at the end of my server, I am using the socket_close function to close
those two variables (AG_SA_Client and AGene_VSocket). Another example is inside of the source code of my
client, where there is a variable for the socket_create function that is called AGene_VSocket, and I am closing that
function with the socket_close function. As you can see, this is the syntax of the socket_close function:
socket_close (socket);
a) Socket: In this parameter, a coder has to include one of those sockets that he/she wants to close.
• The socket_write Function: When a server is using the socket_read function to accept data or messages, a client
can use the socket_write function to start typing or writing a message that will be received by the server. As you
can see, this is the syntax of the socket_write function:
socket_write (socket, message/buffer, Character Number);
a) Socket: In this parameter, a coder has to include a socket, which is the socket that he/she specified in the
socket_create function.
b) Message/buffer: In this field, a coder has to specify a variable that is going to be related to the data that he/she
wants to send to a server. For example, in the next source code of my client, I specify the AGene_Data_to_Server
variable, which has a message that will be send to a server.
c) Character Number: In this parameter, a coder has to include the maximum number of characters that he/she wants
to send to a server. An important point about this parameter is that it is optional, so a coder may not specify
anything in this field when he/she is using the socket_write function.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
171
Practice – Server:
<?php $AGene_VSocket = socket_create(AF_INET, SOCK_STREAM, 0); $result = socket_bind($AGene_VSocket, 'localhost', 2323); $result = socket_listen($AGene_VSocket, 3); $AG_SA_Client = socket_accept($AGene_VSocket); $AG_SR_Input = socket_read($AG_SA_Client, 2048); print $AG_SR_Input; socket_close($AG_SA_Client); socket_close($AGene_VSocket); ?>
Practice – Client:
<?php $AGene_VSocket = socket_create(AF_INET, SOCK_STREAM, 0); $AGene_SC_R = socket_connect($AGene_VSocket, '127.0.0.1', 2323); $AGene_Data_to_Server = "Hi! I am the client =)"; socket_write($AGene_VSocket, $AGene_Data_to_Server); socket_close($AGene_VSocket); ?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
172
Exercise 111: PHP – Hacking Tools: Port Checker Theory: • Port Checker: A port checker is a computer application that can be used to check if a port is open or closed.
• The fsockopen Function: A coder can use the fsockopen function when he/she wants to make a connection with
other socket or host; usually, a coder has to specify a hostname/IP-address and a port. As you can see, this is the
syntax of the fsockopen function:
Fsockopen (Hostname/IP-Address, port, errno, errstr, timeout);
a) Hostname/IP-Address: In this parameter, a coder has to specify a hostname or IP-address, which is going to be the
hostname or IP-address of a server.
b) Port: In this field, a coder has to specify a port.
• The fclose Function: After using the fsockopen function, a coder can use the fclose function to close a connection
or socket.
Practice:
<?php $AGene_Test_Port = fsockopen("127.0.0.1", 21); if ($AGene_Test_Port) { print "Port 21: Open"; fclose($AGene_Test_Port); } else { print "Port 21: Closed"; } ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
173
Exercise 112: PHP – Hacking Tools: Port Scanner Theory: • Port Scanner: In the next exercise, you will learn how to develop a port scanner. As you should know, a port
scanner is a computer application that can check if different kinds of ports are open or closed.
• The error_reporting Function: A coder can use the error_reporting function to print specific errors. Furthermore,
a coder can use the error_reporting function when he/she wants to run a computer application without printing or
showing different kinds of errors; in that case, a programmer has to include the value zero (0) as one of the
parameters of the error_reporting function. If a coder wants to run an application without printing errors, he/she
has to type a line like this: error_reporting(0);.
Practice:
<?php error_reporting(0); for($AGene_Port = 21; $AGene_Port <= 23; $AGene_Port++) { $AGene_SO = fsockopen("127.0.0.1", $AGene_Port); if ($AGene_SO) { print "Open Port: $AGene_Port" . "\n"; fclose($AGene_Test_Port ); } else { print "Port Closed: $AGene_Port" . "\n"; } } ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
174
Exercise 113: PHP – Hacking Tools: HTTP Checker Theory: • HTTP Checker: In the next exercise, you will learn how to print information about an HTTP server, such as the
server name.
• The fwrite Function: As previously stated, a coder can use the fwrite function to start adding content inside of
something, such as a file or variable.
• The stream_get_contents Function: A coder can use the stream_get_contents function when he/she wants to get
the content or data of a file/variable; then, after getting the content or data of a file/variable, a programmer can
use the print function to show or print the data of a file/variable. In the next exercise, I am using the
stream_get_contents function to read and print the content of the Agene_HTTP_Checker variable.
Practice:
<?php $AGene_HTTP_Checker = fsockopen("www.teraexe.com", 80); fwrite($AGene_HTTP_Checker, "GET / HTTP/1.0 \r\n\r\n"); print stream_get_contents($AGene_HTTP_Checker); fclose($AGene_HTTP_Checker); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
175
Exercise 114: MySQL – An Introduction to the MySQL Commands Theory: • The MySQL Command Line: Also known as the MySQL Shell. An individual can use the MySQL shell to
manage his/her databases; more specifically, an individual can use the MySQL command line when he/she wants
to create/modify/organize/update/delete different kinds of databases. After installing MySQL, you can follow
those steps if you want to open the MySQL command line:
o First, you have to open the MS-DOS, also known as the Command Prompt.
o Second, you have to type this command: mysql –u root –p.
o Finally, you have to type your password.
• Creating a database: When an individual wants to create a database, he/she has to type a command similar to this:
create database database-name;. As you can see, there is a semicolon (;) at the end of the line.
• Using a database: An individual can type use database-name when he/she wants to use a database.
• Showing databases: When an individual wants to print the MySQL databases, he/she can use the MySQL shell
and type this command: show databases;.
• Dropping a database: When an individual wants to drop a database, he/she has to type a command similar to this:
drop database database-name;.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
176
Practice: After opening the MySQL command line and typing your password, you have to type those commands:
create database teraexe;
use teraexe
show databases;
drop database teraexe;
show databases;
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
177
Exercise 115: MySQL – The CREATE TABLE Statement Theory: • The CREATE TABLE Statement: After creating a database, a coder can use the CREATE TABLE statement to
create a table. In the next example, I am using the CREATE TABLE statement to create a table called
Gene_Table_A; in addition, I am using the CREATE TABLE statement to create three columns called
G_Column1, G_Column2, and G_Column3.
Practice:
After opening the MySQL command line and typing your password, you have to type those commands:
create database AGene_Database23;
use AGene_Database23
CREATE TABLE Gene_Table_A(G_Column1 VARCHAR(45),G_Column2 VARCHAR(25),G_Column3 INT);
show tables from AGene_Database23;
show columns from Gene_Table_A;
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
178
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
179
Exercise 116: MySQL – The INSERT INTO Statement Theory: • The INSERT INTO Statement: A coder can use the INSERT INTO statement when he/she wants to add some
information or data inside of a table. In the next example, I am using the INSERT INTO statement to add
information inside of the Gene_Table_A table; to put it another way, I am going to add those values to the
Gene_Table_A table: AGene_a1, AGene_a2, and 45 – AGene_b1, AGene_a2, and 25.
• Note: This is a continuation to the previous exercise; therefore, you should create a database and table using the
commands of the previous exercise; then, you can add some values to the Gene_Table_A table.
Practice: After opening the MySQL command line and typing your password, you have to type those commands:
Use AGene_Database23
INSERT INTO Gene_Table_A(G_Column1, G_Column2, G_Column3) VALUES ('AGene_a1', 'AGene_a2',45);
INSERT INTO Gene_Table_A(G_Column1, G_Column2, G_Column3) VALUES ('AGene_b1', 'AGene_a2',25);
Select * from Gene_Table_A;
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
180
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
181
Exercise 117: MySQL – The DESCRIBE Statement Theory: • The DESCRIBE Statement: A coder can use the DESCRIBE statement when he/she wants to show that kind of
information or data that is inside of a table. In the next example, I am using the DESCRIBE statement to show that
kind of information that is inside of the Gene_Table_A table.
• Note: This is a continuation to the two previous exercises; therefore, you should create a database and table using
the commands of the two previous exercises; then, you can use the DESCRIBE statement.
Practice: After opening the MySQL command line and typing your password, you have to type those commands:
use AGene_Database23
describe Gene_Table_A;
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
182
Exercise 118: MySQL – The WHERE Clause Theory: • The WHERE Clause: A coder can use the WHERE clause when he/she wants to show or print only those rows
that are related to that kind of data that a coder specified or included inside of the WHERE clause. In the next
exercise, the application will print only that kind of information that is related to the G_Column1 and AGene_b1,
so the other columns like the G_Column2 and G_Column3 will not be showed or printed because there is not
information about those columns inside of the WHERE clause.
• Note: This is a continuation to the three previous exercises; therefore, you should follow the steps of the previous
exercises before using the WHERE clause.
Practice: After opening the MySQL command line and typing your password, you have to type those commands:
use AGene_Database23
SELECT * FROM Gene_Table_A;
SELECT * FROM Gene_Table_A WHERE G_Column1='AGene_b1';
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
183
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
184
Exercise 119: MySQL – The ORDER BY Command Theory: • The ORDER BY Command: A coder can use the ORDER BY Command when he/she wants to show or print
information in ascending order. In the next exercise, the application will print information according to the order
of the G_Column3.
• Note: This is a continuation to the four previous exercises; therefore, you should follow the steps of the four
previous exercises; then, you can use the ORDER BY command.
Practice: After opening the MySQL command line and typing your password, you have to type those commands:
use AGene_Database23
SELECT * FROM Gene_Table_A;
SELECT * FROM Gene_Table_A ORDER BY G_Column3;
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
185
Exercise 120: MySQL – The UPDATE Statement Theory: • The UPDATE Statement: A coder can use the UPDATE statement when he/she wants to update that kind of
information or data that is below a column. In the next exercise, I am going to use the UPDATE statement to update a
number that is below the third column; more specifically, I am going to use the UPDATE statement to update the
number 45 to 1000.
• Note: This is a continuation to the five previous exercises; therefore, you should follow the steps of the five previous
exercises; then, you can update a number.
Practice: After opening the MySQL command line and typing your password, you have to type those commands:
use AGene_Database23
select * from Gene_Table_A;
UPDATE Gene_Table_A SET G_Column3=1000 WHERE G_Column1='AGene_a1' AND G_Column2='AGene_a2';
select * from Gene_Table_A;
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
186
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
187
Exercise 121: MySQL – The DELETE Statement Theory: • The DELETE Statement: A coder can use the DELETE statement when he/she wants to delete some rows. For
example, in the next exercise, I am going to use the DELETE statement to delete the second row that starts with the
word AGene_b1.
• Note: This is a continuation to the six previous exercises; therefore, you should follow the steps of the six previous
exercises; then, you can use the DELETE statement to delete information or data.
Practice:
After opening the MySQL command line and typing your password, you have to type those commands:
use AGene_Database23
select * from Gene_Table_A;
DELETE FROM Gene_Table_A WHERE G_Column1='AGene_b1';
select * from Gene_Table_A;
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
188
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
189
Exercise 122: MySQL – The AUTO_INCREMENT Attribute Theory: • The AUTO_INCREMENT Attribute: the AUTO_INCREMENT attribute is going to generate an ID when a new row is
added to a database. For example, in the next exercise, I am adding three values to a database, which are called Port-
Scanner, Trojan, and Antivirus; in addition, automatically, the MySQL is going to generate an ID to those three values.
More specifically, the MySQL will generate the number one for the first value (Port-Scanner), the number two for the
second value (Trojan), and the number three for the third value (Antivirus).
Practice:
After opening the MySQL command line and typing your password, you have to type those commands:
create database AGene_Database5; use AGene_Database5
CREATE TABLE Gene_Table_A ( id int(4) NOT NULL AUTO_INCREMENT, Programs CHAR(30) NOT NULL, PRIMARY KEY (id) );
INSERT INTO Gene_Table_A(Programs) VALUES ('Port-Scanner'),('Trojan'),('Antivirus');
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
190
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
191
Exercise 123: PHP & MySQL – The mysqli_connect Function Theory: • The mysqli_connect Function: When a coder wants to make a connection to a database, he/she can use the
mysqli_connect function. As you can see, this is the syntax of the mysqli_connect function:
mysqli_connect (hostname/IP-address, username, database-password, database-name);
a) Hostname/IP-Address: In this parameter, a coder has to type the hostname or IP-address of his/her database
server. If a coder is using his/her own system or computer, he/she may type localhost to connect to his/her
database. As you should know, this parameter is optional.
b) Username: In this parameter, a coder has to type the username of his/her database server; to put it another way, a
programmer has to type the MySQL username.
c) Database-Password: In this parameter, a PHP-developer who is using MySQL has to type the password of his/her
database; to clarity, a coder has to type the MySQL password.
d) Database-Name: In this parameter, a programmer has to type the name of his/her database, such as mysql or
other. If you want to see the names of your databases, you can go to this directory if you are using MySQL 5:
C:\Program Files\MySQL\MySQL Server 5.0\data. In this directory, you will see some names or folders like
mysql and test, which are the names of your databases.
• The mysqli_connect_error Function: A coder can use the mysqli_connect_error function to check a connection.
This function will print an error if there is a problem related to the connection of a database; for example, if a
coder is including a wrong username or password, this function is going to print an error. In the first exercise, I
am using right parameters to connect to my database; however, in the second exercise, I am using wrong
parameters to connect to my database, therefore, the application will print an error in the second exercise. As you
can see in the next source codes, I am checking the connection of my database with the if-statement and the
mysqli_connect_error function.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
192
Practice – Access Granted: <?php $Gene_DB=mysqli_connect("localhost","root","30303030","mysql"); // Connecting to DB if (mysqli_connect_errno()) { print mysqli_connect_error(); } ?> Result – Access Granted:
Practice – Access Denied: <?php $Gene_DB=mysqli_connect("localhost","root","23","mysql"); // Connecting to DB if (mysqli_connect_errno()) { print mysqli_connect_error(); } ?> Result – Access Denied:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
193
Exercise 124: PHP & MySQL – The mysqli_close Function Theory: • The mysqli_close Function: When a coder wants to close a connection, he/she can use the mysqli_close function.
Even though a connection is going to close automatically when a client is closing a browser or ending a script, the
mysqli_close function can be used to close a connection before closing a browser or ending a script. As you can
see, this is the syntax of the mysqli_close function:
mysqli_close ($Variable_Name);
Variable Name: In this field, a coder has to type the variable name that he/she wants to close. For example, in the
next exercise, I am going to use the mysqli_close function to close a variable that is called Gene_Variable.
Practice – Access Granted & Close Connection: <?php
$Gene_DB=mysqli_connect("localhost","root","30303030","mysql"); // Connecting to DB
if (mysqli_connect_errno())
{
print mysqli_connect_error();
}
mysqli_close ($Gene_DB);
?>
Result – Access Granted & Close Connection:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
194
Exercise 125: PHP & MySQL – The CREATE DATABASE Statement Theory: • The CREATE DATABASE Statement: A coder can use the CREATE DATABASE statement when he/she wants
to create a database. For instance, in the next exercise, I am going to use the CREATE DATABASE statement to
create a database that is called Gene_Database.
• The mysqli_query Function: When a coder is using the CREATE DATABASE statement, he/she has to use the
mysqli_query function to create his/her database.
Practice: <?php $Gene_DB=mysqli_connect("localhost","root","30303030"); // Connecting to DB if (mysqli_connect_errno()) { print mysqli_connect_error(); } $Gene_V1="CREATE DATABASE Gene_Database"; // Creating DB if (mysqli_query($Gene_DB,$Gene_V1)) { print "Database Created!"; } else { print mysqli_error($Gene_DB); } ?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
195
Result 1:
Result 2: If you are using Windows XP, MySQL 5, and PHP 5, you can go to this directory:
C:\Program Files\MySQL\MySQL Server 5.0\data.
Then, you will see this folder or database: gene_database.
Result 3: In the MySQL Command Line, you can type show databases;
Then, you will see the names of your databases, including the gene_database.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
196
Exercise 126: PHP & MySQL – The CREATE TABLE Statement Theory: • The CREATE TABLE Statement: A coder can use the CREATE TABLE statement when he/she wants to create a
table. In the next example, I am using the CREATE TABLE statement to create a table called Gene_Table_A; in
addition, I am using the CREATE TABLE statement to create three columns called G_Column1, G_Column2, and
G_Column3.
• Note: This is a continuation to the previous exercise; therefore, you should create a database using the source
code of the previous exercise; then, you can use the next source code to create a table.
Practice:
<?php // Connecting to DB $Gene_DB=mysqli_connect("localhost","root","30303030","gene_database"); if (mysqli_connect_errno()) { print mysqli_connect_error(); } // Creating Table $Gene_V1="CREATE TABLE Gene_Table_A(G_Column1 CHAR(45),G_Column2 CHAR(25),G_Column3 INT)"; if (mysqli_query($Gene_DB,$Gene_V1)) { print "Table Created!"; } else { print mysqli_error($Gene_DB); } ?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
197
Result 1:
Result 2:
As previously stated, if you are using Windows XP, MySQL 5, and PHP 5, you can go to this directory:
C:\Program Files\MySQL\MySQL Server 5.0\data\gene_database.
Then, you will see this table: gene_table_a.frm.
Result 3:
In the MySQL Command Line, you can type those commands:
use gene_database
show tables from gene_database;
show columns from gene_table_a;
Then, you will see the table and columns of gene_database.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
198
Exercise 127: PHP & MySQL – The INSERT INTO Statement Theory: • The INSERT INTO Statement: A coder can use the INSERT INTO statement when he/she wants to add some
information or data inside of a table. In the next example, I am using the INSERT INTO statement to add
information inside of the Gene_Table_A table; to put it another way, I am going to add those values to the
Gene_Table_A table: AGene_a1, AGene_a2, and 45 – AGene_b1, AGene_a2, and 25.
• Note: This is a continuation to the two previous exercises; therefore, you should create a database and table using
the source codes of the two previous exercises; then, you can use the next source code to add some values to the
Gene_Table_A table.
Practice:
<?php //Connecting to DB $Gene_DB=mysqli_connect("localhost","root","30303030","gene_database"); if (mysqli_connect_errno()) { print mysqli_connect_error(); } // Adding Data to columns mysqli_query($Gene_DB,"INSERT INTO Gene_Table_A(G_Column1, G_Column2, G_Column3) VALUES ('AGene_a1', 'AGene_a2',45)"); mysqli_query($Gene_DB,"INSERT INTO Gene_Table_A(G_Column1, G_Column2, G_Column3) VALUES ('AGene_b1', 'AGene_a2',25)"); mysqli_close($Gene_DB); ?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
199
Result 1:
Result 2:
In the MySQL Command Line, you can type those commands:
use gene_database
select * from gene_table_a;
Then, you will see the table and columns of gene_database.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
200
Exercise 128: PHP & MySQL – The SELECT Statement Theory: • The SELECT Statement: A coder can use the SELECT statement when he/she wants to select some information or
data from a database/table. In the next example, I am using the SELECT statement to select or choice data from a
table that is called Gene_Table_A; to put it another way, I am going to use the SELECT statement to choice the
values of the Gene_Table_A table, which are AGene_a1, AGene_a2, and 45 – AGene_b1, AGene_a2, and 25.
• The mysqli_fetch_array Function: A coder can use the mysqli_fetch_array function when he/she wants to interact
with those kinds of values that are inside of a database; more specifically, a programmer can use the
mysqli_fetch_array function when he/she wants to print or show those values that are inside of a table. Hence, in
the next exercise, I am going to use the mysqli_fetch_array to print those kinds of values that are inside of the
Gene_Table_A table, which are AGene_a1, AGene_a2, and 45 – AGene_b1, AGene_a2, and 25.
• Note: This is a continuation to the three previous exercises; therefore, you should follow the steps of the three
previous exercises; then, you can use the next source code to use the SELECT statement.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
201
Practice:
<?php
//Connecting to DB
$Gene_DB=mysqli_connect("localhost","root","30303030","gene_database");
if (mysqli_connect_errno())
{
print mysqli_connect_error();
}
// The Select From Statement
$Gene_Return = mysqli_query($Gene_DB,"SELECT * FROM Gene_Table_A");
while($Gene_Show_Row = mysqli_fetch_array($Gene_Return))
{
print $Gene_Show_Row['G_Column1'] . " ";
print $Gene_Show_Row['G_Column2'] . " ";
print $Gene_Show_Row['G_Column3'] . " ";
print "<br>";
}
?>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
202
Exercise 129: PHP & MySQL – The WHERE Clause Theory: • The WHERE Clause: A coder can use the WHERE clause when he/she wants to show or print only those rows
that are related to that kind of data that a coder specified or included inside of the WHERE clause. In the next
exercise, the application will print only that kind of information that is related to the G_Column1 and AGene_b1,
so the other columns like the G_Column2 and G_Column3 will not be showed or printed because there is not
information about those columns inside of the WHERE clause.
• Note: This is a continuation to the four previous exercises; therefore, you should follow the steps of the four
previous exercises; then, you can use the next source code to use the WHERE clause.
Practice: <?php //Connecting to DB $Gene_DB=mysqli_connect("localhost","root","30303030","gene_database"); if (mysqli_connect_errno()) { print mysqli_connect_error(); } // The Select-From Statement and The Where Clause $Gene_Return = mysqli_query($Gene_DB,"SELECT * FROM Gene_Table_A WHERE G_Column1='AGene_b1'"); while($Gene_Show_Row = mysqli_fetch_array($Gene_Return)) { print $Gene_Show_Row['G_Column1'] . " "; print $Gene_Show_Row['G_Column2'] . " "; print $Gene_Show_Row['G_Column3'] . " "; print "<br>"; } ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
203
Exercise 130: PHP & MySQL – The ORDER BY Command Theory: • The ORDER BY Command: A coder can use the ORDER BY Command when he/she wants to show or print
information in ascending order. In the next exercise, the application will print information according to the order
of the G_Column3.
• Note: This is a continuation to the five previous exercises; therefore, you should follow the steps of the five
previous exercises; then, you can use the next source code to use the ORDER BY command.
Practice: <?php //Connecting to DB $Gene_DB=mysqli_connect("localhost","root","30303030","gene_database"); if (mysqli_connect_errno()) { print mysqli_connect_error(); } // The Select-From Statement and The Order-by Command $Gene_Return = mysqli_query($Gene_DB,"SELECT * FROM Gene_Table_A ORDER BY G_Column3"); while($Gene_Show_Row = mysqli_fetch_array($Gene_Return)) { print $Gene_Show_Row['G_Column1'] . " "; print $Gene_Show_Row['G_Column2'] . " "; print $Gene_Show_Row['G_Column3'] . " "; print "<br>"; } ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
204
Exercise 131: PHP & MySQL – The UPDATE Statement
Theory: • The UPDATE Statement: A coder can use the UPDATE statement when he/she wants to update that kind of
information or data that is below a column. In the next exercise, I am going to use the UPDATE statement to
update a number that is below the third column; more specifically, I am going to use the UPDATE statement to
update the number 45 to 1000.
• Note: This is a continuation to the six previous exercises; therefore, you should follow the steps of the six
previous exercises; then, you can use the next source code to update a number.
Practice:
<?php //Connecting to DB $Gene_DB=mysqli_connect("localhost","root","30303030","gene_database"); if (mysqli_connect_errno()) { print mysqli_connect_error(); } // The UPDATE Statement mysqli_query($Gene_DB,"UPDATE Gene_Table_A SET G_Column3=1000 WHERE G_Column1='AGene_a1' AND G_Column2='AGene_a2'"); mysqli_close($Gene_DB); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
205
Exercise 132: PHP & MySQL – The DELETE Statement Theory: • The DELETE Statement: A coder can use the DELETE statement when he/she wants to delete some rows. For
example, in the next exercise, I am going to use the DELETE statement to delete the second row that starts with
the word AGene_b1.
• Note: This is a continuation to the seven previous exercises; therefore, you should follow the steps of the seven
previous exercises; then, you can use the next source code to delete information or data.
Practice: <?php //Connecting to DB $Gene_DB=mysqli_connect("localhost","root","30303030","gene_database"); if (mysqli_connect_errno()) { print mysqli_connect_error(); } // The DELETE Statement mysqli_query($Gene_DB,"DELETE FROM Gene_Table_A WHERE G_Column1='AGene_b1'"); mysqli_close($Gene_DB); ?> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
206
Exercise 133: PHP & MySQL – The MYSQL_NUM_ROWS Function Theory: • The MYSQL_NUM_ROWS Function: A coder can use the MYSQL_NUM_ROWS function when he/she wants to
print or see the number of rows that is inside of a database. In the next exercise, I am going to use the MySQL
command line to create a database and a table; then, I am going to insert some information or data inside of a
table. After inserting some information inside of a table, I am going to create a PHP script to see and print the
number of rows through the MYSQL_NUM_ROWS function.
Practice: After opening the MySQL command line and typing your password, you have to type those commands:
create database AGene_Database28;
use AGene_Database28
CREATE TABLE Gene_Table_A(G_Column1 VARCHAR(45),G_Column2 VARCHAR(25),G_Column3 INT);
INSERT INTO Gene_Table_A(G_Column1, G_Column2, G_Column3) VALUES ('AGene_a1', 'AGene_a2',45);
INSERT INTO Gene_Table_A(G_Column1, G_Column2, G_Column3) VALUES ('AGene_b1', 'AGene_a2',25);
Then, you have to create the index.php file and put those codes inside of the index file: <?php
mysql_connect("localhost", "root", "30303030");
mysql_select_db("agene_database28");
$result = mysql_query("SELECT * FROM Gene_Table_A");
$AGene_Number_of_Rows = mysql_num_rows($result);
print "This is the number of rows: " . $AGene_Number_of_Rows;
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
207
Result - 1:
Result - 2:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
208
Exercise 134: PHP & MySQL – The MYSQL_FETCH_ARRAY Function Theory: • The MYSQL_FETCH_ARRAY Function: A coder can use the mysql_fetch_array function when he/she wants to
print or see the rows that are inside of a database. In the next exercise, I am going to use the MySQL command
line to create a database and a table; then, I am going to insert some information or data inside of a table. After
inserting some information inside of a table, I am going to create a PHP script to see and print the rows through
the mysql_fetch_array function.
• Syntax: As you can see, this is the syntax of the mysql_fetch_array function:
mysqli_fetch_array(first-parameter, second-parameter);
First-Parameter: the first parameter is required. When a coder is using the mysql_query function, he/she can
obtain its result inside of a variable; then, after obtaining the mysql_query result inside of a variable, a coder has
to type that variable on the first parameter of the mysql_fetch_array function.
Second-Parameter: The second parameter is optional. In this field, a coder may specify some of the ways that the
mysql_fetch_array function is going to display its array or rows; to put it another way, in this parameter, a coder
may specify how the mysql_fetch_array function is going to fetch the result of a row. As you can see, those are
some of the options that a coder can use on the second parameter of the mysql_fetch_array function:
� MYSQLI_ASSOC: An Associative array.
� MYSQLI_NUM: A numerical array.
� MYSQLI_BOTH: An associative and numerical array.
An important point that a coder should know about the mysql_fetch_array function is that he/she can use the
while statement when he/she wants to print a lot of rows. In the next source code, you will see how we can use the
the mysql_fetch_array function with the while statement to display some rows.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
209
Practice: After opening the MySQL command line and typing your password, you have to type those commands:
create database AGene_Database29;
use AGene_Database29
CREATE TABLE Gene_Table_A(G_Column1 VARCHAR(45),G_Column2 VARCHAR(25),G_Column3 INT);
INSERT INTO Gene_Table_A(G_Column1, G_Column2, G_Column3) VALUES ('AGene_a1', 'AGene_a2',10);
INSERT INTO Gene_Table_A(G_Column1, G_Column2, G_Column3) VALUES ('AGene_b1', 'AGene_b2',20);
Then, you have to create the index.php file and put those codes inside of the index file: <?php $Gene_DB = mysql_connect("localhost","root","30303030"); $sql = 'SELECT G_Column1, G_Column2, G_Column3 FROM Gene_Table_A'; mysql_select_db('agene_database29'); $Gene_Result = mysql_query( $sql, $Gene_DB ); if($Gene_Result) { while($row = mysql_fetch_array($Gene_Result, MYSQL_ASSOC)) { print "{$row['G_Column1']} <br> "; print "{$row['G_Column2']} <br> "; print "{$row['G_Column3']} <br> "; print "<hr>"; } } ?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
210
Result - 1:
Result - 2:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
211
A JavaScript Review
Before learning how to develop a PHP project, I am going to provide a review of JavaScript because this
computer programming language can be used with PHP to develop different kinds of web-applications. To put it
another way, sometimes, when an individual is developing a PHP project, he/she has to use PHP with other
languages, such as HTML, CSS, and JavaScript; therefore, I am going to provide a summary of JavaScript before
developing some PHP projects.
JavaScript – Exercise I: Changing the Content of an HTML Element Theory: • Changing the Content of an HTML Element: When an individual is developing an HTML document, he/she can
use JavaScript codes to change the content of an HTML element.
• The document.getElementById() Function: When a coder wants to change the content of an HTML element,
he/she can use the document.getElementById() function. Before using the document.getElementById() function,
a programmer has to use the ID attribute to specify an unique ID; then, he/she has to type an ID name as an
element of document.getElementById. As you can see, this is the syntax of the document.getElementById()
function:
document.getElementById(ID-Name)
ID-Name: In this parameter, a coder has to specify an ID value. In other words, after using the ID attribute to
specify an unique ID, a programmer has to type an ID name as an element of the document.getElementById()
function. For example, in the next exercise, after using the p element, I am using the ID attribute to define the
AGene ID; then, I am using the AGene ID as an element of the document.getElementById() function.
• The innerHTML Property: After using the document.getElementById() function, a coder has to use the
innerHTML property to change the content of an HTML element, such as the p element, the h element, and other
elements. If you want to change the content of an HTML element, you can use the next syntax:
document.getElementById(ID-Name).innerHTML = "The new content of an HTML element";
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
212
Practice: <html>
<body>
<button type="button" onclick="AGene_Function()">Button</button>
<p id="AGene">Using the p element to type a paragraph.</p>
<script>
function AGene_Function()
{
document.getElementById("AGene").innerHTML = "Changing the p element content.";
}
</script>
</body>
</html>
Result: First, you have to open the index file:
After clicking on the button, you will see a result similar to this:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
213
JavaScript – Exercise II: Changing the Value of an HTML Attribute Theory: • Changing the Value of an HTML Attribute: When an individual is developing an HTML document, he/she can
use JavaScript codes to change the value of an HTML attribute.
• The document.getElementById() Function: When a coder wants to change the value of an HTML attribute, he/she
can use the document.getElementById() function.
• Using HTML Attributes: After using the document.getElementById() function, a coder has to type an HTML
attribute to change the value of an attribute. If you want to change the value of an HTML attribute, you can use
the next syntax:
document.getElementById(ID-Name).HTML-Attribute = "New-Value";
HTML-Attribute: In this parameter, a coder has to type an HTML attribute. For example, in the next exercise, I
am using the src attribute to change the value of an image; in other words, I am using the src property of an img
element because I want to display or see a different image.
New-Value: In this parameter, a coder has to type a new value, such as a new image. For example, in the next
exercise, I am typing Teraexe.bmp because I want to display or see the Teraexe image instead of the picture
image.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
214
Practice: First, you have to create the Picture image.
Second, you have to create the Teraexe Image.
Finally, you have to create the index.php file and put those codes inside of the index file:
<html>
<body>
<img id="AGene_Picture" src="picture.bmp">
<script>
document.getElementById("AGene_Picture").src = "Teraexe.bmp";
</script>
</body>
</html>
Result: As you can see, the application will show the Teraexe image instead of the picture image:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
215
JavaScript – Exercise III: Changing the Style of an HTML Element Theory: • Changing the Style of an HTML Element: In the next exercise, you will learn how to use JavaScript to change the
style of an HTML document; in other words, you are going to learn how to use JavaScript to change the CSS
style of a website, such as its color/fontsize/fontFamily/border.
• The document.getElementById() Function: As previously stated, when a coder wants to change the value of an
HTML element, he/she can use the document.getElementById() function. As you can see, this is the syntax of the
document.getElementById() function to change the style of an HTML element:
document.getElementById(ID-Name).HTML-Style = "New-Value";
HTML-Style: In this parameter, a coder has to type an HTML style; for example, a coder may type some of those
HTML styles: style.color, style.fontSize, style.fontFamily, and style.border.
o The style.color property: A coder can use this property to change the color of a character.
o The style.fontSize property: A coder can use this property to change the size of a character.
o The style.fontFamily property: A coder can use this property to change the font-face of a character.
o The style.border property: A coder can use this property when he/she wants to include some borders.
New-Value: In this parameter, a coder has to type a new value, such as a new color/size/font-face.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
216
Practice: <html> <body> <button type="button" onclick="AGene_Function()">Button</button> <p id="AGene">Using the p element to type a paragraph.</p> <script> function AGene_Function() { document.getElementById("AGene").style.color = "blue"; document.getElementById("AGene").style.fontSize = "23px"; document.getElementById("AGene").style.fontFamily = "Monotype Corsiva"; document.getElementById("AGene").style.border = "3px solid"; } </script> </body> </html> Result: First, you have to open your index.php file:
Then, after clicking on the Button, you will see a result similar to this:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
217
JavaScript – Exercise IV: Declaring Variables Theory: • Variables: When a coder is developing a computer application, he/she can use variables to store different kinds of
values or numbers.
• JavaScript Variables: A coder can use the var command when he/she wants to declare a JavaScript variable. In the
next exercise, I am declaring the Teraexe_A variable with a value of eighty-six (86); then, I am using the
document.getElementById() function to print or show the value of Teraexe_A.
• Comments: When a coder wants to add some comments to his/her JavaScript codes, he/she can use the double-
slash symbol (//).
Practice:
<html> <body> <p id="AGene1"></p> <p id="AGene2"></p> <p id="AGene3"></p> <script> var Teraexe_A = 86; var Teraexe_B = "Socket_0x03"; var x =11; var y = 12; document.getElementById("AGene1").innerHTML = Teraexe_A; // Printing a number document.getElementById("AGene2").innerHTML = Teraexe_B; // Printing Text document.getElementById("AGene3").innerHTML = x + y; // Variables & Arithmetic Operators </script> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
218
JavaScript – Exercise V: JavaScript Arrays Theory: • JavaScript Arrays: When an individual is developing an HTML document, he/she can use JavaScript codes to
declare or create different kinds of arrays. As previously stated, a coder can use an array to hold the values of a
variable. In the next exercise, I am declaring or creating an array that is known as Teraexe_Software; furthermore,
I am using the Teraexe_Software array to hold the values of three elements, which are called Trojan, Antivirus,
and Firewall. As you can see in the next source code, I am using the value zero (0) to print or show the first value
(Trojan) of an array because the arrays of JavaScript are zero-based; therefore, if a coder wants to print or show
the second value of an array, he/she has to type one (1).
Practice:
<html> <body> <p id="AGene"></p> <script> var Teraexe_Softwares = ["Trojan","Antivirus","Firewall"]; document.getElementById("AGene").innerHTML = Teraexe_Softwares[0]; </script> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
219
JavaScript – Exercise VI: JavaScript Objects Theory: • JavaScript Objects: When a coder is developing an HTML document, he/she can use JavaScript codes to define or
create different kinds of objects.
Practice:
<html> <body> <p id="AGene1"></p> <p id="AGene2"></p> <p id="AGene3"></p> <script> var Teraexe_Products = {Pen:"23 dollars.", Keyboard:"25 dollars.", PC:"30 dollars."}; document.getElementById("AGene1").innerHTML = "The pendrive cost is: " + Teraexe_Products.Pen; document.getElementById("AGene2").innerHTML = "The keyboard cost is: " + Teraexe_Products["Keyboard"]; document.getElementById("AGene3").innerHTML = "The computer cost is: " + Teraexe_Products.PC; </script> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
220
JavaScript – Exercise VII: JavaScript Function Theory: • JavaScript Function: When a coder is developing an HTML document, he/she can use JavaScript codes to create
different kinds of functions. What is a JavaScript function? A JavaScript function is a code or group of codes that
can be invoked or called by a coder to perform different kinds of tasks. As you can see, this is the syntax of a
JavaScript function:
Function-Name (First-Parameter, Second-Parameter, Third-Parameter) { Codes of a Function }
Function-Name: In this field, a coder has to type the name of a function. For example, in the next exercise, I am
typing AGene_Function because that is the name that I choose for my function.
First-Parameter: After typing the name of a function, a coder has to type a parameter-name among parenthesis.
Furthermore, if a coder wants to type other parameters, he/she has to use a comma (,). For example, in the next
source code, I am using a comma to separate those parameters: Teraexe_A, Teraexe_B, and Teraexe_C.
Function Codes: When a function is called or invoked, the function is going to execute those kinds of codes that
are inside of a function. For example, in the next exercise, after the AGene_Function function is invoked, this
function returns the addition of three elements or parameters, which are known as Teraexe_A, Teraexe_B, and
Teraexe_C. To put it another way, the AGene_Function function returns the value of 86 because this function is
adding three elements or parameters.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
221
Practice:
<html>
<body>
<p id="AGene"></p>
<script>
function AGene_Function(Teraexe_A, Teraexe_B, Teraexe_C)
{
return Teraexe_A + Teraexe_B + Teraexe_C;
}
document.getElementById("AGene").innerHTML = AGene_Function(40, 23, 23);
</script>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
222
JavaScript – Exercise VIII: Functions and Variable Scope Theory: • Functions and Variable Scope: The location or area of a variable is called variable scope. Some of the most
important variable scopes that a coder can use when he/she is programming in JavaScript are known as local and
global. On the one hand, a local scope variable is one of those variables that a coder has been defined and used
inside of a function; on the other hand, a global scope variable is one of those variables that a coder has been
defined and used outside of a function. In the first exercise, I am going to develop a computer application with a
local scope variable; then, in the second exercise, I will develop an application with a global scope variable.
Practice – First Exercise:
<html> <body> <p id="AGene"></p> <script> function Teraexe_Function() { var Pendrive = "86 dollars."; return Pendrive; } document.getElementById("AGene").innerHTML = Teraexe_Function(); </script> </body> </html> Result – First Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
223
Practice – Second Exercise:
<html>
<body>
<p id="AGene"></p>
<script>
var Pendrive = "86 dollars.";
Teraexe_Function()
function Teraexe_Function()
{
document.getElementById("AGene").innerHTML = Pendrive;
return Pendrive;
}
</script>
</body>
</html>
Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
224
JavaScript – Exercise IX: Variables and Arithmetic Operators Theory: • Variables and Arithmetic Operators: In the next exercise, you will see how to use variables with some of the most
important arithmetic operators, such as addition, subtraction, multiplication, and others.
Practice:
<html> <body> <h1>Number 46 & 40</h1> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <p id="AGene3"></p> <p id="AGene4"></p> <p id="AGene5"></p> <script> function Teraexe_Function() { var AGene_A = 46; var AGene_B = 40; var Addition = AGene_A + AGene_B; var Subtraction = AGene_A - AGene_B; var Multiplication = AGene_A * AGene_B; var Division = AGene_A / AGene_B; var Division_Remainder = AGene_A % AGene_B; document.getElementById("AGene1").innerHTML = "Addition: " + Addition; document.getElementById("AGene2").innerHTML = "Subtraction: " + Subtraction; document.getElementById("AGene3").innerHTML = "Multiplication: " + Multiplication; document.getElementById("AGene4").innerHTML = "Division: " + Division; document.getElementById("AGene5").innerHTML = "Division Remainder: " + Division_Remainder; } </script> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
225
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
226
JavaScript – Exercise X: The Date Object Theory: • The Date Object: In the next exercise, you will learn how to use the date object of JavaScript to display the
current date of a computer; in other words, you are going to learn how to create a computer application that is
going to print the current hour, day, month, and year. In the first exercise, I am going to use the date object to
display the current date inside of the p element; then, in the second exercise, I am going to use the date object to
display the current date through an HTML button.
Practice – First Exercise:
<html>
<body>
<p id="AGene"></p>
<script>
document.getElementById("AGene").innerHTML = Date();
</script>
</body>
</html>
Result – First Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
227
Practice – Second Exercise:
<html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
document.getElementById("AGene").innerHTML = Date();
}
</script>
</body>
</html>
Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
228
JavaScript – Exercise XI: The Date-Get-Methods of JavaScript Theory: • The Date-Methods of JavaScript: A coder can use the JavaScript Date-Methods like getHours() when he/she
wants to print or show only a particular portion of a date, such as a millisecond, second, day, hour, month, or
year. Before using the JavaScript Date-Methods, a coder has to use the “new Date()” function; for example, if a
coder wants to print or show the current hour of a computer through the getHours() function, he/she has to type a
line similar to this: new Date().getHours(). As you can see, those are some of the most common Date-Methods of
JavaScript:
1) getDate(): A coder can use the getDate function when he/she wants to print the day of a month (1-31).
2) getDay(): A coder can use the getDay function when he/she wants to print the day of a week (0-6). When a coder
is using this function, Sunday is equivalent to zero (0), Monday is equivalent to one (1), and so on.
3) getFullYear(): A coder can use the getFullYear function when he/she wants to print a year, such as 2014.
4) getHours(): A coder can use the getHours function when he/she wants to print the current hour (0-23).
5) getMilliseconds(): A coder can use the getMilliseconds function when he/she wants to print the current
milliseconds from 0 to 999.
6) getMinutes(): A coder can use the getMinutes function when he/she wants to print or show the current minutes of
a computer (0-59)
7) getMonth(): A coder can use the getMonth function when he/she wants to print or show the current month of a
computer (0-11).
8) getSeconds(): A coder can use the getSeconds function when he/she wants to print or show the current seconds of
a computer (0-59).
9) getTime(): A coder can use the getTime function when he/she wants to print or show the current time in
milliseconds since 01/01/1979.
One of the best ways to understand how to use the Date-Methods of JavaScript is seeing an exercise or source
code; therefore, you should see the next exercise or source code if you want to understand more about the Date-
Methods of JavaScript.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
229
Practice:
<html>
<body>
<p id="AGene1"></p>
<p id="AGene2"></p>
<p id="AGene3"></p>
<p id="AGene4"></p>
<p id="AGene5"></p>
<p id="AGene6"></p>
<p id="AGene7"></p>
<p id="AGene8"></p>
<p id="AGene9"></p>
<script>
document.getElementById("AGene1").innerHTML = "1. Day (1-31): " + new Date().getDate();
document.getElementById("AGene2").innerHTML = "2. WeekDay (0-6): " + new Date().getDay();
document.getElementById("AGene3").innerHTML = "3. Full-Year: " + new Date().getFullYear();
document.getElementById("AGene4").innerHTML = "4. Hour (0-23): " + new Date().getHours();
document.getElementById("AGene5").innerHTML = "5. Milliseconds (0-999): " + new Date().getMilliseconds();
document.getElementById("AGene6").innerHTML = "6. Minutes (0-59): " + new Date().getMinutes();
document.getElementById("AGene7").innerHTML = "7. Month (0-11): " + new Date().getMonth();
document.getElementById("AGene8").innerHTML = "8. Seconds (0-59): " + new Date().getSeconds();
document.getElementById("AGene9").innerHTML = "9. Time: " + new Date().getTime();
</script>
</body>
</html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
230
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
231
JavaScript – Exercise XII: The Date-Set-Methods of JavaScript Theory: • The Date-Set-Methods of JavaScript: A coder can use the Date-Set-Methods of JavaScript when he/she wants to
set a particular time. As you can see, those are some of the most common Date-Set-Methods of JavaScript:
1) setDate(): A coder can use the setDate function when he/she wants to set the day of a month (1-31).
2) setFullYear(): A coder can use the setFullYear function when he/she wants to set a year, such as 1986.
3) setHours(): A coder can use the setHours function when he/she wants to set the current hour (0-23).
4) setMilliseconds(): A coder can use the setMilliseconds function when he/she wants to set the current
milliseconds from 0 to 999.
5) setMinutes(): A coder can use the setMinutes function when he/she wants to set the current minutes (0-59).
6) setMonth(): A coder can use the setMonth function when he/she wants to set the current month (0-11).
7) setSeconds(): A coder can use the setSeconds function when he/she wants set the current seconds (0-59).
8) setTime(): A coder can use the setTime function when he/she wants to set the current time in milliseconds
since 01/01/1979.
One of the best ways to understand how to use the Date-Set-Methods of JavaScript is seeing an exercise or source
code; therefore, you should see the next exercise or source code if you want to understand more about the Date-Set-
Methods of JavaScript.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
232
Practice – First Exercise:
Using the setDate function to set the day of a month:
<html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
var AGene_Variable = new Date();
AGene_Variable.setDate(20);
document.getElementById("AGene").innerHTML = AGene_Variable;
}
</script>
</body>
</html>
Result – First Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
233
Practice – Second Exercise:
Using the setFullYear function to set a year:
<html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
var AGene_Variable = new Date();
AGene_Variable.setFullYear(1986, 4, 20);
document.getElementById("AGene").innerHTML = AGene_Variable;
}
</script>
</body>
</html>
Result – Second Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
234
Practice – Third Exercise:
Using the setHours function to set an hour:
<html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
var AGene_Variable = new Date();
AGene_Variable.setHours(7);
document.getElementById("AGene").innerHTML = AGene_Variable;
}
</script>
</body>
</html>
Result – Third Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
235
Practice – Fourth Exercise:
Using the setMinutes function to set a minute:
<html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
var AGene_Variable = new Date();
AGene_Variable.setMinutes(28);
document.getElementById("AGene").innerHTML = AGene_Variable;
}
</script>
</body>
</html>
Result – Fourth Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
236
Practice – Fifth Exercise:
Using the setMonth function to set a month:
<html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
var AGene_Variable = new Date();
AGene_Variable.setMonth(4);
document.getElementById("AGene").innerHTML = AGene_Variable;
}
</script>
</body>
</html>
Result – Fifth Exercise:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
237
JavaScript – Exercise XIII: Conditional Operator – The If Statement Theory: • The If-Statement: If something is true, the application will print an instruction. In the next example, if the AGene
variable is less than the AGene_B variable, the application will print a message. As you can see, this is the syntax
of the if-Statement:
if-statement (condition) { //A code will be executed if a condition if true. }
Practice: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene"></p> <script> function Teraexe_Function() { var AGene_A = 5; var AGene_B = 10; if (AGene_A < AGene_B) { document.getElementById("AGene").innerHTML = "AGene_A is less than AGene_B."; } } </script> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
238
JavaScript – Exercise XIV: Conditional Operator – The else Statement Theory: • The else Statement: If something is true, the computer application will print an instruction or code; on the other
hand, if something is not true, the computer application is going to print other instruction or code. In the next
example or source code, if the AGene variable is less than the AGene_B variable, the computer application will
print a message, in other words, the computer application is going to print AGene_A is less than AGene_B;
howerver, if the AGene variable is more than the AGene_B variable, the computer application will print a
message, in other words, the computer application is going to print AGene_A is more than AGene_B. As you can
see, this is the syntax of the if-else Statement:
if-statement (condition)
{
//A code will be executed if a condition if true.
}
else
{
//A code will be executed if a condition if not true.
}
One of the best ways to understand the functionality of the else statement is seeing an example or a source
code; therefore, I am going to provide an example of the else-if statement in the next source code.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
239
Practice: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene"></p> <script> function Teraexe_Function() { var AGene_A = 20; var AGene_B = 10; if (AGene_A < AGene_B) { document.getElementById("AGene").innerHTML = "AGene_A is less than AGene_B."; } else { document.getElementById("AGene").innerHTML = "AGene_A is more than AGene_B."; } } </script> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
240
JavaScript – Exercise XV: Conditional Operator – The else-if Statement Theory: • The else-if Statement: If something is true, the application will print an instruction through the if-statement.
However, if something is not true, the computer application will use the else-if statement to check a condition;
then, if something is true, the else-if statement will print an instruction. On the other hand, if something is not
true, the computer application will continue checking through different kinds of else-if statement, or it may
continue checking through a final else-statement. As you can see, this is the syntax of the else-if statement:
if-statement (condition)
{
//A code will be executed if a condition if true.
}
else-if statement (condition)
{
//A code will be executed if a condition if not true.
}
else
{
//A code will be executed if the previous condition was not true.
}
One of the best ways to understand the functionality of the else-if statement is seeing an example or a source
code; therefore, I am going to provide an example of the else-if statement in the next source code.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
241
Practice: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene"></p> <script> function Teraexe_Function() { var AGene_A = 10; var AGene_B = 10; if (AGene_A < AGene_B) { document.getElementById("AGene").innerHTML = "AGene_A is less than AGene_B."; } else if (AGene_A < AGene_B) { document.getElementById("AGene").innerHTML = "AGene_A is more than AGene_B."; } else { document.getElementById("AGene").innerHTML = "AGene_A is egual to AGene_B."; } } </script> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
242
JavaScript – Exercise XVI: The Switch Statement Theory: • The Switch Statement: When a coder wants to develop a computer application that can be used by a client to
choose different kinds of alternatives or options, he/she can use the switch statement. As you can see, this is the
syntax of the switch statement:
switch (the codes that a coder wants to evaluate or test)
{
case first-number
// The Codes that will be executed if the previous case is true or match.
Break;
case second-number
// The Codes that will be executed if the previous case is true or match.
Break;
case default
// The Codes that will be executed if the previous cases are not true or do not match.
Break;
}
One of the best ways to understand the functionality of the switch statement is seeing an example or a source
code; therefore, I am going to provide an example of the switch statement in the next source code.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
243
Practice: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene"></p> <script> function Teraexe_Function() { var Teraexe_Products = 2; switch (2) { case 1: Teraexe_Products = "1"; Teraexe_Products = "Pendrive: $100 dollars."; break; case 2: Teraexe_Products = "2"; Teraexe_Products = "Laptop: $300 dollars."; break; case 3: Teraexe_Products = "3"; Teraexe_Products = "Desktop: $500 dollars."; break; default: Teraexe_Products = "The store does not have that product!"; break; } document.getElementById("AGene").innerHTML = Teraexe_Products; } </script> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
244
JavaScript – Exercise XVII: Comparison Operators Theory: • Comparison Operators: A coder can use the comparison operators to test if something is true or false. As you can
see, those are some of the most common comparison operators:
1) The Equal Operator (==): A coder can use this operator to test if two variables have the same value.
2) The Identical Operator (===): A coder can use this operator to test if two variables are identical, in other words, a
coder can use this operator to test if two variables have the same value and are of the same type.
3) The Not Equal Operator (!=): A coder can use this operator to test if a variable is not equal to other.
4) The Not Identical (!==): A coder can use this operator to test if two variables are not identical.
5) The Greater Than Operator (>): A coder can use this operator to test if a variable is greater than other variable.
6) The Less Than Operator (<): A coder can use this operator to test if a variable is less than other variable.
7) The Greater Than or Equal to Operator (>=): A coder can use this operator to test if a variable is greater than or
equal to other variable.
8) The Less Than or Equal to Operator (<=): A coder can use this operator to test if a variable is less than or equal to
other variable.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
245
Practice 1 – The Equal Operator: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <script> function Teraexe_Function() { var Teraexe_A = 5; var Teraexe_B = 5; var Teraexe_C = 10; document.getElementById("AGene1").innerHTML = (Teraexe_A == Teraexe_B); // True document.getElementById("AGene2").innerHTML = (Teraexe_A == Teraexe_C); // False } </script> </body> </html>
Result 1 – The Equal Operator:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
246
Practice 2 – Identical Operator: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <script> function Teraexe_Function() { var Teraexe_A = 5; var Teraexe_B = 5; var Teraexe_C = "5"; document.getElementById("AGene1").innerHTML = (Teraexe_A === Teraexe_B); // True document.getElementById("AGene2").innerHTML = (Teraexe_A === Teraexe_C); // False } </script> </body> </html> Result 2 – Identical Operator:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
247
Practice 3 – Not Equal Operator: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <script> function Teraexe_Function() { var Teraexe_A = 5; var Teraexe_B = 5; var Teraexe_C = 10; document.getElementById("AGene1").innerHTML = (Teraexe_A != Teraexe_B); // False document.getElementById("AGene2").innerHTML = (Teraexe_A != Teraexe_C); // True } </script> </body> </html> Result 3 – Not Equal Operator:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
248
Practice 4 – Not Identical Operator: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <script> function Teraexe_Function() { var Teraexe_A = 5; var Teraexe_B = 5; var Teraexe_C = "5"; document.getElementById("AGene1").innerHTML = (Teraexe_A !== Teraexe_B); // False document.getElementById("AGene2").innerHTML = (Teraexe_A !== Teraexe_C); // True } </script> </body> </html> Result 4 – Not Identical Operator:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
249
Practice 5 – Greater Than Operator: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <script> function Teraexe_Function() { var Teraexe_A = 7; var Teraexe_B = 5; var Teraexe_C = 10; document.getElementById("AGene1").innerHTML = (Teraexe_A > Teraexe_B); // True document.getElementById("AGene2").innerHTML = (Teraexe_A > Teraexe_C); // False } </script> </body> </html> Result 5 – Greater Than Operator:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
250
Practice 6 – Less Than Operator: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <script> function Teraexe_Function() { var Teraexe_A = 5; var Teraexe_B = 7; var Teraexe_C = 3; document.getElementById("AGene1").innerHTML = (Teraexe_A < Teraexe_B); // True document.getElementById("AGene2").innerHTML = (Teraexe_A < Teraexe_C); // False } </script> </body> </html> Result 6 – Less Than Operator:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
251
Practice 7 – Greater Than or Equal to Operator: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <script> function Teraexe_Function() { var Teraexe_A = 7; var Teraexe_B = 7; var Teraexe_C = 9; document.getElementById("AGene1").innerHTML = (Teraexe_A >= Teraexe_B); // True document.getElementById("AGene2").innerHTML = (Teraexe_A >= Teraexe_C); // False } </script> </body> </html> Result 7 – Greater Than or Equal to Operator:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
252
Practice 8 – Less Than or Equal to Operator: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene1"></p> <p id="AGene2"></p> <script> function Teraexe_Function() { var Teraexe_A = 9; var Teraexe_B = 9; var Teraexe_C = 7; document.getElementById("AGene1").innerHTML = (Teraexe_A <= Teraexe_B); // True document.getElementById("AGene2").innerHTML = (Teraexe_A <= Teraexe_C); // False } </script> </body> </html> Result 8 – Less Than or Equal to Operator:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
253
JavaScript – Exercise XVIII: The For-Loop Statement Theory: • The For-Loop Statement: A coder can use the for-loop statement when he/she wants to execute an instruction
several times. For example, a coder may use the for-loop statement to execute an instruction five times, or a
programmer may use the for-loop statement to execute an instruction ten times. As you can see, this is the syntax
of the for-loop statement:
for (first-expression; second-expression; third-expression)
{
//The codes that a for-loop statement will execute;
}
First expression: In the first expression or parameter, a coder may include the initial value of a variable.
Second-expression: In the second expression, a coder may include some codes that will evaluate some
variables/numbers. If a variable or number is true, the loop will continue running or executing its codes; on the
other hand, the loop will end if a variable or number is false.
Third-expression: In the third expression, a programmer may include those kinds of codes that are going to
increase a number or variable.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
254
Practice 1: <html>
<body>
<p id="AGene"></p>
<script>
var Teraexe = "" ;
var AGene_Loop;
for (AGene_Loop = 0; AGene_Loop <= 7; AGene_Loop++)
{
Teraexe += "The Value of Teraexe is: " + AGene_Loop + "<br>";
}
document.getElementById("AGene").innerHTML = Teraexe;
</script>
</body>
</html>
Result 1:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
255
Practice 2: <html> <body> <button onclick="Teraexe_Function()">Button</button> <p id="AGene"></p> <script> function Teraexe_Function() { var Teraexe = "" ; var AGene_Loop; for (AGene_Loop = 0; AGene_Loop <= 7; AGene_Loop++) { Teraexe += "The Value of Teraexe is: " + AGene_Loop + "<br>"; } document.getElementById("AGene").innerHTML = Teraexe; } </script> </body> </html> Result 2:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
256
JavaScript – Exercise XIX: The Math Object Theory: • The Math Object: While a coder is working with numbers, he/she can use the math object to start doing some
mathematical tasks or operations; for instance, a programmer may use the math object to find the lowest/highest
value of a group of numbers. As you can see, those are some of the most common math objects that a coder can
use when he/she is working with different kinds of numbers or digits:
1) Math.min(): A coder can use the Math.min() object when he/she wants to find the lowest value of a group of
numbers.
2) Math.max(): A coder can use the Math.max() object when he/she wants to find the highest value of a group of
numbers.
3) Math.random(): A coder can use the Math.random() object when he/she wants to print a random number that is
going to be between zero (0) and one (1).
4) Math.round(): A coder can use the Math.round() object when he/she wants to round a number or digit to its
nearest integer; therefore, if a number has a decimal value, the computer application will erase that decimal and
round the number to its nearest integer. For example, if a computer application has a number like 5.5, the
Math.round() object is going to round that number to six (6); on the other hand, if an application has the number
like 5.4, the Math.round() object will round that number to five (5).
5) Math.ceil(): When a coder wants to round a number or digit up to the nearest integer, he/she can use the
Math.ceil() object; for example, if a computer application has a number like 5.3, the Math.ceil() object will round
that number to six (6).
6) Math.floor(): When a coder wants to round a number or digit down to the nearest integer, he/she can use the
Math.floor() object; for example, if a computer application has a number like 5.8, the Math.floor() object will
round that number to five (5).
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
257
Practice 1 – The Lowest Value: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
document.getElementById("AGene").innerHTML = Math.min(5,20,86);
}
</script>
</body>
</html>
Result 1 – The Lowest Value:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
258
Practice 2 – The Highest Value: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
document.getElementById("AGene").innerHTML = Math.max(5,20,86);
}
</script>
</body>
</html>
Result 2 – The Highest Value:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
259
Practice 3 – Random Number: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
document.getElementById("AGene").innerHTML = Math.random();
}
</script>
</body>
</html>
Practice 3 – Random Number:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
260
Practice 4 – Rounding a Number: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene1"></p>
<p id="AGene2"></p>
<script>
function Teraexe_Function()
{
document.getElementById("AGene1").innerHTML = Math.round(5.5); // It will print 6
document.getElementById("AGene2").innerHTML = Math.round(5.4); // It will print 5
}
</script>
</body>
</html>
Result 4 – Rounding a Number:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
261
Practice 5 – Rounding Up a Number: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
document.getElementById("AGene").innerHTML = Math.ceil(5.3); // It will print 6
}
</script>
</body>
</html>
Practice 5 – Rounding Up a Number:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
262
Practice 6 – Rounding Down a Number: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
document.getElementById("AGene").innerHTML = Math.floor(5.8); // It will print 5
}
</script>
</body>
</html>
Result 6 – Rounding Down a Number:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
263
Practice 7 – Rounding an Integer: In the next exercise, you will learn how to use Math.floor and Math.random to print an integer that is going to be
between zero (0) and five (5).
<html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
document.getElementById("AGene").innerHTML = Math.floor(Math.random() * 6);
}
</script>
</body>
</html>
Result 7 – Rounding an Integer:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
264
Practice 8 – Absolute Value: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
// A coder can use the Math.abs to print the absolute value of a number.
document.getElementById("AGene").innerHTML = Math.abs(-10);
}
</script>
</body>
</html>
Result 8 – Absolute Value:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
265
Practice 9 – Cosine: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
// A coder can use the Math.cos to print the cosine of a number.
document.getElementById("AGene").innerHTML = Math.cos(20);
}
</script>
</body>
</html>
Result 9 – Cosine:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
266
Practice 10 – Sine: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
// A coder can use the Math.sin to print the sine of a number.
document.getElementById("AGene").innerHTML = Math.sin(20);
}
</script>
</body>
</html>
Result 10 – Sine:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
267
Practice 11 – Tangent: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
// A coder can use the Math.tan to print the tangent of an angle.
document.getElementById("AGene").innerHTML = Math.tan(45);
}
</script>
</body>
</html>
Result 11 – Tangent:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
268
Practice 12 – Arctangent: <html>
<body>
<button onclick="Teraexe_Function()">Button</button>
<p id="AGene"></p>
<script>
function Teraexe_Function()
{
// A coder can use the Math.atan to print the arctangent...
document.getElementById("AGene").innerHTML = Math.atan(4);
}
</script>
</body>
</html>
Result 12 – Arctangent:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
269
JavaScript – Exercise XX: An Introduction to JQuery Theory: • The JQuery Library: JQuery is one of the JavaScript libraries that a coder can use to simplify his/her work; to
clarify, JQuery is a JavaScript library that a coder can use to do different kinds of tasks without typing many
codes. Before using the JQuery library, an individual has to download it from the internet and put that library or
script inside of an HTTP server; then, if a programmer wants to use the JQuery library on a script, he/she has to
type a line similar to this:
<script src="jquery-1.11.1.min.js"></script>.
• The JQuery Syntax: As you can see, this is the syntax of the JavaScript JQuery library:
$(function() { $("Code").Action() });
� Code: In this field, a coder has to type a code, which can be an HTML element, such as h, p, or other.
� Action: In this field, a programmer has to type an action; in other words, a coder has to type that kind of action
that is going to cause an effect on the previous HTML element or code. For example, a coder may type an action
code like click, hide, or other.
� Using the previous syntax, if a coder includes a function inside of Action, he/she will obtain this code:
$(function() { $("Code").Action(function() { //Codes that will be executed after doing an action }); });
� In the next exercise, I am going to use the previous code to develop a script that is going to open an alert window
if an individual makes a click on the Socket_0x03 header.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
270
Practice:
<html> <head> <script src="jquery-1.11.1.min.js"></script> <script> $(function() { $("h1").click(function() { alert( "Hi!" ); }); }); </script> </head> <body> <h1>Socket_0x03</h1> </body> </html> Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
271
JavaScript – Exercise XXI: JQuery – Mouse Events Theory: • Mouse Events: When a coder is using the JavaScript JQuery library, he/she can use those kinds of mouse events:
click, dblclick, mouseenter, mouseout, mouseleave.
Practice:
<html> <head> <script src="jquery-1.11.1.min.js"></script> <script> $(function() { $("h1").mouseenter(function() { $(this).hide(); }); }); </script> </head> <body> <h1>Socket_0x03</h1> </body> </html> Result: After opening the previous script, you will see this:
Then, after moving your mouse inside of Socket_0x03, you will notice that Socket_0x03 is going to disappear:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
272
JavaScript – Exercise XXII: JQuery – The hover Method Theory: • The hover Method: The hover method has two functions related to the movement of a mouse. On the one hand,
when a user moves his/her mouse inside of something, the hover method executes a function; on the other hand,
when a user moves his/her mouse outside of something, the hover method executes other function. In the next
example, if a user moves his/her mouse inside of the Socket_0x03 header, the hover method is going to hide the
Socket_0x03 header; on the other hand, if a user moves his/her mouse outside of the Socket_0x03 header, the
hover method is going to show the Socket_0x03 header.
Practice:
<html> <head> <script src="jquery-1.11.1.min.js"></script> <script> $(function() { $("h1").hover(function() { $(this).hide(); }, function() { $(this).show(); }); }); </script> </head> <body> <h1>Socket_0x03</h1> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
273
Result:
After opening the previous script, a user is going to see the Socket_0x03 header:
The Socket_0x03 header is going to be hide if a user moves his/her mouse inside of it:
A user will see the Socket_0x03 header if he/she moves his/her mouse outside of it:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
274
JavaScript – Exercise XXIII: JQuery – Focus & Blur
Theory:
• Using Focus and Blur: On the one hand, a coder can use the focus method when he/she wants to execute a
function after clicking inside of an HTML element, such as an input element; on the other hand, a coder can use
the blur method when he/she wants to execute a function after clicking outside of an HTML element, such as an
input element. In the next example, if a user clicks inside of the input element, he/she will notice a gray color
inside of an input element thanks to the focus method; then, if a user clicks outside of the input element, he/she
will see a white color inside of an input element thanks to the blur method.
Practice:
<html> <head> <script src="jquery-1.11.1.min.js"></script> <script> $(function() { $("input").focus(function() { $(this).css("backgroundColor","#E0E0E0"); }); $("input").blur(function() { $(this).css("backgroundColor","white"); }); }); </script> </head> <body> User: <input> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
275
Result:
After opening a script, a user is going to see this image:
If a coder clicks inside of the input, he/she is going to see this image thanks to the focus method:
If a coder clicks outside of the input, he/she is going to see this image thanks to the blur method:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
276
JavaScript – Exercise XXIV: JQuery – The toggle Method Theory:
• The toggle Method: A coder can use the toggle method when he/she wants to display or show those kinds of
elements that are hidden; furthermore, a coder can use the toggle method to hide those kinds of elements that a
user can see on his/her browser. Therefore, the toggle method is similar to the show method because a coder can
use it to show those kinds of elements that are hidden, and the toggle method is similar to the hide method
because a coder can use it to hide some elements. One of the most interesting points that a coder should know
about the toggle method is that he/she can type the speed that he/she wants to use to hide or show the content of
an element; for example, if a coder wants to hide/show the content of an element in three seconds, he/she may
type a line similar to this: toggle(3000);.
Practice:
<html> <head> <script src="jquery-1.11.1.min.js"></script> <script> $(function() { $("input").click(function() { $(this).toggle(3000); }); }); </script> </head> <body> User: <input> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
277
Result:
After opening a script, a user is going to see this image:
If a coder clicks on the input, he/she will notice that the input is going to start disappearing in a few seconds:
After a few seconds, the input element will be hidden:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
278
An XML Review
Before starting with the PHP projects, I am going to provide a review of XML because sometimes a coder has
to use an eXtensible Markup Language (XML) when he/she is developing some applications or webpages in PHP and
JavaScript. What is XML? XML is a language that an individual can use to describe data; more specifically, XML is
an extensible markup language that a programmer can use to define the meaning of some characters or tags, so a
coder has to create and define his/her own tags when he/she is using XML.
One of the most important points that a coder should know about XML is that this markup language is not
going to display or show data like HTML because this language can be used by a coder only to describe data instead
of displaying or showing data. On the one hand, a coder can use HTML to display data and see some results through
a browser thanks to its predefined tags; on the other hand, a coder can use XML only to describe data because its tags
are not predefined. Therefore, a programmer is not going to see some results inside of a browser if he/she is only
using XML; hence, a coder has to use XML with other languages like JavaScript to simplify his/her work with XML
and see some results with other languages like JavaScript.
As previously stated, a coder has to create and define his/her own tags when he/she is using an extensible
markup language (XML). Now, I am going to provide an example of how an individual may create and define his/her
own tags:
First, a coder has to open a text-document and put those codes inside of that document:
<?xml version="1.0"?>
<!-- This is a comment -->
<teraexe_message>
<to>Webmaster</to>
<from>Socket_0x03</from>
<subject>Hey!</subject>
</teraexe_message>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
279
Then, a coder has to save this document as message.xml.
As you can see, instead of using predefined tags like <h1>, <p> , and <img>, I am creating my own tags like
<teraexe_message>. In the future, I may use that XML document with JavaScript/PHP to display some data or
information inside of a browser.
Creating XML Elements
A coder has to follow some rules when he/she is creating or defining XML tags. As you can see, those are
some of the most important rules that a coder should follow when he/she is creating or defining some elements:
a) First, when a coder is typing the name of an element, he/she cannot leave a blank space. For example, a coder
does not have to define or create a tag similar to this: <teraexe message>. When a coder wants to create an
element similar to the previous, he/she may type an element similar to this: teraexe_message or teraexe.message.
b) Second, when a coder is typing the name of an element, he/she cannot start with a number/punctuation-mark. For
instance, a coder does not have to type an element similar to this: <86teraexe> or <#teraexe>.
c) Third, when a coder is typing the name of an element, he/she cannot start with XML/xml.
d) Fourth, XML is case-sensitive, which means that a coder has to pay close attention to the uppercase and
lowercase letters because a word like Teraexe is going to be different than teraexe.
e) Fifth, when a coder is creating or defining an XML tag, he/she has to use a slash (/) to close his/her tag.
The XML Family Tree
Sometimes, when a coder is developing an XML document, he/she has to create an XML family tree, which is
going to include a root element; moreover, an XML family tree may include some children or categories and some
sub-children or sub-categories. One of the best ways to understand the idea of an XML family tree is seeing an
example; therefore, I am going to provide an example of an XML document and its XML family tree.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
280
As you can see, this is an XML document:
<AGene_Commodities> <Hard_Commodities> <Platinum> </Platinum> <Diamond> </Diamond> </Hard_Commodities> <Soft_Commodities> <Coffee> </Coffee> <Corn> </Corn> </Soft_Commodities> </AGene_Commodities>
As you can see, this is a diagram of the previous XML document; in other words, this is the XML family tree
of the previous XML document:
In the previous diagram, the root element is AGene_Commodities. Furthermore, AGene_Commodities is the
parent of Hard_Commodities and Soft_Commodities; to put it another way, the children of AGene_Commodities are
Hard_Commodities and Soft_Commodities. In addition, the children of Hard_Commodities are Platinum and
Diamond. Moreover, the grandchildren of AGene_Commodities are Platinum and Diamond. An important point that a
coder should know is that the elements/text/attributes of an XML family tree are known as nodes.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
281
An XML Review: Exercise I: The XMLHttpRequest Object Theory: • Creating an Object: When a coder is working with XML documents, he/she has to create an
XMLHttpRequest/ActiveX object using one of those syntaxes:
a) Syntax to create a built-in XMLHttpRequest object for those kinds of browsers that are superior to the version
seven of internet explorer: xmlhttp=new XMLHttpRequest();
b) Syntax to create an ActiveX object for those kinds of browsers that are inferior to the version seven of internet
explorer: xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
• Concepts: Before talking about the second step that is about parsing an object, I am going to provide the
definition of some words that a coder should know when he/she is working with XMLHttpRequest Objects:
a) The Meaning of API: What does API means? API is an abbreviation for application program interface. In
computer programming and information technology, an application program interface (API) is a set or group of
instructions/methods/protocols/tasks that can be used by a coder to develop some computer applications. For
example, an API can be those kinds of codes or building-blocks that a coder can use to develop a computer
application; those codes or building-blocks can be designed to facilitate the work of a programmer who wants to
create a computer program.
b) The Meaning of DOM: DOM is an abbreviation for Document Object Model. In XML, a DOM is an API for
XML documents because an XML DOM object can create an easy way of interacting with that kind of data or
information that is inside of an XML document. After creating an XML DOM object, an individual can use it to
gain access to different kinds of XML documents; more specifically, an individual can use a computer
programming language like JavaScript to use an XML DOM object and gain access to the data or information that
is inside of an XML document, then, after using JavaScript to gain access to an XML document, a coder can
display the information that is inside of an XML document on a browser like internet explorer.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
282
c) The Meaning of Parse: What does parse mean? In the field of computers, parsing is the process of reading or
analyzing line by line different kinds of codes in order to separate or simplify it in a way that is easy to read; for
example, in computer programming, a program may read and analyze line by line a source code to convert it into
machine language, then, after the parsing process, a computer can read that machine language to convert it into an
executable and perform an action or task.
• Parsing an Object: After creating an object, an individual has to parse an XML document; more specifically, after
creating an XMLHttpRequest/ActiveX object, a coder has to type some codes that are going to parse or read an
XML document and convert that document into an XML DOM object. As you can see, this is an example of the
codes that a coder can use to parse an XML document (AGene.xml) and convert it into an XML DOM object:
xmlhttp=new XMLHttpRequest(); //Creating an object
xmlhttp.open("GET","AGene.xml",false); //the open method
xmlhttp.send(); //the send method
xmlDoc=xmlhttp.responseXML; //the response property; the xmlDoc holding the data of an XML file.
a) Using the xmlhttp.open method of an XMLHttpRequest Object: Before using the xmlhttp.send method to send a
request to an HTTP server, a coder has to use the xmlhttp.open method to open an XML document. When a coder
is using the xmlhttp.open method to open an XML document, he/she has to specify some instructions related to
the request that he/she wants to send to an HTML server. As you can see, this is the syntax of the xmlhttp.open
method:
xmlhttp.open (request, file-location, async/sync);
� Request: In this field, a coder has to specify what kind of request he/she wants to send to an HTTP server,
which can be GET or POST. On the one hand, a coder may specify a GET request if he/she wants to send
insensitive information; on the other hand, a coder may specify a POST request if he/she wants to send
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
283
sensitive information. Although using the POST request can be more secure than the GET request, there are a
lot of coders who are using the GET request because this method can be faster than the POST request.
� File-Location: In the second parameter, a coder may specify a URL, or a programmer may specify one of
those files that are inside of his/her HTTP server, for example, a coder may specify an XML document that is
on an HTTP server.
� Async/Sync: In this parameter, a coder has to type true if he/she wants to send asynchronous requests; on the
other hand, an individual has to type false if he/she wants to send synchronous requests.
b) Using the xmlhttp.send method of an XMLHttpRequest Object: After using the xmlhttp.open method, a coder has
to use the xmlhttp.send method to send a request to an HTTP server.
c) Using the xmlhttp.responseXML property of an XMLHttpRequest Object: After using the xmlhttp.send method, a
coder can use the xmlhttp.responseXML property of an XMLHttpRequest object when he/she wants to obtain a
response from an HTTP server; more specifically, a coder can use the xmlhttp.resposeXML property of an
XMLHttpRequest object to get a response or obtain information from an XML document that is inside of an
HTTP server.
When a coder is using the XMLHttpRequest object and wants to get a response from an HTTP server, he/she can
use two different kinds of properties, which are known as xmlhttp.responseXML and xmlhttp.responseText. On
the one hand, as previously stated, a coder can use the xmlhttp.resposeXML property of an XMLHttpRequest
object to get a response or obtain information from an XML document that is inside of an HTTP server; on the
other hand, an individual can use the xmlhttp.responseText property when he/she wants to get a response or
obtain information from a text file that is inside of an HTTP server.
In the last stage of the parsing process, if an individual wants to parse an XML file, he/she has to type a line
similar to this: xmlDoc=xmlhttp.responseXML. As you can see, all the data or information that is inside of the
xmlhttp.responseXML property is passing to the xmlDoc property. Because of this movement, the xmlDoc
property is able to hold all the data or information of an XML document.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
284
d) Using the xmlDoc property of an XMLHttpRequest Object: In the last stage of the parsing process, all the data or
information that is inside of an XML document is going to be stored on the xmlDoc property; to put it another
way, in the last stage of the parsing process, the xmlDoc property will hold all the data of an XML document;
therefore, after the parsing process, if a coder wants to obtain information from an XML document, he/she only
has to use the xmlDoc property instead of typing a lot of codes.
As you can see, the parsing goal is to create the xmlDoc object, also known as the XML DOM object.
• Displaying Data: After creating and parsing an XML DOM object, an individual can use a computer
programming language like JavaScript to get information from an xmlDoc object and display that information
inside of a browser. As previously stated, the xmlDoc object holds all the data of an XML document. As you can
see, this is an example of how to retrieve information from an xmlDoc object:
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue;
Now, I am going to explain some of the most important features of the previous code:
� xmlDoc: In this part, a coder has to type an XML DOM object, which holds all the data of an XML file.
� getElementsByTagName("message")[0]: In this part, a coder has to include the first element of an XML DOM
object. In this case, I am including the <message> element.
� childNodes[0]: In this part, I am typing childNodes[0] because I want to print or show the first child of an
element.
� nodeValue: At the end of the code, I am typing nodeValue because I want to obtain the value of a node.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
285
Practice 1:
First, you have to create the AGene.xml document; then, you have to put those codes on the AGene file:
<?xml version="1.0" encoding="UTF-8"?> <AGene> <message>This is a message!</message> </AGene>
Second, you have to create the index.php file and put those codes inside of the index file:
<html> <body> <div> <span id="message"></span> </div> <script> xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open("GET","AGene.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; document.getElementById("message").innerHTML= xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue; </script> </body> </html>
Result 1:
You have to open the index.php file using a browser like Internet Explorer (IE version 6 or inferior):
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
286
Practice 2:
First, you have to create the AGene.xml document; then, you have to put those codes on the AGene file:
<?xml version="1.0" encoding="UTF-8"?> <AGene> <message>This is a message!</message> </AGene>
Second, you have to create the index.php file and put those codes inside of the index file:
<html> <body> <div> <span id="message"></span> </div> <script> xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET","AGene.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; document.getElementById("message").innerHTML= xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue; </script> </body> </html>
Result 2:
You have to open the index.php file using a browser like Firefox or IE (IE version 7 or superior):
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
287
Practice 3:
First, you have to create the AGene.xml document; then, you have to put those codes on the AGene file:
<?xml version="1.0" encoding="UTF-8"?> <AGene> <message>This is a message!</message> </AGene>
Second, you have to create the index.php file and put those codes inside of the index file:
<html> <body> <div> <span id="message"></span> </div> <script> if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); //IE version 7 or superior. xmlhttp.open("GET","AGene.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE version 6 or inferior. xmlhttp.open("GET","AGene.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; } document.getElementById("message").innerHTML= xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue; </script> </body> </html> Result 3:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
288
An XML Review: Exercise II: Loading an XML Document Theory: • Loading an XML document and the write method: In the next exercise, you will learn how to load an XML
document; furthermore, you will learn how to use the write method of JavaScript to display data or information
inside of a browser. As you can see, this is the syntax of the write method:
document.write (first-expression);
Practice:
After creating the AGene.xml file, you have to create the index.php file and put those codes on that file:
<html> <body> <script> if (window.XMLHttpRequest) //IE version 7 or superior. { xhttp=new XMLHttpRequest(); xhttp.open("GET","AGene.xml",false); xhttp.send(); xmlDoc=xhttp.responseXML; } else //IE version 6 or inferior. { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); xhttp.open("GET","AGene.xml",false); xhttp.send(); xmlDoc=xhttp.responseXML; } document.write("Loading an XML Document!"); </script> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
289
An XML Review: Exercise III: Loading an XML String Theory: • Loading an XML string and the write method: In the next exercise, you will learn how to load an XML string.
Practice:
After creating the AGene.xml file, you have to create the index.php file and put those codes on that file:
<html> <body> <div> <span id="message"></span> </div> <script> AGene="<AGene>"; AGene="</AGene>"; if (window.DOMParser) //IE version 7 or superior { xmlDoc=new DOMParser().parseFromString(AGene,"text/xml"); } else //IE version 6 or inferior { xmlDoc=new ActiveXObject("Microsoft.XMLDOM" ); xmlDoc.async=false; xmlDoc.loadXML(AGene); } document.write("Loading an XML string!"); </script> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
290
An XML Review: Exercise IV: The LoadXMLDoc Function Theory:
• The LoadXMLDoc Function: One of the best ways to load an XML document is using the loadXMLDoc function
to create a JavaScript loader; then, after creating a JavaScript loader, a coder only has to type a few codes each
time that he/she wants to load an XML document.
Practice:
First, a coder has to create the AGene.xml file; then, he/she has to put those codes inside of the AGene file:
<?xml version="1.0" encoding="UTF-8"?> <AGene> <message>Using the LoadXMLDoc Function.</message> </AGene>
Second, a coder has to create the AGene_Loader.js file and put those codes on that file:
function loadXMLDoc(AGene_Loader)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest(); //IE version 7 or superior.
xmlhttp.open("GET",AGene_Loader,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE version 6 or inferior.
xmlhttp.open("GET",AGene_Loader,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
}
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
291
Third, a coder has to create the index.php file and put those codes inside of that file:
<html>
<head>
<script src="AGene_Loader.js"></script>
</head>
<body>
<script>
xmlDOC=loadXMLDoc("AGene.xml");
document.write(xmlDoc.getElementsByTagName("message")[0].childNodes[0].nodeValue);
</script>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
292
An XML Review: Exercise V: Gaining Access to Nodes Theory:
• Gaining Access to Nodes: A coder can use the getElementsByTagName method when he/she wants to gain access
to those kinds of nodes that are inside of an XML document. In the next exercise, you will see how to use the
getElementsByTagName method to gain access to the data of the third <message> element.
Practice:
First, a coder has to create the AGene.xml file; then, he/she has to put those codes inside of the AGene file:
<?xml version="1.0" encoding="UTF-8"?> <AGene> <message>First Message.</message> <message>Second Message.</message> <message>Third Message.</message> <message>Fourth Message.</message> <message>Fifth Message.</message> </AGene>
Second, a coder has to create the AGene_Loader.js file and put those codes on that file:
function loadXMLDoc(AGene_Loader) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); //IE version 7 or superior. xmlhttp.open("GET",AGene_Loader,false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE version 6 or inferior. xmlhttp.open("GET",AGene_Loader,false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; } }
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
293
Third, a coder has to create the index.php file and put those codes inside of that file:
<html>
<head>
<script src="AGene_Loader.js"></script>
</head>
<body>
<script>
xmlDOC=loadXMLDoc("AGene.xml");
document.write(xmlDoc.getElementsByTagName("message")[2].childNodes[0].nodeValue);
</script>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
294
An XML Review: Exercise VI: NodeName & NodeType Theory:
• Using the NodeName and NodeType Property: A coder can use the NodeName property when he/she wants to
print or show the name of a node; furthermore, a coder can use the NodeType property when he/she wants to print
or show the node type.
Practice:
First, a coder has to create the AGene.xml file; then, he/she has to put those codes inside of the AGene file:
<?xml version="1.0" encoding="UTF-8"?> <AGene> <message>First Message.</message> <message>Second Message.</message> <message>Third Message.</message> </AGene>
Second, a coder has to create the AGene_Loader.js file and put those codes on that file:
function loadXMLDoc(AGene_Loader) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); //IE version 7 or superior. xmlhttp.open("GET",AGene_Loader,false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE version 6 or inferior. xmlhttp.open("GET",AGene_Loader,false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; } }
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
295
Third, a coder has to create the index.php file and put those codes inside of that file:
<html>
<head>
<script src="AGene_Loader.js"></script>
</head>
<body>
<script>
xmlDOC=loadXMLDoc("AGene.xml");
document.write(xmlDoc.documentElement.nodeName + "<br>");
document.write(xmlDoc.documentElement.nodeType);
</script>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
296
An XML Review: Exercise VII: Using Loop and Length Theory:
• Using Loop and Length: A coder can use the For-Loop statement and the Length property when he/she wants to
print or show all the data that is inside of all those elements that have the same name. For example, in the next
source codes, I am going to use the For-Loop statement and the Length property to print all the data that is inside
of all those elements that have the <message> name.
Practice:
First, a coder has to create the AGene.xml file; then, he/she has to put those codes inside of the AGene file:
<?xml version="1.0" encoding="UTF-8"?> <AGene> <message>First Message.</message> <message>Second Message.</message> <message>Third Message.</message> </AGene>
Second, a coder has to create the AGene_Loader.js file and put those codes on that file:
function loadXMLDoc(AGene_Loader) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); //IE version 7 or superior. xmlhttp.open("GET",AGene_Loader,false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE version 6 or inferior. xmlhttp.open("GET",AGene_Loader,false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; } }
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
297
Third, a coder has to create the index.php file and put those codes inside of that file:
<html>
<head>
<script src="AGene_Loader.js"></script>
</head>
<body>
<script>
xmlDOC=loadXMLDoc("AGene.xml");
for (a=0; a<xmlDoc.getElementsByTagName("message").length; a++)
{
document.write(xmlDoc.getElementsByTagName("message")[a].childNodes[0].nodeValue + "<br>");
}
</script>
</body>
</html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
298
An XML Review: Exercise VIII: Node Navigation Commands Theory:
• Node Navigation Commands: A coder can use node navigation commands when he/she wants to use a node
relationship to print the name of a node. For example, if a coder wants to print the first-child of a node, he/she
may type a command like firstChild; to put it another way, if an individual wants to print or show the first-child
of a node, he/she may use a node navigation command like firstChild. Using node relationships to print or show a
node name is known as node navigation. As you can see, those are some of the most common node navigation
commands that a coder can use when he/she wants to navigate through different kinds of nodes and print a node
name: parentNode, childNodes, firstChild, lastChild, nextSibling, and previousSibling.
Practice:
First, a coder has to create the AGene.xml file; then, he/she has to put those codes inside of the AGene file:
<?xml version="1.0" encoding="UTF-8"?> <AGene_Commodities> <Hard_Commodities> <Platinum> </Platinum> <Diamond> </Diamond> <Gold> </Gold> </Hard_Commodities> <Soft_Commodities> <Coffee> </Coffee> </Soft_Commodities> </AGene_Commodities>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
299
Second, a coder has to create the AGene_Loader.js file and put those codes on that file:
function loadXMLDoc(AGene_Loader)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest(); //IE version 7 or superior.
xmlhttp.open("GET",AGene_Loader,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE version 6 or inferior.
xmlhttp.open("GET",AGene_Loader,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
}
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
300
Third, a coder has to create the index.php file and put those codes inside of that file:
<html> <head> <script src="AGene_Loader.js"></script> </head> <body> <script> xmlDOC=loadXMLDoc("AGene.xml"); //Printing the parentNode of a node. document.write(xmlDoc.getElementsByTagName("Hard_Commodities")[0].parentNode.nodeName + "<br>"); //Printing the second childNode of a node. document.write(xmlDoc.getElementsByTagName("Hard_Commodities")[0].childNodes[1].nodeName + "<br>"); //Printing the firstChild of a node. document.write(xmlDoc.getElementsByTagName("Hard_Commodities")[0].firstChild.nodeName + "<br>"); //Printing the lastChild of a node. document.write(xmlDoc.getElementsByTagName("Hard_Commodities")[0].lastChild.nodeName + "<br>"); //Printing the nextSibling of a node. document.write(xmlDoc.getElementsByTagName("Hard_Commodities")[0].nextSibling.nodeName + "<br>"); //Printing the previousSibling of a node. document.write(xmlDoc.getElementsByTagName("Soft_Commodities")[0].previousSibling.nodeName + "<br>"); </script> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
301
An XML Review: Exercise IX: Changing Nodes Theory:
• Using the nodeValue Property to Change Text: A coder can use the nodeValue property when he/she wants to
change the content or text of an element. For example, in the next exercise, I am going to use the nodeValue
property to change the value of Platinum! to a different value; therefore, after using the nodeValue property to
change the value of Platinum!, the browser of a client is going to display this line: Changing a Node Value!.
• Using the setAttribute Method to Change Attributes: When a coder wants to change a node attribute, he/she can
use the setAttribute method. Then, after changing a node attribute, a programmer can use the getAttribute method
to display or show a node attribute.
Practice:
First, a coder has to create the AGene.xml file; then, he/she has to put those codes inside of the AGene file:
<?xml version="1.0" encoding="UTF-8"?>
<AGene_Commodities>
<Hard_Commodities>
<Platinum category="HC">Platinum!</Platinum>
<Diamond category="HC">Diamond!</Diamond>
<Gold category="HC">Gold!</Gold>
</Hard_Commodities>
<Soft_Commodities>
<Coffee category="SC">Coffe!</Coffee>
</Soft_Commodities>
</AGene_Commodities>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
302
Second, a coder has to create the AGene_Loader.js file and put those codes on that file:
function loadXMLDoc(AGene_Loader)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest(); //IE version 7 or superior.
xmlhttp.open("GET",AGene_Loader,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); //IE version 6 or inferior.
xmlhttp.open("GET",AGene_Loader,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
}
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
303
Third, a coder has to create the index.php file and put those codes inside of that file:
<html> <head> <script src="AGene_Loader.js"></script> </head> <body> <script> xmlDOC=loadXMLDoc("AGene.xml"); //Printing a node value. document.write(xmlDoc.getElementsByTagName("Platinum")[0].childNodes[0].nodeValue + "<br>"); //Changing a node value. document.write(xmlDoc.getElementsByTagName("Platinum")[0].childNodes[0].nodeValue= "Changing a Node Value!" + "<br>"); //Printing a node attribute. document.write(xmlDoc.getElementsByTagName("Platinum")[0].getAttribute("category") + "<br>"); //Changing a node attribute. AGene=xmlDoc.getElementsByTagName("Platinum")[0]; AGene.setAttribute("category","Stone"); document.write(AGene.getAttribute("category")); </script> </body> </html>
Result:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
304
Exercise 135: PHP Projects: A Webcam Project Theory: • Concepts: Before starting with the webcam.js library of JavaScript, I am going to explain some basic concepts
about computer programming that a coder should know to understand this section:
• Callback: Also known as a callback function. In computer programming and information technology, a callback is
one of those functions that will be called by another function only if an event, task, or condition is executed. To
put it another way, a callback is a function that will be called by another function if a particular event happens or
occurs, so if a particular event does not happen, the callback function will not be executed. What is the difference
between a regular function and a callback function? A regular function is like a first function that can be executed
if a client runs a computer application or script; on the other hand, a callback function is like a second function
that may be executed through a regular or first function only if a client is able to perform a particular task, such as
clicking on a button that is inside of a script.
• I/O Stream: A stream is a group or sequence of bytes/data/files, and I/O is an abbreviation for Input or Output.
Therefore, an I/O stream can be an input-stream or an output-stream. An input-stream can be one of those
computer applications that may read data from any kind of source, such as a database/server; on the other hand,
an output-stream can be one of those computer applications that may write data or information into a source, such
as a database/server, for example, an output-stream can be a computer program that writes data into a server or
database.
• API: Even though I provided some information related to the meaning of API in a previous exercise, I am going
to explain its meaning once again because there are some API calls in this section that we will use to develop a
PHP script. As previously stated, API is an abbreviation for application program interface. In computer
programming and information technology, an application program interface (API) is a set or group of
instructions/methods/protocols/tasks that can be used by a coder to develop some computer applications. For
example, an API can be those kinds of codes or building-blocks that a coder can use to develop a computer
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
305
application; those codes or building-blocks can be designed to facilitate the work of a programmer who wants to
create a computer program. Another example is the use of APIs in this section; in this section, there is a
webcam.js JavaScript library with different kinds of API calls. After including the webcam.js library inside of a
script, a coder can use the webcam.js API calls to develop a computer application that will interact with a
webcam. In this case, a coder does not have to type a lot of codes to develop a computer application that will
interact with a webcam because he/she is using the API calls of a JavaScript library or plugin to create its PHP
script.
• The Webcam.js JavaScript Library: A coder can use the webcam.js JavaScript library when he/she wants to
develop a computer application that is going to use a webcam to take pictures and upload those pictures to an
HTTP server. When a coder wants to use the webcam.js library on his/her HTTP server, he/she has to download it
from the internet and put that plugin inside of the root directory or folder of his/her HTTP server; hence, if you
want to run the script or source code of this topic, you should put those files inside of the root folder of your
HTTP server: webcam.js, webcam.swf, and shutter.mp3.
• The API Calls: As you can see, those are some of the most important API calls of the webcam.js library:
o webcam.set_hook
o webcam.set_api_url
o webcam.snap
o webcam.get_html
• The webcam.set_hook API Call: A coder can use this API call when he/she wants to set a callback function that is
going to hook or perform one of those three events:
o onLoad: The application is going to fire if a client is able to load a movie inside of a website.
o onComplete: The application is going to fire if a JPEG image is loaded inside of an HTTP server.
o onError: The application is going to fire if there is an error or mistake.
Because we are developing a computer application that is going to upload a JPEG image to our HTTP server, we
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
306
are going to use the webcam.set_hook API call and its onComplete event or hook.
• The webcam.set_api_url API Call: A coder can use this API call to set a URL or script, which is going to include
or contain those kinds of instructions to connect to a database and upload a picture to one of the directories of an
HTTP server. Thanks to this API call, an HTTP server can get and upload a JPEG image to one of its directories
or folder.
• The webcam.snap API Call: After using the webcam.set_hook and webcam.set_api_url API calls, a coder has to
use the webcam.snap API call to be able to take a picture and upload that picture to an HTTP server. When a
coder is using the webcam.snap instruction, he/she has to include this instruction or code inside of a function;
furthermore, the function of the webcam.snap API call has to be inside of the input element of a button. If a client
or user clicks on the button, the webcam.snap API call will take a picture and upload that JPEG image to one of
the directories or folder of an HTTP server.
• The webcam.get_html API Call: An individual can use this API Call to specify the webcam dimensions. More
specifically, when a client is opening a browser to take a picture of himself/herself, he/she is going to see the
webcam image inside of his/her browser, and a coder can change the dimensions of the webcam image through
the webcam.get_html API Call. When a coder wants to specify or set the webcam image dimensions, he/she has to
type a line similar to this:
document.write(webcam.get_html(width, length));.
width: In this field, a coder has to specify the width.
length: In this parameter, an individual has to set the length.
• I/O Streams of PHP: PHP is a computer programming language that provides different kinds of I/O streams,
including php://input and php://output. On the one hand, a coder can use the php://input stream when he/she
wants to read the data or stream that comes from a source, such as the data that comes from an HTTP server or a
file that is located on an HTTP server; on the other hand, a coder can use the php://output stream when he/she
wants to write data into a source or server.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
307
• The file_get_contents Function: Similar to the stream_get_contents function of the exercise 113, a coder can use
the file_get_contents function when he/she wants to get the content or data of a file/variable. In this section, we
will use a line similar to this: file_get_contents('php://input');. What is the meaning of the previous line? The
previous line is to get the content of the php://input stream.
• The file_put_contents Function: A coder can use the file_put_contents function when he/she wants to write or put
data into a file. If a file does not exist, the file_put_contents function is going to use the first parameter to create a
file, which means that this function can be used by a coder to create files. As you can see, this is the syntax of the
file_put_contents function:
file_put_contents(file, data);
File: In the first parameter, a coder has to type the name of a file, which is going to be the file that will receive
data or information from a variable that is located on the second parameter of the file_put_contents function.
Before typing a filename inside of the first parameter, an individual may use some codes to specify some features
related to the file that he/she wants to create or put data; for example, an individual may use some codes to
specify an extension and/or directory. In this section, we will use the first parameter of the file_put_contents
function to create a file inside of the pictures directory of our HTTP server.
Data: In the second field, an individual has to type the data or information that he/she wants to write or put into a
file. Usually, in the second parameter, a coder has to type a variable with information or data, and the information
or data of that variable will be moved to the variable or file that is located on the first parameter of the
file_put_contents function. Before typing a data variable inside of the second parameter, an individual may use
the file_get_contents function to get some data; then, after getting some data or information through the
file_get_contents function, a coder can use that data on the second parameter of the the file_put_contents function.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
308
Practice: First, you have to create the pictures folder because your pictures will be saved on that directory.
Second, you have to create the index.php file; then, you have to put those codes on the index file:
<html>
<body>
<script src="webcam.js"></script> <!--Adding the webcam.js library.-->
<script>
document.write(webcam.get_html(250, 250)); //Adding the webcam dimensions.
webcam.set_api_url('AGene_Handler.php'); //An API of webcam.js to set an URL.
webcam.set_hook('onComplete'); //An API of webcam.js to set the hook.
function AGene_Snap() //A function to take and upload a picture to the server.
{
webcam.snap(); //An API of webcam.js to snap.
alert('Taked!'); //An alert window after a snap.
}
</script>
<!--The Snap Button-->
<form><input type=button value="Button" onClick="AGene_Snap()"></form>
</body>
</html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
309
Third, you have to create the AGene_Handler.php file and put those codes inside of the AGene_Handler file:
<?php
//Setting the three features of an image or picture: (1) Directory. (2) Name. (3) Extension.
$picture_name = "pictures/". //Adding the directory where the picture will be uploaded.
date('M-d-Y . h.i.sa'). //The picture name, which will be the current computer time.
".jpg"; //Adding the extension of the picture.
//Using a function to get data from the php://input stream.
$jpeg_data = file_get_contents('php://input');
//Using a function to put data into the picture_name variable; then, this function will create an image.
$file = file_put_contents($picture_name, $jpeg_data);
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
310
Result:
After opening the index.php file, you will see something similar to this:
Then, after clicking on Button, you will see a new window:
After opening the pictures directory that is inside of your HTTP server, you will see a JPEG image like this:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
311
Exercise 136: PHP Projects: A Webcam Project v2 Theory: • A Webcam Project v2: In the previous exercise, we learned how use the webcam.js JavaScript library to develop
a computer application that takes pictures and upload those pictures to an HTTP server. In the second version of
this project, we will learn how to use two API calls that are known as webcam.configure and webcam.set_quality.
• The webcam.configure API Call: A coder can use the webcam.configure API call when he/she wants to add a
button that could be used by a client to configure the settings of a webcam. As you should know, a client can use
the settings button for a great variety of purposes; for example, if a client is using two or more webcams on
his/her computer, he/she can use the settings button to choose only one of his/her webcams.
• The webcam.set_quality API Call: An individual can use the webcam.set_quality API call when he/she wants to
specify or set the quality of a picture or image. Thanks to this API call, a coder has the opportunity of choosing
the quality of a JPEG image in a scale of one to one-hundred.
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
312
Practice: First, you have to create the pictures folder because your pictures will be saved on that directory.
Second, you have to create the index.php file; then, you have to put those codes on the index file:
<html> <body> <script src="webcam.js"></script> <!--Adding the webcam.js library.--> <script> document.write(webcam.get_html(250, 250)); //Adding the webcam dimensions. webcam.set_quality(100); //Adding the picture quality (1-100). webcam.set_api_url('AGene_Handler.php'); //An API of webcam.js to set an URL. webcam.set_hook('onComplete'); //An API of webcam.js to set the hook. function AGene_Snap() //A function to take and upload a picture to the server. { webcam.snap(); //An API of webcam.js to snap. alert('Taked!'); //An alert window after a snap. } </script> <form> <!--The button of "Configure Settings"--> <input type=button value="Configure settings" onClick="webcam.configure()"> <!--The Snap Button--> <input type=button value="Button" onClick="AGene_Snap()"> </form> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
313
Third, you have to create the AGene_Handler.php file and put those codes inside of the AGene_Handler file:
<?php
//Setting the three features of an image or picture: (1) Directory. (2) Name. (3) Extension.
$picture_name = "pictures/". //Adding the directory where the picture will be uploaded.
date('M-d-Y . h.i.sa'). //The picture name, which will be the current computer time.
".jpg"; //Adding the extension of the picture.
//Using a function to get data from the php://input stream.
$jpeg_data = file_get_contents('php://input');
//Using a function to put data into the picture_name variable; then, this function will create an image.
$file = file_put_contents($picture_name, $jpeg_data);
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
314
Result:
After opening the index.php file, you will see something similar to this:
Then, after clicking on Button, you will see a new window:
After opening the pictures directory that is inside of your HTTP server, you will see a JPEG image like this:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
315
Exercise 137: PHP Projects: Creating a Login System v1 Theory: • Creating a Login System: In the next exercise, you will learn how to create a login system. What is a login
system? A login system is a computer application where a user/admin/internaut has to type a username/email and
a password. After typing a username/email and a password, an individual may gain access to a private script,
form, or program. One of the most interesting points that a coder should know about the login systems is that
he/she can develop a login system for a great variety of web-applications, including blogs, forums, stores,
administrative panels, and more.
Practice: First, you have to open the MySQL command line and type those commands:
create database AGene_Database103; use AGene_Database103
CREATE TABLE Gene_Table_A ( id int(4) NOT NULL auto_increment, username varchar(65) NOT NULL, password varchar(65) NOT NULL, PRIMARY KEY (id) ) ;
INSERT INTO Gene_Table_A VALUES (1, 'Socket_0x03', '30303030'); Second, you have to create the index.php file and put those codes on the index file: <html> <body> <form name="form1" method="post" action="AGene_Check.php"> Admin: <input name="AGene_User" type="text" id="AGene_User"> Password: <input name="AGene_Pass" type="text" id="AGene_Pass"> <input type="submit" name="Submit" value="Login"> </form> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
316
Third, you have to create the AGene_Check.php file, and you have to put those codes on the AGene_Check file:
<?php mysql_connect("localhost", "root", "30303030"); // Connecting to DB mysql_select_db("AGene_Database103"); // Selecting DB $AGene_User = $_POST['AGene_User']; // Defining User $AGene_Pass = $_POST['AGene_Pass']; // Defining Password $result = mysql_query("SELECT * FROM Gene_Table_A WHERE username='$AGene_User' and password='$AGene_Pass'"); $AGene_Counting_NR = mysql_num_rows($result); // The mysql_num_rows function to count the number of rows if($AGene_Counting_NR == 1) // An if-else after the mysql_num_rows function... { session_register("AGene_User") . session_register("AGene_Pass") . header("location:admin.php"); } else { print "Wrong Username/Password"; } ?>
Fourth, you have to create the admin.php file; then, you have to put those codes inside of the admin file:
<?php session_start(); if (!isset( $_SESSION['AGene_User'])) { header("location:index.php"); } else { print "<h1>Admin Panel</h1>"; } ?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
317
Result – The MySQL Command Line:
Result – Wrong Username/Password:
Result – Right Username and Password:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
318
Exercise 138: PHP Projects: Creating a Login System v2 Theory: • Creating a Login System v.2: In the next exercise, I am going to use Cascading Style Sheets (CSS) to improve the
previous login system.
Practice: First, you have to open the MySQL command line and type those commands:
create database AGene_Database103; use AGene_Database103
CREATE TABLE Gene_Table_A ( id int(4) NOT NULL auto_increment, username varchar(65) NOT NULL, password varchar(65) NOT NULL, PRIMARY KEY (id) ) ;
INSERT INTO Gene_Table_A VALUES (1, 'Socket_0x03', '30303030'); Second, you have to create the index.php file and put those codes on the index file: <html> <body> <head> <link rel="stylesheet" href="styles.css"> </head> <h1>Login System</h1> <div style="margin-left: 30%"> <form name="form1" method="post" action="AGene_Check.php"> <p><input name="AGene_User" type="text" id="AGene_User" value="Admin"> </p> <p><input name="AGene_Pass" type="text" id="AGene_Pass" value="Password"> </p> <p> <input type="submit" name="Submit" value="Login"> </p> </form> </div> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
319
Third, you have to create the AGene_Check.php file, and you have to put those codes on the AGene_Check file:
<html> <body> <head> <link rel="stylesheet" href="styles.css"> </head> <?php mysql_connect("localhost", "root", "30303030"); // Connecting to DB mysql_select_db("AGene_Database103"); // Selecting DB $AGene_User = $_POST['AGene_User']; // Defining User $AGene_Pass = $_POST['AGene_Pass']; // Defining Password $result = mysql_query("SELECT * FROM Gene_Table_A WHERE username='$AGene_User' and password='$AGene_Pass'"); $AGene_Counting_NR = mysql_num_rows($result); // The mysql_num_rows function to count the number of rows if($AGene_Counting_NR == 1) // An if-else after the mysql_num_rows function... { session_register("AGene_User") . session_register("AGene_Pass") . header("location:admin.php"); } else { print "Wrong Username/Password"; } ?> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
320
Fourth, you have to create the admin.php file; then, you have to put those codes inside of the admin file:
<html>
<body>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<?php
session_start();
if (!isset( $_SESSION['AGene_User']))
{
header("location:index.php");
}
else
{
print "<h1>Admin Panel</h1>";
}
?>
</html>
</body>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
321
Fifth, you have to create the styles.css file; then, you have to put those codes inside of the styles file: body {
text-align: center;
background-color:lightgrey;
}
p {
text-align: center;
color: #808080;
}
input
{
text-align: center;
color: #686868;
background-color: #c0c0c0;
margin-left:20px;
}
h1 {
text-align: center;
color: #808080;
}
div {
border: 2px solid #a1a1a1;
padding: 10px 40px;
background: #dddddd;
width: 300px;
border-radius: 25px;
}
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
322
Result – The MySQL Command Line:
Result – Right Username and Password:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
323
Exercise 139: PHP Projects: Medical Record Form v1 Theory: • Medical Record Form: In the next exercise, you will learn how to develop a basic medical record form, which is
going to include two PHP scripts: data.php and records.php.
The Data File: One of the most important functions of the data.php file is to store data inside of a database; for
example, after typing some information inside of the data file and clicking on the save button, the data.php script
is going to store the patient ID, patient name, surgery cost, and other details inside of a MySQL database. In this
script, we will use our PHP form knowledge of the exercises 105-109 to understand the data.php form;
furthermore, we will use our MySQL knowledge of the exercises 123-134 to understand the data.php file.
The Records File: One of the most important functions of the records.php file is to retrieve information from a
database and display that information inside of a browser. In this script, we will use the MYSQL_FETCH_ARRAY
function of the exercise 134 to display some rows.
Practice: First, you have to open the MySQL command line and type those commands:
create database agene_database_p;
use agene_database_p
CREATE TABLE medical_records(
agene_id INT NOT NULL AUTO_INCREMENT,
agene_name VARCHAR(23) NOT NULL,
agene_cost INT NOT NULL,
agene_date timestamp(14) NOT NULL,
primary key ( agene_id ));
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
324
Second, you have to create the data.php file and put those codes on the data file: <html> <body> <h1>Medical Records</h1> <form method="post" action="<?php $_PHP_SELF ?>"> Patient Name: <input name="agene_name" type="text" id="agene_name"><br><br> Surgery Cost: <input name="agene_cost" type="text" id="agene_cost"> <input name="add" type="submit" id="add" value="Save"> </form> <?php $Gene_DB = mysql_connect("localhost","root","30303030"); mysql_select_db('agene_database_p'); //Selecting DB $agene_name = ($_POST['agene_name']); $agene_cost = $_POST['agene_cost']; $sql = "INSERT INTO medical_records ". "(agene_name,agene_cost, agene_date) ". "VALUES('$agene_name',$agene_cost, NOW())"; $Gene_Result = mysql_query( $sql, $Gene_DB ); if($Gene_Result) { print "The records have been saved.\n"; mysql_close($Gene_DB); } ?> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
325
Third, you have to create the records.php file; then, you have to put those codes inside of the records file: <?php
$Gene_DB = mysql_connect("localhost","root","30303030"); //Connecting to DB
mysql_select_db('agene_database_p'); //Selecting DB
$sql = 'SELECT agene_id, agene_name, agene_cost, agene_date FROM medical_records';
$Gene_Result = mysql_query( $sql, $Gene_DB );
if($Gene_Result)
{
while($row = mysql_fetch_array($Gene_Result))
{
print "Patient ID: {$row['agene_id']} <br>";
print "Patient Name: {$row['agene_name']} <br>";
print "Surgery Cost: {$row['agene_cost']} <br>";
print "Date: {$row['agene_date']} <br>";
print "<hr>";
}
print "The records have been printed.\n";
mysql_close($Gene_DB);
}
?>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
326
Results: After creating the database and adding some data, your MySQL Command Line will show you those results:
After typing some information inside of the data.php file, you will see a result similar to this:
After opening the records.php file, you will see the patient records:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
327
Exercise 140: PHP Projects: Medical Record Form v2 Theory: • Medical Record Form: In the next exercise, you will learn how to develop a medical record form that is going to
use an administrative login system. Developing an administrative login system is very important for those kinds
of clients who want to store sensitive information, such as patient IDs, patient names, surgery costs, and other
details.
Practice: First, you have to open the MySQL command line and type those commands:
create database AGene_Database105;
use AGene_Database105
CREATE TABLE Gene_Table_A (
id int(4) NOT NULL auto_increment,
username varchar(65) NOT NULL,
password varchar(65) NOT NULL,
PRIMARY KEY (id)
) ;
INSERT INTO Gene_Table_A VALUES (1, 'Socket_0x03', '30303030');
CREATE TABLE medical_records(
agene_id INT NOT NULL AUTO_INCREMENT,
agene_name VARCHAR(23) NOT NULL,
agene_cost INT NOT NULL,
agene_date timestamp(14) NOT NULL,
primary key ( agene_id ));
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
328
Second, you have to create the data.php file and put those codes on the data file: <html> <body> <h1>Medical Records</h1> <form method="post" action="<?php $_PHP_SELF ?>"> Patient Name: <input name="agene_name" type="text" id="agene_name"><br><br> Surgery Cost: <input name="agene_cost" type="text" id="agene_cost"> <input name="add" type="submit" id="add" value="Save"> </form> <?php $Gene_DB = mysql_connect("localhost","root","30303030"); mysql_select_db('AGene_Database105'); //Selecting DB $agene_name = ($_POST['agene_name']); $agene_cost = $_POST['agene_cost']; $sql = "INSERT INTO medical_records ". "(agene_name,agene_cost, agene_date) ". "VALUES('$agene_name',$agene_cost, NOW())"; $Gene_Result = mysql_query( $sql, $Gene_DB ); if($Gene_Result) { print "The records have been saved.\n"; mysql_close($Gene_DB); } ?> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
329
Third, you have to create the admin.php file; then, you have to put those codes inside of the admin file:
<html> <body> <h1>Admin Panel</h1> <hr> <?php session_start(); if (!isset( $_SESSION['AGene_User'])) { header("location:index.php"); } else { $Gene_DB = mysql_connect("localhost","root","30303030"); //Connecting to DB mysql_select_db('AGene_Database105'); //Selecting DB $sql = 'SELECT agene_id, agene_name, agene_cost, agene_date FROM medical_records'; $Gene_Result = mysql_query( $sql, $Gene_DB ); if($Gene_Result) { while($row = mysql_fetch_array($Gene_Result)) { print "Patient ID: {$row['agene_id']} <br>"; print "Patient Name: {$row['agene_name']} <br>"; print "Surgery Cost: {$row['agene_cost']} <br>"; print "Date: {$row['agene_date']} <br>"; print "<hr>"; } print "The records have been printed.\n"; mysql_close($Gene_DB); } } ?> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
330
Fourth, you have to create the AGene_Check.php file and put those codes inside of the AGene_Check file:
<?php mysql_connect("localhost", "root", "30303030"); // Connecting to DB mysql_select_db("AGene_Database105"); // Selecting DB $AGene_User = $_POST['AGene_User']; // Defining User $AGene_Pass = $_POST['AGene_Pass']; // Defining Password $result = mysql_query("SELECT * FROM Gene_Table_A WHERE username='$AGene_User' and password='$AGene_Pass'"); $AGene_Counting_NR = mysql_num_rows($result); // The mysql_num_rows function to count the number of rows if($AGene_Counting_NR == 1) // An if-else after the mysql_num_rows function... { session_register("AGene_User") . session_register("AGene_Pass") . header("location:admin.php"); } else { print "Wrong Username/Password"; } ?> Fifth, you have to create the index.php file and put those codes inside of the index file: <html> <body> <form name="form1" method="post" action="AGene_Check.php"> Admin: <input name="AGene_User" type="text" id="AGene_User"> Password: <input name="AGene_Pass" type="text" id="AGene_Pass"> <input type="submit" name="Submit" value="Login"> </form> </body> </html>
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
331
Results:
After creating the database and adding some data, your MySQL Command Line will show you those results:
After typing some information inside of the data.php file, you will notice a message about the patient records:
After opening the index.php file and typing some data, you will see a result similar to this:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
332
Then, after clicking on the login button, you will see an administrative panel showing the patient records:
The Easiest Way to Learn PHP & MySQL Alvaro J. Gene
333
CONCLUSION
After reading this tutorial, you will expand your knowledge and enhance your programmer skills to be able to
develop different kinds of computer applications; for example, after reading this paper, you will be able to develop
some PHP applications like PHP forms, socket programs, clients, servers, and many other computer programs.
Moreover, thanks to this tutorial, you can use your knowledge and programmer skills to build a great variety of login
systems, and a coder can use his/her login systems inside of many PHP applications, including blogs, forums, chats,
administration panels, and many other applications. In addition to the basic PHP applications and login systems, one
of the most interesting points about The Easiest Way to Learn PHP & MySQL is that a coder can use this tutorial to
learn how to develop some security tools, such as Port-Scanners, HTTP checkers, and more.
Not only does this tutorial teach you how to develop basic PHP applications and security-tools, but also how
to use different kinds of markup/programming languages inside of a PHP program to improve its functionality and
visual aspect. For instance, The Easiest Way to Learn PHP & MySQL can teach you how to use different kinds of
Ajax techniques to create some computer applications without typing a lot of codes; furthermore, The Easiest Way to
Learn PHP & MySQL can teach you how to use the JavaScript JQuery library and the Cascading Style Sheets (CSS)
to improve the graphical user interface of a computer program.
PHP is one of the most popular computer programming languages for web-development. Therefore, there are
many corporations/companies/organizations who want to hire or employ PHP developers for different kinds of
projects; for instance, there are some corporations who are hiring PHP developers for the development of ecommerce
or shopping products, contact forms, registration forms, and many other projects. In addition to the development of
PHP applications, there are some corporations/companies/organizations who want to hire or employ those kinds of
individuals who have knowledge on web-development and computer security. As previously stated, there are a lot of
PHP applications with vulnerabilities or security flaws, and a coder can use his/her computer security knowledge to
secure those PHP applications.