You are on page 1of 178

SQL

CRASH COURSE

The Ultimate Beginners Course to
Learning SQL Programming in Under 12
Hours

By Eprogramy

Copyright 2015
All rights reserved. No portion of this book may be reproduced -mechanically,
electronically, or by any other means, including photocopying- without the permission of
the publisher.

Disclaimer
The information provided in this book is designed to provide helpful information on the
subjects discussed. The authors books are only meant to provide the reader with the
basics knowledge of SQL Programming, without any warranties regarding whether the
student will, or will not, be able to incorporate and apply all the information provided.
Although the writer will make her best effort share his insights. This book, nor any of the
authors books constitute a promise that the reader will learn SQL Programming within a
certain timeframe. The illustrations are guidance.

Table of contents
Introduction: Welcome to Your New Programming Language

Chapter 1: SQL Programming Language

History of MySQL

What is MySQL?

Why PHP and MySQL?

Chapter 2: Setting up MySQL and PHP

Chapter 3: MySQL Data Types

Numeric Data Types

Date and Time Types

String Data Types:

Chapter 4: Creation of Databases and Tables

Chapter 5: Inserting Data in to Databases

Chapter 6: Updating and Deleting Data

Updating Data

Deleting Data

Chapter 7: Selecting and Limiting Data


Chaptet 8: Joining Data

Chapter 9: Useful SQL Functions

Chapter 10: Application of MySQL in Web-Development

HTML

Tags

CSS

External CSS

Chapter 11: PHP Language Structure

Variables

What is a Variable?

Variable Types

Instance Variables

Class/Static Variables

Local Variables

Data Types

Declaring a Variable


Using a variable

Operators

The Arithmetic Operators

The Assignment Operators

Boolean Logic

If Statements

The Relational Operators

The Logical Operators

Combining Operators

Loops and Arrays

Loops

For Loops

While Loop

Continue keyword

Break keyword

Arrays


Functions and Classes

Chapter 12: PHP Integration into MySQL

Summary of SQL

Summary of data types in MySQL

Fundamental Sorts

SQL Server Data Types

String sorts

Other Information Sorts

Chapter 13: Application of MySQL with Login/Registration

Login System Creation

Chapter 14: Registration System Creation

Chapter 15: In Closing

Check Out My Other Books

About the Author

Introduction
Welcome to Your New Programming Language

So, youve decided to learn SQL Programming? Well, congratulations and welcome to
your new Programming Language! Youre going to love it!

In Eprogramy we believe that the foundation of a good education is to provide the tools
able to open the doors of the future. It is indisputable that the world has entered an era in
which we all have everything at the fingertips. Social needs have changed. Thus, today
communication has changed. Communication opens doors, so it is our challenge to learn
how to communicate. In Eprogramy we want you to learn how to communicate with a
new language: The programming language. This language allows us to use our PC or
notebook to create.

Maybe the road is difficult and hard, but we will give the reader the tools to make learning
enjoyable and fruitful. Well show all aspects necessary to learn how to program. From
the ABCs to the solution of the most common programming problems and much, much
more. Always with the help of numerous examples that will contribute to a better
understanding

We know what we do and believe that you are fully capable of incorporating our
teachings.

The doors of the future are here. Lets go step by step together.

Lets get started!

Eprogramy Team

Chapter 1
SQL Programming Language

History of MySQL

MySQL is an open source database item which was made by MySQL AB. This
organization was established in 1995 in Sweden. Before long, the organization was
obtained by Sun Microsystems for almost one-billion dollars.

Heres a course of events of MySQL ABs history from the initiation of their organization,
plotting their achievements and development.

1995

MySQL AB established by Michael Widenius (Monty), David Axmark and Allan
Larsson in Sweden.

2000

MySQL goes Open Source and discharges programming under the terms of the GPL.
Incomes dropped 80% thus, and it took a year to compensate for it.

2004

Ended the year with $20 million in income.

2005

Ended the year with $34 million in income in light of 3400 clients.

2006

8 million dynamic establishments.

MySQL has 320 workers in 25 nations, 70 percent of whom telecommute.

Ended the year with $50 million in income.


2007

Ended the year with $75 million in income.

2008
Sun Microsystems procured MySQL AB for more or less $1 billion.

What is MySQL?

MySQL is a powerful open source database server built based on a relational database
management system (RDBMS) and is capable of handling a large concurrent database
connection. It can be sent commands by writing out queries it can understand, and then
doing something with them, like manipulating a database.

PHP is a server-side programming language that can be used to make static web pages
more dynamic in the sense where it can do logical operations in the backend of a server
and return/output results accordingly on a page. The reason Im mentioning PHP is
because PHP and MySQL together can build very powerful and scalable Web / Internet /
Intranet Applications if knowledge of both of them has been attained.

Why PHP and MySQL?



Now lets go over why PHP is a great programming language to know. It is a quick and
easy to use server side scripting language designed for web development and also many
other uses. It also has great community support which helps out with many solutions to
problems that developers face commonly with PHP.

Due to the fact that it has a lot of great community support, there are many third party
programs available for free to help out and ease the use of programming PHP. Considering
that PHP has community support also leads one to think of the great list of inbuilt
functions for PHP that will allow a developer less time to worry about custom coding his
own functions and worry more about what he needs accomplished.

We have talked a lot about how PHP is a server side scripting language but we havent
really talked about what that means. There are two types of scripting languages: server
side and client side. An example of a client side language would be Javascript and an
example of a server side language would be PHP.

MySQL is open-source meaning that it is a free development tool and a large community
is able to support it and make improvements on it continuously. When used correctly with
PHP, database systems can be built with clean and simple usability, complex functionality,
speed, power and scalability.

Chapter 2
Setting up MySQL and PHP

The first thing you want to do is download XAMPP, which will allow you to run PHP
code and manipulate MySQL databases. After the successful installation of XAMPP go
to the folder it was installed and execute xampp.control.exe. Then, press the start button at
Apache and MySQL.

Press the start button at the MySQL row.


When MySQL has successfully started, there are still a few more things you must do.
There are two different ways to actually manage and administrate the MySQL server and
its databases.

Start the apache server and open your browser and type in localhost or 127.0.0.1. Once
you have done this, then an XAMPP status page should appear. Navigate to the security
settings and change your MySQL root password. Then, you are able to browse to
PHPMyAdmin under localhost or you can download a Windows MySQL client. An
example would be Navicat or MySQL Workbench. Once you have installed it, youre able
to log in to your MySQL Server with the password that you set. So you can either use a
third party program to access your database or use PhpMyAdmin built in to XAMPP.


Now for PHP files, you must head to the XAMPP directory where it was installed and find
a folder named htdocs. This folder is going to contain all the files that will popup when
you do localhost/filename.html. So if you have an index.html file in the htdocs folder, you
can refer to it accordingly. Over here, you can create a .php extension file with PHP code
and HTML code and put it in the folder. Then you can call it in the browser and it will
execute. Reason you cant just test it like a normal HTML file is because since PHP
depends on a server, like MySQL does, it must be done this way. If youre using a web
hosting service, contact them to sort out how to do what we did just now over XAMPP.
Also, note that youre able to send queries in PHPMyAdmin to your database. If youre
unsure how, you can view their documentation.

Chapter 3
MySQL Data Types

MySQL supports a number of data types in several categories ranging from numeric types,
data and time types, string types and more. These data types might not make sense right
now but will be very useful later on in this guide. Here is a full list of all the data types in
MySQL. Remember, you dont need to memorize this; it will always be here for you to
refer to.

Numeric Data Types



INT:


Definition: Normal sized integer

Signed: Allowable range is from -2147483648 to 2147483647

Unsigned: Allowable range is from 0 to 4294967295

TINYINT:


Definition: Very small integer (4 digits max)

Signed: Allowable range is from -128 to 127

Unsigned: Allowable range is from 0 to 255

SMALLINT:


Definition: Small integer (5 digits max)

Signed: Allowable range is from -32768 to 32767

Unsigned: Allowable range is from 0 to 65535

MEDIUMINT:


Definition: Medium-sized integer (9 digits max)

Signed: Allowable range is from -8388608 to 8388607

Unsigned: Allowable range is from 0 to 16777215



BIGINT:


Definition: Large-sized Integer (20 digits max)

Signed: Allowable
9223372036854775807

range

is

from

-9223372036854775808

to


Unsigned: Allowable range is from 0 to 18446744073709551615

FLOAT(M,D):


Definition: Floating-point number (24 places decimal precision ) [unsignable]

Decimals: Display length and number of decimals is definable

Default: 10, 2 (10 = total number of digits including decimals and 2 = number of
decimals)

DOUBLE(M,D):


Definition: Double precision floating-point number being able to reach 53 places
[unsignable]

Decimals: Display length and number of decimals is definable

Default: 16, 4 (16 = total number of digits including decimals and 4 = number of
decimals)

DECIMAL(M,D):


Definition: Unpacked floating point number [unsignable]


Decimals: Display length and number of decimals is definable

Default: 16, 4 (16 = total number of digits including decimals and 4 = number of
decimals)

Date and Time Types



The MySQL date and time data types are:

DATE - A date in YYYY-MM-DD configuration, between 1000-01-01 and 9999-12-31.
For instance, December 30th, 1973 eventual put away as 1973-12-30.

DATETIME - A date and time mix in YYYY-MM-DD HH:MM:SS organization,
between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For instance, 3:30 toward the
evening on December 30th, 1973 future put away as 1973-12-30 15:30:00.

TIMESTAMP - A timestamp between midnight, January 1, 1970 and at some point in
2037. This resembles the past DATETIME form, just without the hyphens between
numbers; 3:30 toward the evening on December 30th, 1973 eventual put away as
19731230153000 ( YYYYMMDDHHMMSS ).

TIME - Stores the time in HH:MM:SS form.

YEAR(M) - Stores a year in 2-digit or 4-digit form. On the off chance that the length is
indicated as 2 (for instance YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). On the off
chance that the length is determined as 4, YEAR can be 1901 to 2155. The default length
is 4.

String Data Types:



CHAR(M) - A settled length string somewhere around 1 and 255 characters long (for
instance CHAR(5)), right-cushioned with spaces to the predefined length when put away.
Characterizing a length is not needed, but rather the default is 1.

VARCHAR(M) - A variable-length string somewhere around 1 and 255 characters long;
for instance VARCHAR(25). You must characterize a length when making a VARCHAR
field.

BLOB or TEXT - A field with a most extreme length of 65535 characters. BLOBs are
Paired Large Objects and are utilized to store a lot of double information, for example,
pictures or different sorts of records. Fields characterized as TEXT additionally hold a lot
of information; the contrast between the two is that sorts and correlations on put away
information are case touchy on BLOBs and are not case delicate in TEXT fields. You
dont indicate a length with BLOB or TEXT.

TINYBLOB or TINYTEXT - A BLOB or TEXT segment with a most extreme length
of 255 characters. You dont indicate a length with TINYBLOB or TINYTEXT.

MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT segment with a most
extreme length of 16777215 characters. You dont indicate a length with MEDIUMBLOB
or MEDIUMTEXT.

LONGBLOB or LONGTEXT - A BLOB or TEXT section with a most extreme length
of 4294967295 characters. You dont determine a length with LONGBLOB or
LONGTEXT.

ENUM - A count, which is an extravagant term for rundown. At the point when
characterizing an ENUM, you are making a rundown of things from which the worth
must be chosen (or it can be NULL). Case in point, on the off chance that you needed
your field to contain An or B or C, you would characterize your ENUM as ENUM
(A, B, C) and just those qualities (or NULL) could ever popula

Chapter 4
Creation of Databases and Tables

Databases in MySQL can understand a query, which is simply a request for something to
happen. When someone sends a query to a database, depending on what the query is
asking for the database to do, it will function accordingly. There many types of queries
ranging from creation of tables, inserting data, selecting data, joining data, deleting data,
updating data, limiting data, and much more.

In order to create a database, you must specify in a query that you would like to do so.
This can be done using the CREATE keyword and then the type of item you would like to
create. In this case, we would like to create a Database, so we specify using the
DATABASE keyword and then the name of the database that you would like to create.
Here is a full rundown of how it would like query wise:

CREATE DATABASE myDB

In the above example, you can see that the first element in the CREATE keyword followed
by the DATABASE keyword as a specifier and then finally the database name. Now, lets
apply the same philosophy when working with creating tables.

In order to create a table, which is essentially a section in the database which would hold
all the rows and columns that are relevant to the tables use This can be done by doing
the same thing we did last time to make a database.

First, you must use the CREATE keyword, followed by the TABLE keyword as a specifier
and then finally, name the table. The only difference between creating a database and
creating a table is that with creating a table, you are able to create the columns and their
data-types associated so your database can be ready to have information filled in it.

Now, as you know, we have gone over all the data types previously, but you didnt have to
memorize them. They are there for your reference so you can always look at them any
time you want. The first thing you must do to start creating your columns is by making a
parenthesis like so ( and then writing down all the column information and ending it
with ).

Now in order to actually write down the column information, you must start with the
column name. Lets say for example we wanted to have a first name column. Well would
specify the name of the column and say firstname followed by the database of that

column. Well we want our column to have the ability to have text inserted in to it.
Therefore, we say VARCHAR(30) which is a data type allowing text to be inputted in to
the column of firstname. Next, you can place optional attributes after the data type
specification. Lets quickly go over how this might look like.
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
)

The optional attributes after the data-type specification, can be explained here:

NOT NULL Null values are not allowed in these records

DEFAULT value If no value is given, a certain default value will be assigned

UNSIGNED Makes it so that numbers can only be greater than or equal to zero

AUTO INCREMENT Auto increments a column number by 1 whenever a new
record is added this is mostly used for columns referring to an id of something

PRIMARY KEY - Used to uniquely identify the rows in a table and is used with
AUTO INCREMENT

It is recommended to use an id column, which would have AUTO INCREMENT and be
primary as it would make it easier and efficient to refer to different records.

Chapter 5
Inserting Data in to Databases

Now that we have had our database created along with our table with all the necessary
columns and the data types and attributes associated with them, we can start to insert data
in our table. Now how exactly do we do this?

When inserting information, you might need to watch out for some syntax rules that might
mess up your query. The first one is that whenever youre working with an SQL query
within PHP, it must be quoted. This isnt the case when youre working with simply
sending queries to your database without the use of a programming language that can
communicate with MySQL.

The next thing you need to watch out for is that whenever you want to insert information
of string type (text), they must be quoted. For example, if you want to insert data in to the
second record (row) of the first name column and change it to John instead of Peter
then you must point out this new information using a quotation mark. Again, this will
make more sense to you once we have actually started to develop a query to do stuff like
this. Also, what I have just explained is an idea of updating data in databases which is
what well be talking about soon after this section of the guide.

Moving on, the next syntax rule you must remember is that if youre updating or inserting
data of any numeric value, it must not be quoted. In many programming languages, even,
including PHP, when you are declaring variables, you dont set your value of the variable
in quotes if it is a number. That way, the program can differentiate the difference between
what text (string) is and what a number (int/double/float) is.

Finally, if youre ever wanting to set anything or add anything NULL which simple means
to make the record at that specific section empty, then that keyword must not be quoted. If
it is quoted, it will be mistaken as a string, and therefore have the world NULL literally be
printed out in the specific record.

Now that we have finally went over some of the basic syntax rules to look out for when
inserting data in to MySQL, lets get started. The INSERT INTO statement is used to add
new records to a MySQL table. Once you have used these keywords, the next thing you
must write is the table name to specify what you want to insert your information in to.
Then, you create open and closed parenthesis, and within these parenthesis, you list down
all the column names you want part of the insert command. The way these columns can be
noted is by separating them with commas to indicate that it is not one column with a huge
name as separating them with a space or a new line wont suffice.


INSERT INTO table_name (column1, column2, column3)

Once you have specified what table to insert into and the column names associated with
the insertion, you must now specify the values to go in to each column. The first thing you
must do is use the VALUES keyword to actually specify that youre about to indicate all
the values that will fall in to the columns specified prior. You do this by using the
VALUES keyword and then having opening and closing parenthesis which surround
column separated values. Now, the order in which you put these values in to the
parenthesis are important because how ever you made the order in putting down the
column names when you were specifying them, is exactly the order the values will
correspond their column to. So column1 will specify value1 which are the first two
elements of the variety of comma separated elements you put down for the columns and
values.

VALUES (value1, value2, value3)

Here is the final outlook on the skeleton of how inserting data in to MySQL works:

INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3)

Chapter 6
Updating and Deleting Data
Updating Data

Lets start with the update functionality in SQL which simply allows you to update
existing records in your MySQL database (specifically table). In order to update values in
your database, you must first start with the UPDATE keyword and then the table name.
This will simply specify which table to update in the database. Once this has been done,
you can use the SET keyword.

Once you have used the SET keyword, you are able to set each column record to a specific
value. This can be done by saying column_name = value, column_name2 = value and so
on and so forth. This will allow you to set different columns to a certain value. The
problem with this statement so far is the fact that by running this statement, it will go
through ALL records and set everything to a certain value. In order to specify a specific
row, we must use the WHERE keyword.

The WHERE keyword simply allows you to include some logic in your code where you
can tell the server to only fetch information to update at a specific record that contains a
certain value or data type. Firstly, you must use the WHERE keyword and then specify a
column name like you did after the SET keyword and then have it say column_name =
value which simply means: Update the employee table and set the firstname column to
John and the lastname column to Rane WHERE the id is equal to 5 which essentially
means that it will only update the 5th row, in the case that you have an id column that is
incrementing.

UPDATE table_name
SET column1=value, column2=value2,
WHERE some_column=some_value

As seen above, we are updating a specific table and setting specific columns to certain
values ONLY where a certain condition is met. If the condition of the WHERE clause isnt
met, then nothing will be updated. Lets take a look at the tblEmployee table.

id firstname lastname
1

Thomas

Horga

email

horga@example.com

Matthew

Leliever

matthew@example.com

As shown above, there is an id column, firstname column, lastname column, and an email
column with two rows to indicate that there are two records for each column. Now lets
run our statement:

UPDATE tblEmployee SET lastname=Doe WHERE id=2

Now the table will look like the following:

id firstname lastname
1

Thomas

Horga

Matthew

Doe

email

horga@example.com

matthew@example.com

The last name of Matthew has changed from Leliever to Doe because the query told it
to set the specific lastname record only where the id=2. Since there was an id that was
equal to 2, which was the row of Matthew Leliever, his row was successfully updated to
Matthew Doe as specified in the UPDATE query statement.

Deleting Data

In order to delete data in MySQL, we must use the DELETE keyword followed by the
FROM keyword. The FROM keyword looks for something to DELETE FROM and in this
case, we want to delete from a table where a specific column is equal to something. Lets
delete Matthews row. In order to this, we must first specify the tblEmployee table and
then specify that we want to delete the row when the id is equal to 2 since that is the row
where Matthew is located.

Now lets say that we didnt know his ID. Well, we can specify his first name instead. The
thing with that is, lets say we have multiple Matthews in our database, and then other
Matthews would also be deleted. That is why it is smarter to go for the id option. But just
in the case that we didnt know the ID, we could use a simple SELECT statement to
retrieve it. We will be learning about this after this topic.

The skeleton of a MySQL query for deleting something will be like the following:

DELETE FROM table
WHERE column = value

Now lets go over a more visual example as I have found that it is easier for people to
learn that way, including myself, especially for databases. This is our tblEmployee table
before affecting it with a DELETE query:

id firstname lastname
1

Thomas

Horga

Matthew

Doe

email

horga@example.com

matthew@example.com

We want to remove Matthew Doe from the tblEmployee table, how exactly do we do this?
Well, lets set up our MySQL query, but before we do, we need to get a few things across.
We know that Matthew is in id=2, therefore we know which row he is and where to delete
him from. We also know our table name, so now we have all the necessary information to
delete the second record. The query would look something like this:

DELETE FROM MyGuests WHERE id=2



Our table would now look like this, after the execution of the above DELETE query:

id firstname lastname
1

Thomas

Horga

email

horga@example.com


Now lets move on to understanding how to SELECT and LIMIT data as these are two
very important and fundamental concepts of MySQL that everyone learning MySQL
should understand.

Chapter 7
Selecting and Limiting Data

When working with a database, it is always important not only to add, update and delete
data from it, but also retrieve information and simply view it. It can act as a way for you to
analytically understand things about whatever your database pertains to. In this section,
we will be learning how to retrieve data from a MySQL Database.

In order to retrieve data from a MySQL Database, we must use the SELECT keyword,
which is going to simply SELECT information from the MySQL Database depending on
whatever parameters you give it. In this case, I want this SELECT statement to select a
few column names from a specific table. Well, remember how we used the FROM
keyword with the DELETE functionality? Well, we are going to do the same thing with
the SELECT keyword.
Here is how it would like as a query:

SELECT cname FROM aTable

We can also have more than one column name be selected by doing the following:

SELECT cname1, cname2, cname3 FROM aTable

Finally, we can also have a way to select all the columns at once by doing the following:

SELECT * FROM aTable

This statement would simply select all the columns and rows. Remember, the WHERE
statement can also be used when selecting data. Also, sometimes when you want to select
a bunch of records, you might want to just limit from too much information being
retrieved because lets say you have millions of records and you send a query to retrieve
all the information. This will be a HUGE load on the server.

This is why it is sometimes smart to limit the data being retrieved from a SELECT
statement. This can be done by simply using the LIMIT keyword and the number of rows
we would like from the result, nothing more. We can also use an OFFSET keyword which
simply starts the search of information at a specific row, and after. Here are a few
examples:


SELECT * FROM cName LIMIT 30
SELECT * FROM cName LIMIT 10 OFFSET 15
SELECT * FROM cName LIMIT 15, 10

This third statement is a shorter way of saying the second statement.

Chaptet 8
Joining Data

In this area of the aide, youre going to figure out how to consolidate lines from distinctive
tables. You will have the capacity to take x measure of columns from Table An in a
particular condition and consolidate it with Table B as needs be. There are numerous
extraordinary uses to joining information, and can turn out to be exceptionally ingenious
in your future tries with the SQL dialect. So as to really join pushes together from two or
more tables taking into account a condition, you must comprehend the four sorts of joins.
How about we begin with the most ordinarily utilized join, INNER JOIN?

The SQL JOIN condition is utilized at whatever point we need to choose information from
2 or more tables.

To have the capacity to utilize SQL JOIN statement to concentrate information from 2 (or
more) tables, we require a relationship between specific segments in these tables.

We are going to show our SQL JOIN illustration with the accompanying 2 tables:

Customers:

CustomerID FirstName LastName

Jane

Doe

Stephen

Boyd

Peter

Allen

Jamie

Doe

Email

DATE
SSN
JOINED

Jane.Doe@hotmail.com 4/8/2014

Boyd@yahoo.com

2/8/2013

Peter.Allen@gmail.com 1/5/2014

jim@hotmail.com

3/5/2014

829

426

532

554



Sales:

CustomerID

Date

AmountInSales

8/2/2014

$82.99

5/3/2014

$98.92

7/2/2014

$45.48

2/9/2014

$76.32

5/6/2014

$324.23


As should be obvious those 2 tables have normal field called CustomerID and because of
that we can remove data from both tables by coordinating their CustomerID segments.

Consider the accompanying SQL articulation:

SELECT Customers.FirstName, Customers.LastName,


SUM(Sales.AmountInSales) AS SPS
FROM Customers, Sales
WHERE Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName


The SQL expression above will choose every single particular client (their first and last
names) and the aggregate separate measure of dollars they have spent.

The SQL JOIN condition has been determined after the SQL WHERE statement and says
that the 2 tables must be coordinated by their separate CustomerID sections.


Here is the aftereffect of this SQL articulation:

FirstName

LastName

SPS

Jane

Doe

$98.92

Stephen

Boyd

$82.99

Peter

Allen

$76.32

Jamie

Doe

$324.23


The SQL explanation above can be re-composed utilizing the SQL JOIN provision like
this:

SELECT Customers.FirstName, Customers.LastName,


SUM(Sales.AmountInSales) AS SPS
FROM Customers JOIN Sales
ON Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName


There are 2 sorts of SQL JOINS INNER JOINS and OUTER JOINS. On the off chance
that you dont put INNER or OUTER pivotal words before the SQL JOIN catchphrase,
then INNER JOIN is utilized. In short Internal JOIN = JOIN (take note of that
distinctive databases have diverse language structure for their JOIN provisos).

The INNER JOIN will choose all columns from both tables the length of there is a match
between the segments we are coordinating on. In the event that we have a client in the
Customers table, which still hasnt made any requests (there are no sections for this client
in the Sales table), this client wont be recorded in the consequence of our SQL question
above.
On the off chance that the Sales table has the accompanying line:


CustomerID

Date

AmountInSales

8/2/2014

$82.99

5/3/2014

$98.92


Whats more, we utilize the same SQL JOIN proclamation from above:

SELECT Customers.FirstName, Customers.LastName,


SUM(Sales.AmountInSales) AS SPS
FROM Customers JOIN Sales
ON Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName


Well get the following result:

FirstName

LastName

SPS

Jane

Doe

$98.92

Stephen

Boyd

$82.99


Despite the fact that Peter and Jamie are recorded as clients in the Customers table they
wont be shown on the grounds that they havent obtained anything yet.

In any case, imagine a scenario in which you need to show all the clients and their
business, regardless of on the off chance that they have requested something or not. Well
do that with the assistance of SQL OUTER JOIN provision.

The second sort of SQL JOIN is called SQL OUTER JOIN and it has 2 sub-sorts called
LEFT OUTER JOIN and RIGHT OUTER JOIN.

The LEFT OUTER JOIN or just LEFT JOIN (you can overlook the OUTER decisive
word in many databases), chooses all the columns from the first table recorded after the
FROM provision, regardless of on the off chance that they have coordinates in the second
table.

On the off chance that we marginally adjust our last SQL articulation to:

SELECT Customers.FirstName, Customers.LastName,


SUM(Sales.AmountInSales) AS SPS
FROM Customers LEFT JOIN Sales
ON Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName


and the Sales table still has the following rows:

CustomerID

Date

AmountInSales

8/2/2014

$82.99

5/3/2014

$98.92


The result will be the following:

FirstName

LastName

SPS

Jane

Doe

$98.92

Stephen

Boyd

$82.99

Peter

Allen

NULL

Jamie

Doe

NULL


As should be obvious we have chosen everything from the Customers (first table). For all
lines from Customers, which dont have a match in the Sales (second table), the SPS
segment has sum (NULL means a section contains nothing).

The RIGHT OUTER JOIN or simply RIGHT JOIN acts precisely as SQL LEFT JOIN,
with the exception of that it gives back all lines from the second table (the right table in
our SQL JOIN articulation).

Chapter 9
Useful SQL Functions

SQL has numerous implicit capacities for performing handling on string or numeric
information. Taking after is the rundown of all valuable SQL assembled in capacities:

SQL COUNT Function - The SQL COUNT total capacity is utilized to include the
quantity of lines a database table.

SQL MAX Function - The SQL MAX total capacity permits us to choose the most
astounding (greatest) esteem for a certain section.

SQL MIN Function - The SQL MIN total capacity permits us to choose the (least)
esteem for a certain segment.

SQL AVG Function - The SQL AVG total capacity chooses the normal worth for certain
table segment.

SQL SUM Function - The SQL SUM total capacity permits selecting the aggregate for a
numeric segment.

SQL SQRT Functions - This is utilized to produce a square base of a given number.

SQL RAND Function - This is utilized to produce an arbitrary number utilizing SQL
order.

SQL CONCAT Function - This is utilized to connect any string inside any SQL
summon.

SQL Numeric Functions - Complete rundown of SQL capacities needed to control
numbers in SQL.

SQL String Functions - Complete rundown of SQL capacities needed to work with
strings in SQL.

Chapter 10
Application of MySQL in Web-Development

HTML

In order to understand how we can implement the MySQL language through application
of web development, and work with it, we must understand the fundamentals of how a
web page in its most basic form works. HTML stands for HyperText Markup Language. It
is the standard markup language used to create static web pages. Through the help of PHP,
HTML/CSS and MySQL, we can make these web pages more dynamic and responsive.

Tags

In HTML, there is a standard convention to starting a statement, and ending one. In
English, we must start our sentences with a capital letter and end them with a period to
maintain a standard flow of writing which is easy to interpret. Well, HTML uses the idea
of Tags to be able to understand what exactly you are writing. There are a few vital tags
you must remember in HTML, and understand what they are used for.

In any HTML file, there is a standard structure that must be followed. Here is sample code
showing an example of it:

<html>

<head>
<title> This the webpage title </title>
</head>

<body>
This is the content of the webpage.
</body>

</html>

When you are making a tag, you must start it with a < symbol and then indicate the
name of the tag, and then end it off with > symbol. Then, the inner portion of the tag,
or within the tag, goes the rest of the code. To end the tag, you do the same convention as
starting the tag, except end it with a /. This is why you see the top of document as:
<html> and the end of the document as </html>.


Visual demonstration:

<tagname> content within tag </tagname>

Now lets analyze the sample code down:

<html>

This is the tag that indicates when the HTML portion of the site will be, so it must be
presented in every HTML document. The tag is then closed at the end of the document.
Therefore, the <html> tag is the parent of all the tags within it, the children.

<head>

This is the tag that would hold all the header information when loading a web-page.
Everything within this tag will not be shown to the user, and is mostly used to initialize
scripts to ready them for use. An example would be to set a script tag in the head section
to prepare for use for the rest of the HTML document. We will have to do this when
learning about the jQuery library.

<title>

The contents of this tag will hold the title of the webpage.

<body>

This is the whole content part of the website. Just line in any essay, you have your thesis,
body and conclusion. This is the same idea in the form of tags.

There are many other tags in HTML that you could look up online. Lets look at a variety
of examples and identify some helpful tags.

<html>

<head>
<title> Example of <p> tag </title>
</head>

<body>
<p> This is a paragraph. </p>
</body>

</html>

The bolded tag in the above example essentially describes a paragraph and formats it in
such a way where it has proper padding/spacing without you having to format it yourself
through the use of CSS (ability to style HTML elements).

<html>

<head>
<title> Example of <p> tag </title>
</head>

<body>
<h1> This is a heading. </h1>
</body>

</html>

This <h1> tag used in the above example simply bolds the text in between it and enlarges
it. All properties of tags that you will be using are editable through CSS which we will be
going through soon.

Here is an example using both tags that we have learned and showing the output. Note that
once you have created a file with HTML in it, you must save the file with a .html
extension. You can then open the file and test it out by opening with a browser of your
choice.


<html>

<head>
<title> Example of <p> tag </title>
</head>

<body>
<h1> This is a heading. </h1>
</body>

</html>

Output:


Finally, lets go over the idea of commenting in HTML. Sometimes you might want to
code something but not exactly print it to the screen, but just want to explain a statement
that you are doing or adding a reminder in the code without having it translate visually on
the web browser so that it wont be able to see it.

You can comment by starting your comment with <! and ending it with

Therefore, if I wanted to comment a certain line, I would do the following with a
functioning paragraph:


<p> This is paragraph text </p>
<! This line prints out a paragraph that says This is a paragraph text >

There are tags, and then there are attributes, which contain values which are then used to
determine how the tags contents are displayed or are interpreted by CSS or PHP. Two
important attributes to note when going in to PHP and CSS are: id and class.

You can use these on any appropriate tag like the <p> tag within the <body> tag.

The format of how an attribute works is like the following:

<p id = content> This is the content of the webpage. </p>

As shown in the example, in order to declare an attribute, you must make space within the
first tag which is <p> and then name the known attribute, so id for example. Then to give
it a value, you must have an equal sign and then two quotation marks and the value within
the quotation marks. In this case, this paragraph, contains the attribute id which is the
value of content - this can be used as a reference for languages like CSS and PHP
through the use of selectors which you will be learning about.

There are still many tags that you can learn about in HTML but these are the basic tags
that you need to know to start writing PHP. Also, you should now understand the basic
structure of an HTML document.

Lets review:

The tag <html> and </html> defines the HTML document, and the tag itself simply
defines the content within it as HTML type so the browser is able to interpret it.

The tag <head> and </head> provide information about the document and initialize any
external scripts or styling sheets.

The tag <title> and </title> simply give information to the browser to display a title of the
HTML document.

The tag <body> and </body> holds all the content of the document which includes the
paragraphs, navigation bars, tables, images, etc.

The tag <h1> and </h1> simply formats text in between it as a header or a title to a
paragraph.

The tag <p> and </p> formats text in between it as a paragraph accordingly.

CSS

CSS stands for Cascading Style Sheets and essentially styles how HTML elements are
displayed on the web browser.

Now, before we move on, lets quickly go over how commenting works in CSS. Just like
in HTML, commenting is useful, and can also be done in CSS, but it has different syntax
for it. In order to comment in CSS, you must use the following notation:

/* This is a comment */

The text in between the slash and symbol is not processed and is simply there for human
reading. So to begin a comment you must do /* and to end a comment you must do */.

Lets scan through the idea of how to write CSS code.

Example:

p {
color: red;
font-size: 14px;
}

In the above example, there are a few critical things to note of the format in the above CSS
code.

The element we must specify when writing CSS code is the tag name or the selector.

p {
color: red;
font-size: 14px;
}

The bolded text indicates the selector, which is the <p> tag, which handles the paragraphs
of the document. If you place any text in between <p> in the body, you will now see the
text being red, and the font size being 14 pixels. Lets move on to analyzing this code
further.

p {
color: red;
font-size: 14px;
}

The bolded text indicates the property in the above example. In every selected tag, you
must indicate properties of that tag, like the color of the text, the size of the text, the style
of the text, the font-weight and much more. You can always look for any property that
youre wanting on the internet. There are many properties and we wont be going over
them in this guide. There are different properties that are applied to different tags. For the
p tag in this instance, we can reference the color property and the font-size property.
Upon referencing them within curly braces (which simply indicates the block of properties
that applies to the selector which is p) and then assigning it to a certain value.

p {
color: red;
font-size: 14px;
}

To assign a certain value to the property of color, you must make a colon symbol which
simply separates the property and the value, and then type out a value accordingly. Once
you have written out the property and the value, use the semi-colon as a way to let the
browser know that you have ended that statement so it can read the next statement.

When working with colors, instead of using the standard red, blue, white, yellow, etc You can reference more specific colors depending on the RGB values (Red, Green, Blue)
which can be obtained using an HTML color selector. This is a link of a site that can give
you HTML color codes for use in your CSS.

Link: http://html-color-codes.info/

To review CSS syntax lets look at it in the following approach:

1.
2.
3.
4.
5.

p
{
color:
red;
}


The code above takes the color of the paragraph and changes the color to red. Each line
has been numbered, but wouldnt be included in the code. It is numbered so we can scan
through each line and go over how it works.

1. Selector/Tag

2. Indicating the start of the selector properties

3. Property/Attribute name with a colon to prepare to indicate the value

4. Value of the Property/Attribute and then a semi-colon to indicate the end of statement

5. Indicating the end of the selector properties for the certain selector which was p

Remember, you can do this as many times, just remember to separate the selector blocks
so the browser doesnt get confused. Well, lets first go over how you can actually start
coding in your HTML document with CSS. To begin, you must go in between your
<head> </head> tags and input the following:

<html>

<head>
<title> This the webpage title </title>

<style type = text/css>
p {
color: red;
font-size: 14px;
}
</style>

</head>

<body>
<h1> This is Header text </h1>
<p id = content> This is the content of the webpage. </p>
</body>

</html>

In order to start coding CSS in an HTML document, you must use the style tag with the
help of the type attribute which references to the standard convention text/css which
you must use every time you want to write CSS in your HTML document. Within this
style tag, is your CSS code which references successfully to all p tags in the HTML
document. Well, what if youd like to only reference a specific paragraph?

Now the reason I like to call p as a selector instead of a tag is because the term selector is
a general term and what can be put in the position of p is also general. Instead of putting
an actual tag that is being referenced in the HTML document, you are able to reference an
id by using a hashtag and then the id name accordingly:

#idname {
color: red;
font-size: 12px;
}


You can also use the selector to reference a tag with a class attribute with a certain
name. For example:

.classname {
color: red;
font-size: 12px;
}

Now you must be wondering why id or class could ever become helpful. Let me enlighten
you with the following sample code:

<html>

<head>
<title> This the webpage title </title>

<style type = text/css>
#content {
color: red;
font-size: 14px;
}
</style>

</head>

<body>
<h1> This is Header text </h1>
<p id = content> This is the content of the webpage. </p>
</body>

</html>

In the above example, you can see that we listed a specific paragraph to be affected by the
change we listed in the CSS within the head tag. This is one way that you can use the id
selector. To use the class selector (not really a big difference, just two preferences) is to do
the following:

<html>

<head>
<title> This the webpage title </title>

<style type = text/css>
.content {
color: red;
font-size: 14px;
}
</style>

</head>

<body>
<h1> This is Header text </h1>
<p class = content> This is the content of the webpage. </p>
</body>

</html>

In the code above, instead of using a hashtag symbol to select a specific attribute with a
specified id name, but rather a class name this time. Using this knowledge of selectors, we
can reference specific HTML elements using PHP and use that to manipulate the tags, by
adding attributes or changing the content within the tags and making them dynamic to user
interaction.

In CSS, there are different ways to actually implement the styling language into the
HTML. I have already showed you one way, which is to have it in the head tag with a
style tag. Well, there are three main different types of ways to implement CSS, one way is

inline, other way is internal, which is the way we did it and the other way is to do it
externally. The way we did it directly in the head, internally. To make it external, instead
of having the CSS code within the tags, we have the style tag reference a file that contains
all the CSS code.

Lets simply look at examples of how each way works. Remember, if you reference a
certain file, like a CSS one in this instance, if you dont list the direct directory path (e.g.
C:\Program Files (x86)\Crazybump) and just the name, then it will resort to looking at the
root directory your HTML file which is referencing is in.

External CSS

Filename: Learn.html

<html>

<head>
<title> This the webpage title </title>

<link rel=stylesheet type=text/css href=pageStyle.css>
<! This is the conventional line used in the head tags to reference an external
CSS file. The href attribute is used to reference the specific file and is the only
one you will change from this line for your CSS file. >

</head>

<body>
<h1> This is Header text </h1>
<p id = content> This is the content of the webpage. </p>
</body>

</html>

Filename: pageStyle.css

#content {
color: red;
font-size: 14px;
}

Now, since weve already seen how internal CSS and external CSS referencing works, we
can look at the cheapest way to do CSS: Inline. This way is not recommended just because
it isnt neat or organized to look at. Although it is useful when testing a few things with a
specific tag. In order to do inline, for any tag you want to style, you must add the attribute
style with an equal sign and then quotation marks for all the properties. Then for each
property, you must have the value separated by a colon and when you are done writing
down all your properties, you must end it off with a semi colon. Here is an example:

<p style = color: red; font-size: 14px id = content> This is the content of the webpage.
<p>

This above is an example of inline coding. Here is the full source code:

<html>

<head>
<title> This the webpage title </title>
</head>

<body>
<h1> This is Header text </h1>
<p style = color: red; font-size: 14px id = content> This is the
content of the webpage. </p>
</body>

</html>

Chapter 11
PHP Language Structure

So as we learn MySQL, we start to learn that it is a really useful language in regards to
database, except without a logical backend to control the way it can perform, it can seem
pretty useless, if youre going for an automated viewpoint and not a manual database
manager. In that case, learning PHPs basic language structure is helpful and is why well
be going over it in this section.

Variables

What is a Variable?

A variable is essentially a storage unit that holds a certain type of data. It is named by the
programmer, and is used to identify the data it stores. A variable can usually be accessed
or changed at any time. You can write information to it, take information from it, and even
copy the information to store in another variable.

Variable Types

In PHP, a variable has a specific type, which would determine what size it is, and the
layout of its memory. The PHP language defines 3 types of variables:

Instance Variables

Instance variables are declared within a class but outside of any method, constructor or
block. Instance variables are created with the keyword new and are destroyed when the
object is destroyed. An instance variable is visible to all methods, constructors and blocks,
within the class that it is declared in. All instance variables have a default value, unlike
local variables which do not have default values. All these terms like classes,
methods, constructors will be explained at a later time in the guide.
Class/Static Variables

Static Variables are declared outside of any method, constructor, or block, and are declared
with the keyword static. If a variable is static, only one instance of that variable will
exist, regardless of how many instances of the object are called. Static variables are rarely
used except for constant values, which are variables that are never changed.

Local Variables

Local variables are only declared within methods, blocks or constructors. They are only
created when the method, block or constructor is created, and then destroyed as soon as
the method ends. You can only access local variables within the method, block, or
constructor it is called, and are not visible outside of where it is called. Local variables do
not have a default value.

Data Types

As said above, variables are used to store data. PHP has multiple built in variable data
types that are used to store predefined types of data. These data type are called primitive
data types. These data types are the most basic data types that are in the programming
language. You can also create your own data types, which we will go over later. PHP has 8
primitive data types.

byte: The byte data type is a 8-bit signed twos complement integer. It has a default value
of zero when it is declared, a maximum value of 127 and a minimum value of -128. A byte
is useful to use when you want to save memory space, especially in large arrays.

Example:

$b = 1; // has a value of one

short: The short data type is a 16-bit signed twos complement integer. Its maximum
range is 32,767 and its minimum value is -32,768. A short is used to save memory, or to
clarify your code.

Example:

$s = 100; // has a value of one

int: The int data type is a 32-bit signed twos complement integer. Its maximum value is

2,147,483,647 (231 -1), and its minimum value is - 2,147,483,648 (-231). Int is the most
common used data type for integral numbers, unless memory is a concern.
Example:

$i = 10000000000; // has a value of one

long: The long data type is a 64-bit signed twos complement integer. Its maximum value
is
9,223,372,036,854,775,807
(2^63
-1),
and
its
minimum
value
is
-9,223,372,036,854,775,808 (-2^63). This data type is used when a larger number is

required to work with than would be possible with an int.



Example:

$n = 1; // has a value of one

float: The floating point data type is a double-precision 64-bit IEEE 754 floating point.
The min and max range is too large to discuss here. A float is never to be used when
precision is necessary, such as currency.

Example:

$f = 1200.5; //value of one thousand two hundred, and a half

double: The double point data type is a double-precision 64-bit IEEE 754 floating point. It
is often the data type of choice for decimal numbers. The min and max range is too large
to discuss here. A float is never to be used when precision is necessary, such as currency.
Example:

$d = 1200.5; // value of one thousand two hundred, and a half

bool: A bool data type represents one bit of data. It can contain two values: true or false. It
is used for simple flags to track true or false conditions.

Example:

$b = true; // has a value of true

char: The char data type is a single 16-bit Unicode character. Its minimum value is
/u0000 (or 0) and its maximum value is /uffff (or 65,535 inclusive)

Example:

$c = w; // returns the letter w


Another commonly used data type is called String. String is not a primitive data type, but
is a very commonly used data type which stores strings of text.

Example:

$cat = meow; // sets value of cat to meow

This example gets a string named cat, and sets it to the string of characters that spell out
meow.

Declaring a Variable

The declaration of a variable has two parts to it: The variable name and the stored value.
Note that there is a specific convention and set of rules to be used when naming variables.
A variable name can be any length of Unicode letters and numbers, but it must start with a
letter, the dollar sign $ or an underscore _, or else it would return a syntax error. It is
also common naming convention to start the name with a lowercase letter, followed with
each following word starting with a capital letter. For example, if the variable name was
theName, the first word the starts with a lower case, and each following word, in this
case Name, starts with a capital letter.

Example:

$theName = 123; // value of 123

In the example above, the data type is int, the name of the variable is theName, and the
value stored inside that is 123. You can also declare a variable without storing a value in it.
Example:
$name; // no value

You can do this if you choose to later declare it.

Using a variable

After a variable is declared, you can then read its value, or change it. After the variable
was initially declared, you can reference it only by its name; you only need to declare its
data type when you are declaring the variable.

Example:

$name = 2; // sets the int name to a value of 2

Variables can also be added together:

Example:
$a; // no value
$b = 1; // value of one
$c = 2; // value of two
$a = $b.$c; // sets a to the value of b.c

In the example above, we set the value of a, to equal the value of b and c added together.
The addition sign is known as an operator, which we will go over in the following section.
It is also possible to combine values of variables that are different data types to a certain
extent.

Example:
$test = 0; // $test is string (ASCII 48)

$test += 2; // $test is now an integer (2)


$test = $test.1.3; // $test is now a float (3.3)
$test = 5.10 Little Piggies; // $test is integer (15)
$test = 5.10 Small Pigs; // $test is integer (15)

Assignment

Using what we learned about variables, we can now create a simple calculator to add
numbers together for us. The first thing we will want to do is declare 3 variables: one to
store the value, one to represent the first number we want to add, and one to represent the

second number we want to add. We will declare these variables as double so that we can
add decimal numbers:

$a = 0; // stores value of addition
$b = 3.55; // first number to add
$c = 52.6; // second number to add

Next, we will simply set the value of a, to equal the value of b and c combined, and then
print out the value of a.

$a = $b.$c;
echo($a);

If you run the program now, it should print out 56.15. You now have just created a very
simple calculator. I highly encourage you to play around with this, and test things for
yourself. Change the data type of the variables, add more numbers together, and
experiment to understand how things work.

Operators

Just like in Math class, you learned about addition, subtraction, multiplication, division
and more. These are all arithmetic operators that are used within programming to intake
numbers, process them, and calculate them accordingly. Lets go over these operators in
programming, as they are one of the most important things to understand and also one of
the easiest to grasp.

Ive divided up programming into 4 main groups: expressions, statements, keywords and
blocks. Ill begin with expressions. Expressions are mathematical steps that computers do
to create a single value. Essentially, they work exactly like in math class, although you
need to know the characters for certain things. In PHP, there are 5 operations. Addition(+),
subtraction(-), multiplication(* that is an asterisk by the way), division( / that is a slash),
and modulus(% that is a percent sign). Most of these should be familiar, although modulus
is not too well known. Modulus means to get the remainder of a division. Here are some
examples:

6 % 3 = 0 7 % 3 = 1
8 % 3 = 2 9 % 3 = 0

This can be useful to find out if a number is even. Simply modulus by 2 and if it is 0, the
number is even, otherwise it is odd. This can also be useful when trying to find the number
of minutes, like on a clock. Simply modulus the time in minutes by 60 (60 minutes in an
hour) and the result will be the minutes counter of a clock. Notice that when using
modulo, you can only get numbers from 0 to any number lower than your operator (which
can also be a decimal).

Other mathematical operators like exponents, roots, rounding, etc, are not default
operations and are actually functions which we will discuss later. Be aware, that
expressions follow BEDMAS (or PEMDAS, whichever you were taught). Either way,
here are some expressions and their values.

7 * (3 % 2) = 7
(8 - 1.3) * 6 - 8 / (0 - 4) = 62

Keywords are the next division of programming. There are many, which we will get
around to as we learn different parts of programming. Some common ones are $, for,
while, return, function, and break. The computer looks for these special words to
perform specific actions within your code. That is a very generic description, but they

have a very broad range. Be wary of writing them down when you do not mean to use it. If
used improperly, it can not only cause mistakes in code execution, but can simply make
your code not run at all due to an error in syntax.

Statements are the next division of programming. Statements always end in a semicolon
(except in very specific circumstances). Notice that console.log ends in a semicolon, and
therefore is a statement. This is indicative of the fact that console.log is a function, but
well get to that.

Lets begin with a very common and important statement. This has to do with variables.
Variables are values that are stored inside memory for reuse later in your code, often
several times. Variables let us give names to stored values. Imagine variables like a box,
specifically a moving box. When you get the box out, you write the name of it on the side
of the box so you can know what should be inside the box. This is called variable
declaration. You are pulling out memory (the box), giving it a variable name (writing on
the side of the box), and also telling it where the box should be, or rather what kind of
scope the variable has, but well come back to that.

The Arithmetic Operators

Addition

5+5 = 10
$x = 5;
$y = 5;
$sum = 0;
$sum = $x.$y;

In the example above, a variable of sum is taking the addition of two variables (x and y)
and adding them together to produce the value of 10.

Subtraction

10-5 = 5
$x = 10;
$y = 5;

$total = 0;
$total= $x - $y;

In the example above, a variable of total is taking the subtraction of two variables (x and
y) and subtracting them together to produce the value of 5.

Multiplication

5*4 = 20
$x = 5;
$y = 4;
$total = 0;
$total= $x * $y;

In the example above, a variable of total is taking the multiplication of two variables (x
and y) and multiplying them together to produce the value of 20.

Division

20/5 = 4
$x = 20;
$y = 5;
$total = 0;
$total= $x / $y;

In the example above, a variable of total is taking the division of two variables (x and y)
and dividing them together to produce the value of 20.

Modules

7 % 2 = 1
$x = 7;
$y = 2;

$total = 0;
$total= $x % $y;

In the example above, a variable of total is taking the remainder of two variables (x and y)
and by finding how many times 2 multiplies in to 7 evenly before it cant, and the
remainder is the output. For example:

How many times does 2 get in to 7?

3 times.
2 * 3 = 6
7 - 6 = 1

Therefore, 7 modules 2 is equal to 1 because that is the remainder.

Post-Incrementation

5.1 = 6
$x = 5;
x++;
$y = 0;
$y = $x++;

In the example above, a variable of x is being incremented by the value of 1. Therefore,
the value of x must now be 6 because x.1 = 6 as $x = 5. If you were to print out the value
of x, the output would be 6. You can do x++ again and the value would then become 7.
The value of y on the other hand is still 6 because it is post incrementing meaning that the
value of x has changed by an increment of 1 (to 7), but the value of y has yet to be
changed until it is called again (y = x++) which in the case would be y = 7.

Pre-Incrementation

5.1 = 6
$x = 5;

++$x;
$y = 0;
$y = ++$x;

In the example above, a variable of x is being incremented just like it was when it was
post-incrementing as a variable by itself. The value of y on the other hand changes directly
to 6 because it is pre-incrementing meaning that the value of x has changed by an
increment of 1, and the value of y changes, meaning that y = 7.

Post-Decrementing

5 - 1 = 4
$x = 5;
x;
$y = 0;
$y = $x;

In the example above, a variable of x is being decremented by the value of 1. Therefore,
the value of x must now be 4 because x - 1 = 4 as before $x = 5. If you were to print out
the value of x, the output would be 4. You can do x again and the value would then
become 3. The value of y on the other hand is still 4 because it is post decrementing
meaning that the value of x has changed by a decrement of 1, but the value of y has yet to
be changed until it is called again (y = x) which in the case would be y = 3.

Pre-Decrementing

5 - 1 = 4
$x = 5;
x;
$y = 0;
$y = $x;

In the example above, a variable of x is being decremented by the value of 1. Therefore,
the value of x must now be 4 because x - 1 = 4 as before $x = 5. If you were to print out
the value of x, the output would be 4. You can do x again and the value would then
become 3. The value of y on the other hand is 3 because it is pre decrementing meaning

that the value of x has changed by a decrement of 1, and the value of y has changed.

The Assignment Operators

The assignment operators are operators that are used when assigning variables values, the
most commonly used operator being (=). Here are a list of examples:

Equal Sign: =

$x = 5;

In this example, if you were to print out x, the value would be 5 because you assigned the
variable x equal to 5.

Add-Equal Sign: +=

$x = 5;
$x += 5;

In this example, if you were to print out x, the value would be 10 because you are adding
the value of 5 on to the value of x. This statement is the same thing as saying $x = x.5 x
+= 5.

Subtract-Equal Sign: -=

$x = 5;
$x -= 5;

In this example, if you were to print out x, the value would be 0 because you are
subtracting the value of 5 from the value of x. This statement is the same thing as saying
$x = x - 5 x -= 5.

Multiplication-Equal Sign: -=

$x = 5;
$x *= 5;

In this example, if you were to print out x, the value would be 25 because you are
multiplying the value of 5 on to the value of x. This statement is the same thing as saying
$x = x * 5 x *= 5.

Division-Equal Sign: -=

$x = 5;
$x /= 5;

In this example, if you were to print out x, the value would be 1 because you are dividing
the value of 5 on to the value of x. This statement is the same thing as saying $x = x / 5
x /= 5.

Modules-Equal Sign: -=

$x = 5;
$x %= 5;

In this example, if you were to print out x, the value would be 0 because you are finding
the remainder in (5/5). This statement is the same thing as saying $x = x % 5 x %= 5.

Another important thing to understand when working with numbers in PHP is that it
matters how you declare your number. If you declare it with a decimal value, when you
divide it, it will output as a decimal number if it doesnt divide by two evenly, while if you
declare it with an integer value (whole number) it will divide by two and round down if it
divides unevenly.

For example:

$numberWithDecimal = 5.5;
$wholeNumber = 5;

Now that we have went over all the operators that we can use to work with variables, lets
go over some special cases with variables. First of all, if you would like to join two strings
together, the way to do that is to concatenate them together (join them together) and to do
that is to simply use the . operator.

For example:

$x = Hello;
$y = World;
$line = $x. .$y;
echo $line;

The value of line in the case would be Hello World without the quotation marks.

The next special case is when trying to add a string and a number together. So for
example:

$line = 15.test;

The variable of line will now hold the value of 15test without quotation marks, as it
wont understand why youre trying to add a number to a string, so it will automatically
treat it as the following in the backend:

$line = 15. test;

Remember that in PHP, you can update variables dynamically, so for example:

$x; // undefined
$x = 10; // x is a number
$x = This is text; // x is now a string

Throughout this guide, youve been seeing me use double quotation marks for strings - it
actually doesnt matter - youre able to use single quotes to declare string variables as
well. The catch with single quotes and double quotes usage is that if youre using double
quotation marks outside your string variable, and want to use it inside, PHP will get

confused, so in order to make it unconfused, you are to place an escape character: \ right
before the double quotation mark that is confusing the PHP string variable which will
simply bypass that double quotation mark and ignore the \ when outputting the string.
Another way is to simply surround your string variable with single quotes and be able to
use double quotation marks within your string variable without confusing PHP - or vice
versa.

Examples:

$text = Its great to learn!;
// Single quote inside double quotes

$text = Their name is Microsoft;
// Single quotes inside double quotes

$text = Their name is Microsoft;
// Double quotes inside single quotes

Boolean Logic

A Boolean is a variable that holds the value of either true or false - and these variables can
be manipulated to logically breakdown conditions to come up with a decision.

If Statements

An if statement, simply put, checks to see IF something is true, or false. To create an if
statement, you simply write the word if followed by two rounded brackets. Within an if
statement is the block of code that will execute if the condition of the if statement is met.
if statements can also include else if statements, and else statements. An else if statement
will run if the if statement returns false. However, it also contains its own parameter that
must return true. An else statement also is called if the if statement returns false, the
difference between an else statement, and an else if statement, is that no parameters need
to be true for an else statement to run.

Example:

$a = 10;
$b = 20;
if ($a == $b) {
echo(a is equal to b );
}
else if ($a > $b) {
echo(a is greater than b );
}
else {
echo(a is not equal to b or greater than b );
}

The operands used in this example (== and >) are explained below. In the following
code, we first check to see if a is equal to b. If that is true, we simply print a is equal
to b and ignore the rest of the code. If a does not equal b, then it goes down and calls
the else if. The else is due to the first if returning false. The if part of else if is checking its
own parameters, which happen to be whether a is greater than b. If a is greater than
b, then we would have printed a is greater than b. However, since a is less than b,

we go further down and simply call else. The else runs if all the above parameters return
false. It does not require its own parameter to be true. Note That each if statement can
have an infinite amount of else if statements which follow it, but only one else statement.
Also Note that you cannot have code between an if statement and an else statement,
because the code would not be able to find the else. As well, an else statement requires
there to be an if statement before it, since for an else statement to be called, an if statement
HAS to equal false immediately before it. It is also important to know that it is possible to
have an if statement INSIDE of another if statement. This is called a NESTED if
statement.

Example:

$a = 20;
$b = 30;
if ($a == 20) {
if ($a < $b) {
echo(a is less than b and it is equal to 20);
}
}

In this example, we first check to see if the value of a is equal to the value of b. If it is,
we then check to see if the value of a is less than the value of b. If this statement also
returns true, we can print to the console a is less than b and it is equal to 20. This can
work with as many if statements as you would like. This can be useful if completely
necessary to check the parameters separately, or if you want to add additional logic
between each check.

You will understand fully the way an if statement works by the end of this section.

The Relational Operators

PHP supports 6 different types of relational operators, which can be used to compare the
value of variables. They are the following:

== This operator checks to see if the value of two integers are equal to each
other. If they are the equal, the operator returns true. If they are not, it returns false.
Example:


$a = 10;
$b = 10;
if ($a == $b) {
echo(they are the same);
}

This code checks to see IF the value of a is equal to the value of b. Since the value of
a is equal to the value of b, the value within the brackets will be true. This ends up
causing the above code to print out the statement they are the same.

!= This operator checks to see if the value of two things DO NOT equal the
same thing. If two things DO NOT equal the same thing, then it will return true. If they
DO equal the same thing, it will return false.

Example:
$a = 10;
$b = 20;
if ($a != $b) {
echo(they are not the same);
}

This code will check if a does not equal b. Since a does not equal to b, the
program will print they are not the same in the console.

> This operator Checks to see if something is Greater than something
else. If the value of the variable in front of it is greater than the value of the variable after
it, it will return true. If the value of the variable in front of it is less than the value of the
variable after it, it will return false.
Example:
$a = 10;
$b = 20;
if ($a > $b) {
echo(a is larger than b);
}

else {
echo(a is not larger than b);
}

This example checks to see if a is larger than b. Since a is not larger than b, this if
statement will return false. Instead, it will print a is not larger than b, because the code
passes the failed if statement and calls the else statement.

< This operator checks to see if something is less than something
else. If the value of the variable before the operator is less than the value of the operator
after the variable, then the code will return true; else, it will return false.

Example:

$a = 10;
$b = 20;
if ($a < $b) {
echo(a is larger than b);
}
else {
echo(a is not larger than b);
}

This example is just like the one before it, however, the operator changed from greater
than, to less than. Therefore the if statement will return true this time. Since the value of
a is less than the value of b, and the program will print to the console a is larger than
b.

>= This operator checks to see if something is greater than Or Equal to
something else. If the value of the variable before it is greater than Or Equal to the
variable after it, then it will return true. If the variable after it is greater but not equal to the
variable before it, it will return false.

Example:

$a = 20;
$b = 20;
if ($a >= $b) {
echo(a is larger or equal to b);
}
else {
echo(a is not larger or equal to b);
}

In this example, a and b both have a value of 20. Although a is not greater than b,
it is EQUAL to b, therefore the statement returns true, and the code ends up printing a
is larger or equal to b.

<= This operator checks to see if something is less than Or Equal to
something else. If the value of the variable before it is less than Or Equal to the variable
after it, then it will return true. If the variable after it is less but not equal to the variable
before it, it will return false.

Example:
$a = 20;
$b = 20;
if ($a <= $b) {
echo(a is larger than b);
}
else
echo(a is not larger than b);
}

This example is identical to the one before it except the operator was changed from >= to
<=. Although the operator has changed, the result is the same. Since a is equal to b,
this code will return true, printing a is larger than b to the console.

The Logical Operators

PHP supports 3 Logical Operators that can be used in your logic, which will often be used
in conjunction with Relational Operators.

&& This is known as the logical AND operator. If the operands
before and after this operator both return true, then the condition returns true. If both of
the operands are false, or one operand is false, the condition will return false. BOTH
operands MUST be true for the condition to return true.

Example:
$a = 20;
$b = 20;
if ($a == 20 && $a == $b) {
echo(a is equal to 20 and b );
}
else {
echo(a is not equal to 20 or a is not equal to b);
}
In this Example, we check to see if a is equal to 20, AND if a is equal to b. These
two conditions will be referred to as operands. Since a is equal to 20, and equal to b,
the statement returns true, and we print to the console a is larger than b.

Example 2:

$a = 20;
$b = 30;
if ($a == 20 && $a == b) {
echo(a is equal to 20 and b);
}
else {
echo(a is not equal to 20 or a is not equal to b);
}

In this next example, we check the exact same thing as the first example. The difference
this time, however, is that we changed the value of b from 20 to 30. This means that
when we run this code, the if statement will return false because although a is equal to

20, it is not equal to b. Therefore we print out a is not equal to 20 or a is not equal to
b. Take note that the order does not matter. If the first operand was false instead of the
second, we would have the same result.

|| This Operator is known as the logical OR operator. If the first


operand OR the second operand is true, the statement will return true. This means that if
the first operand returns false and the second is true, the statement will still return true,
and vice versa. The statement also will return true if both the operands are true.
Essentially, when using an OR operator, at least one operand must return true.

Example:
$a = 20;
$b = 30;
if ($a == 20 || $a == $b) {
echo(a is equal to 20 or b);
}
else {
echo(a is not larger than b);
}

In this example, we check to see if a is equal to 20, OR if a is equal to b. In this
case, a is equal to 20 and is not equal to b. Since only one of these operands need to
be true, the statement as a whole will return as true. Therefore the program will print a is
equal to 20 or b in the console.

Example 2:

$a = 20;
$b = 20;
if ($a == 20 || $a == $b) {
echo(a is equal to 20 and b );
}
else {
echo(a is not equal to 20 or b );
}


In this example, I have changed the value of b from the previous example from 30 to 20.
This means that a is equal to 20 and a is equal to b. Both operands return true,
therefore the statement returns true. This is due to the fact that an OR operator requires 1
or more of the operators to be true. This program will output a is equal to 20 and b in to
the console.

! This operator is known as the logical NOT operator. It is used to reverse the
logical state of its operand. This operand can be used with any other operand to reverse its
output. If an operand was returning true, after applying the logical NOT operator, the
operand will return false.

Example:

$a = 21;
$b = 20;
if ( !( $a == 20) && $a > b) {
echo(a is not equal to 20, and a is greater than b);
}
else {
echo(a is equal to 20, and a is not greater than b );
}

In this example, we check to see if the value of a does not equal to 20, and we check if
a is greater than b. Since a is both not equal to 20, and greater than b, we can
print out to the console a is not equal to 20, and a is greater than b.

Example 2:

$a = 21;
$b = 20;
if ( !( $a == 20 && $a > $b) ) {
echo(a is not equal to 20, and a is greater than b );
}
else {

echo(a is equal to 20, and a is not greater than b );


}

In this example, I changed the position of the bracket from the NOT operator to extend to
both operands. Now for the statement to be true, a has to NOT equal to 20, AND a
must NOT be greater than b. In this situation the statement will return false, because a
is greater than b. Due to the operand it needs to be less than b for the statement to
return true. Therefore this program will return a is equal to 20, and a is not greater than
b to the console.

Combining Operators

In PHP, it is possible to use as many operators as you require per statement.

Example:

$a = 21;
$b = 20;
if ( ($a == 20 && $a > $b) || ($a != 20 && $a < $b)) {
echo(correct);
}
else {
echo(wrong);
}

With this example, we can see how we can achieve much more complicated statements.
Here, we apply an OR operator with two operands, however, each operand also
incorporates an AND operator. Therefore, for this statement to return true, a must be
equal to 20 and be greater than b OR a must not be equal to 20 AND a must be less
than b. Note that we use brackets to make the code more easy to understand, and to
prevent the code from misreading our logic.

Example 2:

$a = 21;

$b = 20;
if ($a == 20 && ($a > $b || $a != 20) && $a < $b) {
echo(correct);
}
else {
echo(wrong);
}

In the above example, we have significantly changed the logic of the program, by only
switching the position of a bracket. Notice how now the brackets surround the two inner
operands, instead of two pairs of brackets surrounding each pair of outer operands. For
this statement to return true now, 3 different conditions must return true. Variable a must
be equal to 20, AND, either a must be greater than b OR it must not be equal to 20;
AND a must be less than b. With this new logic, the first operand must be true, on top
of EITHER the second or third having to return true. Also on top of that, a must be less
than b. This statement will return false. It will fail the first condition, because a does
not equal 20. It will pass the second condition, because it is greater than b, and it will
fail the last condition because a is not less than b. Since this would have required
three correct conditions, and only had one, the statement returns false and prints wrong.

Loops and Arrays



This section of the guide is important because it covers one of the most important concepts
in programming. Loops are what it says they are - they are simply functions that allow you
to Loop a certain block of code for a certain amount of iterations depending on what you
ask of it. Although this may not seem useful right now, when you start to apply your
knowledge to real programming applications, you will find use of them. Before we cover
arrays, lets go over how Loops work.

Loops

Loops in PHP are relatively the same as many other programming languages. The syntax
for it is also pretty straight forward. In every Loop, there is a condition that is set forth for
the Loop to check whether or not it is true and until the case is the opposite, is when the
Loop itself would break out itself. For example, if you were to create a Loop and say that I
want it to run a certain block of code 10 times before stopping, there are a few ways to do
this because there are a different type of Loop. A general idea of a Loop is the following:

Loop (condition) {
// block of code
}

In order to create a Loop in PHP - we must understand the different type of Loops and
when they are useful. Lets go over these types of Loops and then Ill explain how each of
them work as we go through and by the end, you should have gained a good understanding
of how Loops work.

For Loops

for ($x = 0; $x < 10; $x++) {
echo(Hi .$x);
}
There are quite a few things that are going on in the above example so lets go over it line
by line. The first line says:

for ($x = 0; $x < 10; $x++)


In the above statement, it is a conventional standard for the for Loop. We must first
declare the variable, so lets start by declaring the x variable and make it an int starting at
0. Next, lets add a semicolon to separate that specific component of the for Loop by
adding a condition. That is why I did $x < 10 which simply says that for however long
that x is less than 10, run the block of code that is under my curly braces ({ and }).
This statement is now separated by another semi-colon to let the final element of the for
Loop to be entered. This is the part where you tell the specific variable that you declared,
to do a certain arithmetic operation. In this case, we are telling x to increment each time
the Loop passes.

Lets go over this in a pseudocode approach (english-readable):

for ( declare variable; create condition for variable; affect variable) {
// Run this block of code
}

Once it runs the block of code, it will go back to the first statement and check whether or
not the condition is still met. It will skip declaring the variable since it will notice that it
has already been declared. It will then skip to affecting the variable before checking to see
if the condition is met.

Heres a blueprint to follow for the for Loop or any Loop for that matter:

Declares Variable Checks Condition Runs block of code Affects Variable
Checks Condition Runs block of code Affects Variable Checks Condition
Runs block of code Repeat starting from Affect Variable

Now if we look back at the code we created with a little modification on alert:

for ($x = 0; $x < 10; $x++) {
echo(Current Number: .$x);
}

We can see that this Loop is simply incrementing x from 0 to 9, so technically 10
iterations since 0 is inclusive. Therefore, the Loop alerts the following as the output:

Current Number: 0
Current Number: 1
Current Number: 2
Current Number: 3
Current Number: 4
Current Number: 5
Current Number: 6
Current Number: 7
Current Number: 8
Current Number: 9

Remember how I said that a for Loops last statement is the arithmetic operation for the
variable that has been declared - well the variable can be affected in any way, you can
increment by 2s if you wanted to as well.

Now that we know how a for Loop works, it will be easier to understand how a while
Loop and a do-while Loop work.

While Loop

The only difference with a while Loop compared to a for Loop is that it only carries the
condition of the Loop, and not the variable. Therefore, you must actually declare the
variable outside of the scope of the Loop before affecting it in the Loop to carry out a
certain condition.

For example:

$x = 0;
while ($x < 10) {
echo(Current number: .$x);
$x++;
}

In the example above, as seen, a while Loop simply checks for a condition and when it has

been met, runs the block of code, and then affects the variable x so it goes back to
checking the condition when the block of code is done executing, and simply continues to
do it until x is not less than 10. The output for this is the same as the for Loop output:

Current Number: 0
Current Number: 1
Current Number: 2
Current Number: 3
Current Number: 4
Current Number: 5
Current Number: 6
Current Number: 7
Current Number: 8
Current Number: 9

There are things that can go wrong with this while Loop like the accidental creation of an
infinite Loop. For example:

$x = 0;
while ($x < 10) {
echo(Current number: .$x);
}

In the above example, it is doing exactly everything the previous Loop was doing except
the output (which is to alert a certain piece of text) would be infinitely displaying because
the variable x is never being affected.

The final type of Loop we will be covering is the do-while Loop. This Loop does
everything the while Loop does, except it does something at least once regardless of the
condition before resorting to depending on the condition.

For example:

$x = 0;

do {
echo(Current number: .$x);
x++;
} while ($x < 10)

The above example simply runs the iteration of the block of code at least once regardless
of the condition that is given at the end before actually testing the condition. This can be
useful if you ever wanted a Loop to do something, except at least do it once before
checking the condition.

Continue keyword

The continue keyword is used when you want to skip an iteration of a Loop. For example:

$x = 0;
while ($x < 10) {
if ($x == 5) {
continue;
}
echo($x);
}

In the above example, we are checking if x is equal to 5, if it is then what we do is skip the
iteration of the Loop, meaning the output of this Loop then becomes:

Current Number: 0
Current Number: 1
Current Number: 2
Current Number: 3
Current Number: 4
Current Number: 6
Current Number: 7
Current Number: 8

Current Number: 9

As seen in the output above, the Loop skips 5 because it was told to skip that iteration of
the Loop before it even had the chance to alert the number out.

Break keyword

The continue keyword is used when you want to break out of the Loop. For example:

$x = 0;
while ($x < 10) {
if ($x == 5) {
break;
}
echo($x);
}

In the above example, we are checking if x is equal to 5, if it is then what we do is break
out of the Loop, meaning the output of this Loop then becomes:

Current Number: 0
Current Number: 1
Current Number: 2
Current Number: 3
Current Number: 4

As seen in the output above, the Loop breaks out once it reaches the fifth iteration
meaning, to essentially stop the Loop from continuing on any further.

If we combine the conceptual understanding of Loops and arrays, we can come up with
complex code - that is why we will be learning arrays, before we look at a real-world
application where this may be useful to use so you can gain a better understanding of why
Loops and arrays are helpful. You will be using Loops and arrays a lot when programming
even if it doesnt seem like it right now.


Arrays

Arrays in programming are helpful because it allows you to create lists of
strings/numbers/objects or whatever data type you can think of. Again, this might not be
apparent at first but will be when you start to program and realize that you may need to
use arrays in certain instances. So an array is basically a single variable that holds multiple
values that can be accessed individually. Lets go over the syntax of how an array
declaration would work.

In order to declare a variable, you must do the following:

$names = array( John, Bob, Tom);

In the example above, what we are doing is declaring a variable with the name of names,
and then we are assigning it a list of values, which are of string type. So in order to assign
values to the array, we added array() which simply set the boundaries for the array. Then,
we noted that the array type is string by surrounding each element by quotation marks and
then adding a comma in between each element to indicate that it is a different element in
the array.

In order to access specific element values from the array, we use the following syntax:

echo($names[0]);

In the above example, what we are doing is alerting the value of the arrays index of 0. In
arrays, we refer to the values of the array through the index value - and the index value
starts at 0. Therefore, John is index of 0, Bob is index of 1 and Tom is the index of
2. The length of the array itself is 3. In order to get the length of the array we use the
following property:

echo(count($names));

Since arrays in general are objects (you will learn what this means later) they have
variables and functions, and length is a property of arrays, and therefore can be accessed
by the names variable since it is a variable of array type. The output of this piece of code
would be 3 since it would count the first element of the array as 1 and then 2 and so forth.


Now lets say that we want to declare an array but not assign it any values until later in the
code. Then you would do the following:

$names = []
$names[0] = John;
$names[1] = Bob;
$names[2] = Tom;

In the above example, we are declaring an empty array that we preparing to add elements
to, and we do so by referring to an index that doesnt yet exist and give it a certain value.
Now we can refer to the names arrays index and retrieve the appropriate value that was
assigned to it.

echo($names[0);

The above example now returns John as it was assigned the string John. One thing to
note is that youre able to overwrite index values by simply using the assignment operator
for the certain index that you would like to overwrite and then assign it something else.

Functions and Classes



A function is a block of code that can be run at any point in your program with a single
line of code, and it can be used as many times as youd like. This allows you to write a
block of code once, and then be able to use it as many times as youd like throughout your
code. To create a function, simply write function, a variable name, and then brackets,
followed by squiggly brackets, which hold your code.

function printSomething()
{
echo(Something I guess? I dont know);
}

This is a very simple function. Between the normal brackets, you can place variable
names. These are called parameters. These parameters will allow you to give values to the
code, which could give you a different output.

function printSomething($times)
{
for($i = 0; $i < $times; $i++)
{
echo(Mum!);
}
}

This function uses a variable called times, runs a Loop for that number of times, and in
each Loop prints Mum!. So if you run this code with a value of 7, Mum! will print out
7 times. You can have as many parameters as you want (although the fewer the better).
Just separate each variable name with a comma.

function printSomething($times, $whatToPrint)
{
for($i = 0; $i < times; $i++)
{
echo($whatToPrint);

}
}

This function will print out whatever whatToPrint is set to for however many times is set.
So how do we use this code? To make this code run, simply type the function name,
followed by brackets, which contain values, separated by commas, which should relate to
what the function is using it for. For example, for our function, our first parameter is the
times variable, so we should only be putting a number as the value for our first parameter,
specifically a whole number (although in this case, whether the number is whole or not is
not important). As well, for the second parameter, we should put what we want to print.
This is called calling a function.

echo(7.I like to move it, move it!);

We can call our function as many times as we want, whenever we want. Something
interesting about functions is that you can use functions as values when setting variables,
and then call them from these variables. The difference between calling a function, and
using it as a value, is that when calling a function, you use brackets with parameters in
them, while when using a function as a value, you do not place brackets.

An important feature of functions is the fact that you can return values. This means that
the function will act as the returned value when called. To return a value, simply use the
return keyword, followed by a value. Here is an example. To use the returned value,
simply imagine the function call as being the returned value.

function calculateHalfCircumference($radius)
{
return 3.14*$radius;
}

$circumference = 2*calculateHalfCircumference(7);
echo($circumference);

In this example, we create a function, and return half of the circumference (why you
would want to do this, I do not know, but for the sake of an example, that is what we will
do). Outside the function, we create a variable, and set it to twice the returned value of our
function, which we know will be half the circumference of our circle. If we are taking half
of the circumference and multiplying it by 2, that means we are getting the total

circumference, which we print out. Returning also has a secondary function. It stops
execution of a function. This means that say you have a Loop in your function that runs
for a long time, but you want it to stop after an if-statement runs. Just use the return
keyword and it will stop the rest of the Loop from running. The return keyword does not
need a value to be returned either. You can use the return keyword on its own to end
execution of your function where it may be.

function kindaUseless($number)
{
$i = 0;
while(true)
{
$i++;
if($number == $i)
{
echo($i);
echo(That wasnt the best way to do that);
return;
}
}
}

This is not a very useful example, but it shows the syntax of it. This Loop will run as long
as trueis true. This Loop will run forever. We also have a variable called i that we
simply make count up. In each iteration, we check if the number we are looking for is
equal to our i variable. If it is, we print out i and also just print something about this
function in general. Finally, we return the function. Since the function stops execution
after its returned, the infinite Loop is escaped, and our program can continue. This is
extremely useful, especially in situations where you want to limit the number of iterations.
For example, if you are searching for something in an array, and you find it, you may want
to just return right there, to avoid wasting more iterations on looking for a duplicate or
something.

Functions are incredibly useful, especially when your code becomes exceedingly lengthy.
Rather than have similar code all throughout your code, you could use a function to only
have the code written out once, and called where it needs to run. Functions also allow us
to make code clearer just as comments do, but in the form of the function name. For
example, say you have some hard-to-read or confusing code that prints the output of your

code. You could make a function called printOutput. This makes it easier to read code,
because instead a block of code, you have a single line that just tells you what its doing:
printing the output.

Ex 1 (Basic function):

<?php
function SaySomething() {
echo Hello world!;
}

SaySomething();
?>

Ex 2 (Feeding two arguments):

<?php
function Birthday($name, $year) {
echo $name.Born in.$year. <br>;
}

Birthday(John, 1987);
?>

Ex 3 (Default Argument Value):

<?php
function SetFavoriteColor($color = white) {
echo The color is : $color <br>;
}
SetFavoriteColor(Blue);
SetFavoriteColor(); // will use the default value of white

?>

Ex 4 (Returning Values):

<?php
function Add($fNum, $sNum) {
$sum = $fNum + $sNum;
return $sum;
}

echo 5 + 10 = .(Add(5,10));
?>

Next, lets talk about classes or objects:

A class is simply a section filled with functions, more often than not, similar functions
bunched up together with a similar purpose within a section that can then be referred to
and called. Think of the class as a parent directory to a function within that class as a sub
directory. This can be used to organize your code and refer to different classes which
handle different branches of functions.

In order to create a class, we must use the class keyword followed by the class name
which is then followed by an opening brace and a closing brace.

Class ClassName {
// contents of class here
}

Not only can there be functions in a class, but there can also be variables in a class that
can be referred to. Lets start out by making two random variables and sticking it in the
class just for example purposes. Lets also call our class Marks as we will be working with
manipulating student marks when a teacher inputs them, as a real world application to
object oriented use. One thing to note is that when creating global variables in your class,
they must start with the var keyword to signify that they are indeed a class variable.
Ofcourse outside of classes, this term doesnt need to be used. For example:


class Marks {
var $studentName;
var $average;
}

In the code above, the first thing that happens is we create a global class variable named
studentName and declare it but not yet assign it. We do the same for average. The goal for
the following variables is to essentially allow the teacher to input a student name and then
input the average the student received. Then, the teacher is able to retrieve these values at
any time he wants. A real world application of this would have an interface but Im going
to show you a skeleton of the functionality.

class Marks {

var $studentName;
var $average;

function setStudentName($name) {
$studentName = $name;
}

function setStudentAverage($avg) {
$average = $avg;
}

function getStudentName() {
return $studentName;
}

function getStudentAverage() {
return $average;
}

}

So to explain each functionality above. The first thing we do is create a function with the
name of setStudentName and it asks for an argument of variable name $name and then
sets the class variable $studentName to the variable name inputted. Then our next function
simply has the same idea as the previous method except it allows the teacher to input an
average for the student. Then we set the class variable equal to the variable inputted in to
the function. Finally, in order to retrieve the variables value, we create a function of name
getStudentName which simply returns the value of the $studentName variable in the class.
We apply the same philosophy to the getStudentAverage function which simply returns the
average of the student of the variable $average in the class.

Now in order to actually reference the class and its variables / methods, we must use
special syntax in the PHP code outside of the class for the executing code. In order to
reference a class, we must create an object, which is pretty much a variable that holds the
class as the class can be seen as an object since it holds functions / properties / variables
which makes itself unique. In order to actually create this object, we must use the new
keyword which basically is used whenever declaring a class/object. Example:

<?php
class Marks {

var $studentName;
var $average;
function setStudentName($name) {
$studentName = $name;
}
function setStudentAverage($avg) {
$average = $avg;
}

function getStudentName() {
return $studentName;
}

function getStudentAverage() {

return $average;
}

}
// $objectName = new nameOfClass();
declaration

Example Skeleton of object / class




?>

Now in order to actually create this object, we will do the following:

<?php
class Marks {

var $studentName;
var $average;
function setStudentName($name) {
$studentName = $name;
}
function setStudentAverage($avg) {
$average = $avg;
}

function getStudentName() {
return $studentName;
}

function getStudentAverage() {
return $average;
}

}
$marksObject = new Marks();


?>

Now that we know how to reference the class, how do we reference what is within the
class? Well we use a dash and an arrow pointing to the right to signify the path the object
must take to get to a certain variable / function. For example:

<?php
class Marks {

var $studentName;
var $average;
function setStudentName($name) {
$studentName = $name;
}
function setStudentAverage($avg) {
$average = $avg;
}

function getStudentName() {
return $studentName;
}

function getStudentAverage() {
return $average;
}

}
$marksObject = new Marks();
// I want marksObject to reference the $studentName variable and echo it



?>

In order to actually do it, you must do the following:

<?php
class Marks {

var $studentName;
var $average;
function setStudentName($name) {
$studentName = $name;
}
function setStudentAverage($avg) {
$average = $avg;
}

function getStudentName() {
return $studentName;
}

function getStudentAverage() {
return $average;
}

}
$marksObject = new Marks();
echo ($marksObject -> studentName);


?>


In the above code, the $marksObject references the studentName variable without the
dollar sign because you dont have to use it. We then tell the class to refer to the variable
name studentName within it and it echoes out accordingly. But since studentName hasnt
been set by the user, it is not going to be able to echo out a proper value. Another thing
you might be wondering is, if were referencing the variable studentName directly instead
of using a function to retrieve the value, then why did we create a function to do just that?
Well, no reason really its just convention to and also for example purposes to show you
the idea of how classes and functions can work together.

Now in order to actually reference a function, you do the same thing you do when you are
referencing a variable except this time you add parenthesis to the end of the thing that you
are referencing in order to specify that youre pointing to a function and not a variable
name.

Example:

<?php
class Marks {

var $studentName;
var $average;
function setStudentName($name) {
$studentName = $name;
}
function setStudentAverage($avg) {
$average = $avg;
}

function getStudentName() {
return $studentName;
}

function getStudentAverage() {
return $average;

}

}
$marksObject = new Marks();
$marksObject -> setStudentName(Peter);
$marksObject -> setStudentAverage(80);
echo ($marksObject -> getStudentName());
echo ($marksObject -> getStudentAverage());


?>

In the above code, we are simply referencing the two functions to set the variables in the
class to a certain value we input in the argument. Then, we actually output the values we
set the variables to in the end.

Chapter 12
PHP Integration into MySQL

Using PHP, youre able to connect and manipulate databases this can be used for login
systems, directories, and much more. With PHP, youre able to use the MySQL language
to send commands to a database to do different functionalities. MySQL is known as the
most popular database system used with PHP. We have went over a lot of what MySQL
has to offer in this guide, but are going to do it again except with its connection to PHP.
This is also a good time to look at what you have learned so far in a condensed version,
while learning along how PHP has a connection to MySQL and can help it do more than
just accept queries created by you and run manually, but moreover, the automation of
databases.

Summary of SQL

database framework utilized on the web

database framework that keeps running on a server

ideal for both little and vast applications

very quick, dependable, and simple to utilize

uses standard SQL

compiles on various stages

free to download and utilization

When working with data in MySQL, it is stored in a table which is a collection of data
consisting of rows and columns. Each column is a separate category while each row is
information regarding that category. For example, someone might be doing a survey of
peoples favorite: color, food, car, sport. These would all be columns and the rows would
be the values of each column. Every row would have different values for the
corresponding column.

So how can you work with PHP and MySQL to create database like systems where you
might want to save information of users that log in or register on your website? Well, the
first thing we must do is understand the basics of MySQL. Lets start with MySQL
Database Queries. A query is simply a request for someone to do something. In this case,
we would be writing query statements for MySQL to do something. An example in
English would be: Retrieve the column of color in the table name tblSurvey in the row
number 14. Now that you have a basic idea of what a query is like, we can move on to the
nitty gritty the code.

In order to work with databases, you can use your Xampp installation to create a MySQL
database using PHPMyAdmin. There are many tutorials and guides on Google regarding
this so we wont be covering that, but once you have created a quick table in
PhpMyAdmin, continue reading the guide.

1. Connecting to MySQL

In order to access data from the MySQL Database, we must first connect to the server that
has MySQL installed. In order to do that, we must do the following:

<?php
$server_name = localhost;
$username = username;
$password = password;
// Establishing a connection
$con = new mysqli($server_name, $username, $password);
// Check connection
if ($con->connect_error) {
die(Connection failed: . $con->connect_error);
}
echo Connected successfully;
?>

In the above code, we are declaring three variables which are server_name, username, and
password. Each of these variables are then assigned a generic string value. Next, we create
a variable that is going to hold the return value of the function mysqli. In the arguments of
mysqli, we must input the server_name first, then the username second, and finally the
password third. Once all of these are inputted in to the functions arguments, mysqli will
return a connection object which can then be used to check whether or not the connection
was successful or if it wasnt.

Now the way we did it above was in the object oriented way. In order to do it in a simple
Without Object Oriented way, we would do the following:

<?php
$server_name = localhost;
$username = username;
$password = password;
// Establishing a connection
$con = mysqli_connect($server_name, $username, $password);
// Check connection
if (!$con) {
die(Connection failed: . mysqli_connect_error());

}
echo Connected successfully;
?>

The only difference in the above code now is the fact that the mysqli_connect function is
being used which simply returns a Boolean of either true or false. If it returns true, that
means the code has successfully connected to the database. If it is false, then that means it
has not successfully connected to the database.

To close the connection, you must use the following:

OBJECT ORIENTED Format: $con -> close();

Without Object Oriented Format: mysqli_close($con);

Now in order to actually create the database, we will need special CREATE privileges to
create or delete a MySQL database by the server. Now to begin, we will slowly start to
learn how the query language works as we approach it head on with code. Now in order to
actually execute the query, we must use a function called query or mysqli_query
depending on if youre doing without Object Oriented or the OBJECT ORIENTED
format. Then, this function will take in the query statement that you created and the
connection (if its Without Object Oriented).

OBJECT ORIENTED Format Example:

<?php
$server_name = localhost;
$username = username;
$password = password;
// Establishing a connection
$con = new mysqli($server_name, $username, $password);
// Check connection
if ($con->connect_error) {
die(Connection failed: . $con->connect_error);
}
// Create database
$sql = CREATE DATABASE dbName;
if ($con->query($sql) === TRUE) {

echo Database created successfully;


} else {
echo Error creating database: . $con->error;
}
$con->close();
?>

Without Object Oriented Format Example:

<?php
$server_name = localhost;
$username = username;
$password = password;
// Establishing a connection
$con = mysqli_connect($server_name, $username, $password);
// Check connection
if (!$con) {
die(Connection failed: . mysqli_connect_error());
}
// Create database
$sql = CREATE DATABASE dbName;
if (mysqli_query($con, $sql)) {
echo Database created successfully;
} else {
echo Error creating database: . mysqli_error($con);
}
mysqli_close($con);
?>

Now that we have created a database, we can move on to create a table in the database.
This table will hold columns and rows of data. In order to do this, we must understand
how the MySQL Query language works. Again, we will start to gain familiarity on this as
we read and practice it. The query string in this case would be:

CREATE TABLE Employee_table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),

birth_date TIMESTAMP

Now this looks daunting but is quite simple Remember; if you forget any syntax, you
can always refer to documentation, as it is well documented and easy to read. As seen,
every table should have a primary key column (in this case, its ID) and its value would
change for each new record or row in the table.

The first element of creating a table is to use the CREATE TABLE keywords and then
name it accordingly. Next, we use normal brackets to surround all the different columns
we want to add to the table. To do this we simply just name the column we want to add
and then add the data type we want it to be. I will list all the data types in a moment, but
before that, lets go over what you write after the data type:

After the data type, you can specify other attributes for each column (optional):

NOT NULL - Each segment must contain a value for that area, invalid qualities are not
allowed

DEFAULT regard - Set a default regard that is incorporated when no other worth is
passed

UNSIGNED - Used for number sorts, obliges the set away data to positive numbers and
zero

AUTO INCREMENT - MySQL actually grows the estimation of the field by 1 each time
another record is incorporated

PRIMARY KEY - Used to phenomenally perceive the sections in a table. The section
with PRIMARY KEY setting is consistently an ID number, and is every now and again
used
Now to actually implement the creation of a table to a database, here is how it would be
done in the code:

OBJECT ORIENTED Format Example:

<?php
$server_name = localhost;

$username = username;
$password = password;
$dbname = dbName;
// Establishing a connection
$con = new mysqli($server_name, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die(Connection failed: . $con->connect_error);
}
$sql = INSERT INTO Employee_table (firstname, lastname, email)
VALUES (Bob, Doe, bob@hotmail.com);
$con->close();
?>

Without Object Oriented Format Example:

<?php
$server_name = localhost;
$username = username;
$password = password;
$dbname = dbName;
// Establishing a connection
$con = mysqli_connect($server_name, $username, $password, $dbname);
// Check connection
if (!$con) {
die(Connection failed: . mysqli_connect_error());
}
$sql = INSERT INTO Employee_table (firstname, lastname, email)
VALUES (Bob, Doe, bob@hotmail.com);
mysqli_close($con);
?>

Summary of data types in MySQL



Text Use for content or blends of content and numbers. 255 characters greatest

Memo Memo is utilized for bigger measures of content. Amasses to 65,536
characters. Note: You cant sort a reminder field. In any case, they are searchable

Byte Allows entire numbers from 0 to 255 1 byte

Integer Allows entire numbers between -32,768 and 32,767 2 bytes

Long Allows entire numbers between -2,147,483,648 and 2,147,483,647 4
bytes

Single exactness coasting point. Will handle most decimals 4 bytes

Double accuracy drifting point. Will handle most decimals 8 bytes

Currency Use for cash. Holds up to 15 digits of entire dollars, in addition to 4
decimal spots. Tip: You can pick which nations money to use 8 bytes

AutoNumber AutoNumber fields consequently give every record its own number,
normally beginning at 1 4 bytes

Date/Time Use for dates and times 8 bytes

Yes/No A coherent field can be shown as Yes/No, True/False, or On/Off. In code,
utilize the constants True and False (proportional to -1 and 0). Note: Null qualities are not
permitted in Yes/No fields 1 bit

Ole Object Can store pictures, sound, feature, or different BLOBs (Binary Large
Objects up to 1GB

Hyperlink Contain connections to different records, including pages


Lookup Wizard Let you write a rundown of choices, which can then be browsed a
drop-down list 4 bytes

Fundamental Sorts

In MySQL there are three fundamental sorts: content, number, and Date/Time sorts.

CHAR(size) Holds an altered length string (can contain letters, numbers, and
uncommon characters). The altered size is indicated in enclosure. Can save to 255
characters

VARCHAR(size) Holds a variable length string (can contain letters, numbers, and
unique characters). The most extreme size is indicated in enclosure. Can stockpile to 255
characters. Note: If you put a more prominent worth than 255 it will be changed over to a
TEXT sort

TINYTEXT Holds a string with a greatest length of 255 characters

TEXT Holds a string with a greatest length of 65,535 characters

BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of
information

MEDIUMTEXT Holds a string with a greatest length of 16,777,215 characters

MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215
bytes of information

LONGTEXT Holds a string with a greatest length of 4,294,967,295 characters

LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295
bytes of information

ENUM(x,y,z,etc.) Let you enter a rundown of conceivable qualities. You can

rundown up to 65535 qualities in an ENUM list. In the event that a quality is embedded
that is not in the rundown, a clear esteem will be embedded.

Note: The qualities are sorted in the request you enter them.

You enter the conceivable values in this organization: ENUM(X,Y,Z)

SET Similar to ENUM with the exception of that SET may contain up to 64
rundown things and can store more than one decision

TINYINT(size) -128 to 127 typical. 0 to 255 UNSIGNED*. The most extreme
number of digits may be determined in bracket

SMALLINT(size) -32768 to 32767 typical. 0 to 65535 UNSIGNED*. The most
extreme number of digits may be determined in bracket

MEDIUMINT(size) -8388608 to 8388607 typical. 0 to 16777215 UNSIGNED*.
The most extreme number of digits may be determined in bracket

INT(size) -2147483648 to 2147483647 typical. 0 to 4294967295 UNSIGNED*.
The most extreme number of digits may be determined in bracket

BIGINT(size) -9223372036854775808 to 9223372036854775807 typical. 0 to
18446744073709551615 UNSIGNED*. The most extreme number of digits may be
determined in bracket

FLOAT(size,d) A little number with a skimming decimal point. The greatest
number of digits may be determined in the size parameter. The greatest number of digits to
one side of the decimal point is indicated in the d parameter

DOUBLE(size,d) A vast number with a drifting decimal point. The greatest
number of digits may be indicated in the size parameter. The most extreme number of
digits to one side of the decimal point is determined in the d parameter

DECIMAL(size,d) A DOUBLE put away as a string , taking into account an
altered decimal point. The most extreme number of digits may be determined in the size
parameter. The greatest number of digits to one side of the decimal point is indicated in

the d parameter

*The whole number sorts have an additional choice called UNSIGNED. Typically, the
number goes from a negative to positive quality. Including the UNSIGNED trait will
move that range up so it begins at zero rather than a negative number.

DATE() A date. Position: YYYY-MM-DD

Note: The upheld extent is from 1000-01-01 to 9999-12-31

DATETIME() *A date and time blend. Form: YYYY-MM-DD HH:MI:SS

Note: The upheld reach is from 1000-01-01 00:00:00 to 9999-12-31 23:59:59

TIMESTAMP() *A timestamp. TIMESTAMP qualities are put away as the
quantity of seconds following the Unix age (1970-01-01 00:00:00 UTC). Design:
YYYY-MM-DD HH:MI:SS

Note: The bolstered extent is from 1970-01-01 00:00:01 UTC to 2038-01-09 03:14:07
UTC

TIME() A time. Form: HH:MI:SS

Note: The upheld extent is from -838:59:59 to 838:59:59

YEAR() A year in two-digit or four-digit design.

Note: Values permitted in four-digit design: 1901 to 2155. Qualities permitted in two-digit
design: 70 to 69, speaking to years from 1970 to 2069

*Even if DATETIME and TIMESTAMP return the same arrangement, they work in an
unexpected way. In an INSERT or UPDATE question, the TIMESTAMP naturally set
itself to the present date and time. TIMESTAMP likewise acknowledges different
configurations, as YYYYMMDDHHMISS, YYMMDDHHMISS, YYYYMMDD, or
YYMMDD.


SQL Server Data Types

String sorts

Information type Description Storage

char(n) Fixed width character string. Greatest 8,000 characters Defined
width

varchar(n) Variable width character string. Greatest 8,000 characters 2
bytes + number of roasts

varchar(max) Variable width character string. Greatest 1,073,741,824
characters 2 bytes + number of roasts

text Variable width character string. Greatest 2GB of content data 4 bytes
+ number of roasts

nchar Fixed width Unicode string. Greatest 4,000 characters Defined
width x 2

nvarchar Variable width Unicode string. Greatest 4,000 characters

nvarchar(max) Variable width Unicode string. Greatest 536,870,912 characters

ntext Variable width Unicode string. Greatest 2GB of content information

bit Allows 0, 1, or NULL

binary(n) Fixed width double string. Greatest 8,000 bytes

varbinary Variable width double string. Greatest 8,000 bytes

varbinary(max) Variable width twofold string. Most extreme 2GB



image Variable width twofold string. Most extreme 2GB

Number sorts:

Information type Description Storage

tinyint Allows entire numbers from 0 to 255 1 byte

smallint Allows entire numbers between -32,768 and 32,767 2 bytes

int Allows entire numbers between -2,147,483,648 and 2,147,483,647 4
bytes

bigint Allows entire numbers between -9,223,372,036,854,775,808 and
9,223,372,036,854,775,807 8 bytes

decimal(p,s) Fixed accuracy and scale numbers.

Permits numbers from -10^38 +1 to 10^38 1.

The p parameter shows the most extreme aggregate number of digits that can be put away
(both to one side and to one side of the decimal point). p must be a worth from 1 to 38.
Default is 18.

The s parameter shows the most extreme number of digits put away to one side of the
decimal point. s must be a worth from 0 to p. Default worth is 0

5-17 bytes

numeric(p,s) Fixed exactness and scale numbers.

Permits numbers from -10^38 +1 to 10^38 1.


The p parameter demonstrates the greatest aggregate number of digits that can be put
away (both to one side and to one side of the decimal point). p must be a worth from 1 to
38. Default is 18.

The s parameter shows the most extreme number of digits put away to one side of the
decimal point. s must be a quality from 0 to p. Default worth is 0

5-17 bytes

smallmoney Monetary information from -214,748.3648 to 214,748.3647 4
bytes

money Monetary information from -922,337,203,685,477.5808 to
922,337,203,685,477.5807 8 bytes

float(n) Floating exactness number information from -1.79E + 308 to 1.79E + 308.

The n parameter demonstrates whether the field ought to hold 4 or 8 bytes. float(24) holds
a 4-byte field and float(53) holds a 8-byte field. Default estimation of n is 53.

4 or 8 bytes

real Floating exactness number information from -3.40E + 38 to 3.40E +
38 4 bytes

datetime From January 1, 1753 to December 31, 9999 with a precision of
3.33 milliseconds 8 bytes

datetime2 From January 1, 0001 to December 31, 9999 with a precision of 100
nanoseconds 6-8 bytes

smalldatetime From January 1, 1900 to June 6, 2079 with a precision of 1
minute 4 bytes

date Store a date just. From January 1, 0001 to December 31, 9999 3 bytes

time Store a period just to a precision of 100 nanoseconds 3-5 bytes

datetimeoffset The same as datetime2 with the expansion of a period zone
offset 8-10 bytes

timestamp Stores a special number that gets redesigned each time a column gets
made or changed. The timestamp worth is based upon an inside clock and does not
compare to ongoing. Every table may have one and only timestamp variable

Other Information Sorts

Information type Description

sql_variant Stores up to 8,000 bytes of information of different information sorts,
aside from content, ntext, and timestamp

uniqueidentifier Stores an internationally exceptional identifier (GUID)

xml Stores XML designed information. Greatest 2GB

cursor Stores a reference to a cursor utilized for database operations

After a database and a table have been created, we can start adding data in them.
Here are the syntax rules to review:

When inserting information, you might need to watch out for some syntax rules that might
mess up your query. The first one is that whenever youre working with an SQL query
within PHP, it must be quoted. This isnt the case when youre working with simply
sending queries to your database without the use of a programming language that can
communicate with MySQL.

The next thing you need to watch out for is that whenever you want to insert information
of string type (text), they must be quoted. For example, if you want to insert data in to the

second record (row) of the first name column and change it to John instead of Peter
then you must point out this new information using a quotation mark. Again, this will
make more sense to you once we have actually started to develop a query to do stuff like
this. Also, what I have just explained is an idea of updating data in databases which is
what well be talking about soon after this section of the guide.

Moving on, the next syntax rule you must remember is that if youre updating or inserting
data of any numeric value, it must not be quoted. In many programming languages, even,
including PHP, when you are declaring variables, you dont set your value of the variable
in quotes if it is a number. That way, the program can differentiate the difference between
what text (string) is and what a number (int/double/float) is.

Finally, if youre ever wanting to set anything or add anything NULL which simple means
to make the record at that specific section empty, then that keyword must not be quoted. If
it is quoted, it will be mistaken as a string, and therefore have the world NULL literally be
printed out in the specific record.

Now to actually insert data in to table, we must the following format as a query:

INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3)

Now previously, we created a table named Employee_table with the five columns as id,
firstname, lastname, email, and birth_date.

In order to actually create it through PHP code, you must do the following:

OBJECT ORIENTED Format Example:

<?php
$server_name = localhost;
$username = username;
$password = password;
$dbname = dbName;
// Establishing a connection
$conn = new mysqli($server_name, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {

die(Connection failed: . $conn->connect_error);


}
$sql = INSERT INTO Employee_table (firstname, lastname, email)
VALUES (Bob, Doe, bob@example.com);
$conn->close();
?>

Without Object Oriented Format Example:

<?php
$server_name = localhost;
$username = username;
$password = password;
$dbname = dbName;
// Establishing a connection
$conn = mysqli_connect($server_name, $username, $password, $dbname);
// Check connection
if (!$conn) {
die(Connection failed: . mysqli_connect_error());
}
$sql = INSERT INTO Employee_table (firstname, lastname, email)
VALUES (Bob, Doe, bob@hotmail.com);
mysqli_close($conn);
?>

There are still much more things to learn regarding inserting data in to MySQL but this is
a PHP guide, not a MySQL guide. Lets go over the last two final basic steps for
understanding MySQL. Lets learn how to retrieve data from tables or SELECT data from
tables. Here is the query format:

SELECT column_name(s) FROM table_name

OR we can use the * character to select ALL columns from a table:

SELECT * FROM table_name


OBJECT ORIENTED Format Example:

<?php
$server_name = localhost;
$username = username;
$password = password;
$dbname = dbName;
// Establishing a connection
$conn = new mysqli($server_name, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(Connection failed: . $conn->connect_error);
}
$sql = SELECT id, firstname, lastname FROM Employee_table;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo id: . $row[id]. - Name: . $row[firstname]. .
$row[lastname]. <br>;
}
} else {
echo 0 results;
}
$conn->close();
?>

So exactly is happening here? Well, first of all, we must set up an SQL query that selects
the id, firstname, and lastname columns from the Employee_table table. The next line will
then run the query and put the resulting data in to a variable called $result. Then a function
checks if more than zero rows have been returned and if they have, a function
fetch_assoc() puts all the results in to an associative array that is then Looped through to
echo the results out.

Without Object Oriented Format Example:

<?php
$server_name = localhost;

$username = username;
$password = password;
$dbname = dbName;
// Establishing a connection
$conn = mysqli_connect($server_name, $username, $password, $dbname);
// Check connection
if (!$conn) {
die(Connection failed: . mysqli_connect_error());
}
$sql = SELECT id, firstname, lastname FROM Employee_table;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo id: . $row[id]. - Name: . $row[firstname]. .
$row[lastname]. <br>;
}
} else {
echo 0 results;
}
mysqli_close($conn);
?>

Let us finally go over the idea of deleting data from a MySQL Table using PHP and the
MySQLi function. The query format to do so would be the following:

DELETE FROM table_name
WHERE some_column = some_value

Table before deletion:

id firstname lastname email birth_date
1 John Doe john@example.com 2015-1024 14:26:15
2 Mary Moe mary@example.com 201510-23 10:22:30
3 Jane Lane julie@example.com 201510-26 10:48:23


OBJECT ORIENTED Format Example:

<?php
$server_name = localhost;
$username = username;
$password = password;
$dbname = dbName;
// Establishing a connection
$conn = new mysqli($server_name, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(Connection failed: . $conn->connect_error);
}
// sql to delete a record
$sql = DELETE FROM Employee_table WHERE id=3;

$conn->close();
?>

Without Object Oriented Format Example:

<?php
$server_name = localhost;
$username = username;
$password = password;
$dbname = dbName;
// Establishing a connection
$conn = mysqli_connect($server_name, $username, $password, $dbname);
// Check connection
if (!$conn) {
die(Connection failed: . mysqli_connect_error());
}
// sql to delete a record
$sql = DELETE FROM Employee_table WHERE id=3;

mysqli_close($conn);

?>

Table after deletion:

id firstname lastname email birth_date
1 John Doe john@example.com 2015-1024 14:26:15
2 Mary Moe mary@example.com 201510-23 10:22:30

We have went over the basics of what PHP and MySQL has to offer in conjunction with
one another and the power they have when working together. Lets now apply what we
learned here and make a login system.

Chapter 13
Application of MySQL with Login/Registration

Login System Creation



We have now learned about PHP and MySQL and the underlying power they possess
when working together. Now lets work on applying our knowledge to real-world projects.
Lets work on creating a login system and see how it may work. Lets start with a simple
HTML form to work with. An HTML form is going to allow us to send a query to PHP
with information to work with. There are two methods when configuring a property of the
form. This property is called an: HTTP Request Method.

There are two types of HTTP Request methods: GET and POST. When sending
information from PHP, one can either request data or submit data. POST submits data to
be processed, whereas GET requests data. When pressing the submit button on a form, the
information gets passed to the URL, and the GET method takes the information from the
URL and processes it however it was coded to be processed in the code. POST on the
other hand does not use the URL to process data, but rather directly submits data for PHP
to process the code. When submitting a form with GET, it will display information on the
URL, with each key and value of the form separated by an & symbol and the start
symbol would be ?.

Now lets get in to the creation of the HTML form. The first thing we must know is the
form tag, this can simply be written as <form> and ending with a </form>.

<form>
</form>

Once this has been complete, we must define the action attribute of the form. This
action attribute is in charge of telling the form where to redirect the page to, which will
receive the information submitted in the form with the specified method (GET / POST).
So essentially, most of the time, the action attributes value is a php file. In this case, were
going to be using the file name itself: login.php. This form is also being created in this
file, so it will essentially redirect itself back to itself in order to send the information to the
PHP code in the file. Therefore, we are going to set the action attributes value to
login.php.

<form action = login.php>
</form>

Next, we must define the type of method were using. Since we want to do the more
conventional way of submitting the information, we are going to use the POST method.

Both methods can accomplish the same task but the GET method has a few security
issues. Since the information shows up in the URL, many people would be able to see the
password submitted in the form. Due to this, we are going to be using the POST method
which is more discrete. In order to do this, we must use the method form attribute and
set the value accordingly to POST.

<form action = login.php method = POST>
</form>

Now that we have created the skeleton of our form, lets fill it with text boxes to allow the
user to input information in it. In order to create a textbox, we must use the input tag.

<input>

Now there are a few attributes we are going to need to add to this input tag. We are going
to need to look over the: type, name, id and value attributes. The type attribute is
essentially a way to tell the textbox what type of input it will be receiving and how it will
interpret it. The type can be set to text to indicate that it will be receiving and displaying
test. This can also be set to password which would then process the text and display it as
asterisks (stars) accordingly. Next, we are going to over the name attribute. The name
attribute simply is like the id tag in which it identifies itself to the PHP code when
communicating its value it possesses on submission of the form. The same goes with the
id attribute. The id attribute is more conventionally used to identify itself, but well use
both because theres no reason to not use both. Finally, the value attribute simply sets a
default value in the text-field if nothing is filled. We just want to keep our form empty,
without any fancy Javascript, so we wont need to use this attribute.

<input type = text name = username id = username>

Next, we are going to add the password input field.

<input type = password name = password id = password>

Then we must end the form.

</form>

It should now look like this overall:



<form action = login.php method = POST>

<input type = text name = username id = username>
<input type = password name = password id = password>

</form>

Now that we are complete the HTML form, we can work on the PHP code that receives
the information from the form. First, we must understand a few functions. The isset
function simply checks whether or not information has been received successfully and
contains data. The syntax to check for every field, depending on the method is:
$_POST[idname] where idname would be the id/name you set for the input fields. Once
we have checked that all these fields are not empty and have successfully received the
information, we will then send a query as we have learned to check whether or not the
username exists. We do the same for the password field.

We will also include a connection file in the PHP code. This is how it looks:

<?php

class connect {

function mysqli_connect() {

$host = localhost;
$dbname = appbukki_database;
$user = appbukki_admin;
$pass = battle123;

$con = @mysqli_connect($host, $user, $pass, $dbname);
if (mysqli_connect_errno($con)) {
die (Could not connect to MySQL: .mysqli_connect_error());

}else{
//echo Connected;
}
}

}

?>

There is a better way to check if the username and password exist in the same row, so the
information doesnt mismatch, but for simplicity purposes, well go with this example as
shown here using the POST method:

<?php

session_start();

require_once functions/connect.php;

$connect = new connect;
$connect->mysqli_connect();
$con = mysqli_connect(localhost, appbukki_admin, battle123, appbukki_database);

if (isset($_POST[username]) && isset ($_POST[password])) {
if (!empty($_POST[username]) && !empty ($_POST[password])) {

$username = $_POST[username];
$password = $_POST[password];

$username_check = false;
$password_check = false;

$query = SELECT `username` FROM `users_list` WHERE 1;

if ($result = mysqli_query($con, $query)) {


while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row[username]) {
$username_check = true;
//echo OK Username;
break;
}else{
$username_check = false;
}
}
}

if ($username_check == true) {
$query = SELECT `password` FROM `users_list` WHERE
`username` = $username;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($password == $row[password]) {
$password_check = true;
//echo OK Password;
break;
}else{
$password_check = false;
}
}
}
}else{
echo Username is invalid.;
}
if ($password_check == false) {
echo Password is invalid.;
}

if ($username_check == true && $password_check) {


$_SESSION[login] = true;
Header(Location: index.php);
}

}else{
echo Please fill in all fields.;
}
}
ob_end_flush();

?>

Here is the same code with the GET instead of POST method:

<?php

session_start();

require_once functions/connect.php;

$connect = new connect;
$connect->mysqli_connect();
$con = mysqli_connect(localhost, appbukki_admin, battle123, appbukki_database);

if (isset($_GET[username]) && isset ($_GET[password])) {
if (!empty($_GET[username]) && !empty ($_GET [password])) {

$username = $_POST[username];
$password = $_POST[password];

$username_check = false;

$password_check = false;

$query = SELECT `username` FROM `users_list` WHERE 1;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row[username]) {
$username_check = true;
//echo OK Username;
break;
}else{
$username_check = false;
}
}
}

if ($username_check == true) {
$query = SELECT `password` FROM `users_list` WHERE
`username` = $username;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($password == $row[password]) {
$password_check = true;
//echo OK Password;
break;
}else{
$password_check = false;
}
}
}
}else{
echo Username is invalid.;
}
if ($password_check == false) {

echo Password is invalid.;


}

if ($username_check == true && $password_check) {
$_SESSION[login] = true;
Header(Location: index.php);
}

}else{
echo Please fill in all fields.;
}
}
ob_end_flush();

?>

This page is now covered with CSS and requires statements from other files in my FTP
server, but this is how it would look like as a rough outline for a login system:

<?php
ob_start();
session_start();

require_once structure/template_nologin.php;
require_once functions/connect.php;

$connect = new connect;
$connect->mysqli_connect();
$con = mysqli_connect(localhost, appbukki_admin, battle123, appbukki_database);

if (isset($_POST[username]) && isset ($_POST[password])) {
if (!empty($_POST[username]) && !empty ($_POST[password])) {

$username = $_POST[username];
$password = $_POST[password];

$username_check = false;
$password_check = false;

$query = SELECT `username` FROM `users_list` WHERE 1;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row[username]) {
$username_check = true;
//echo OK Username;
break;
}else{
$username_check = false;
}
}
}

if ($username_check == true) {
$query = SELECT `password` FROM `users_list` WHERE
`username` = $username;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($password == $row[password]) {
$password_check = true;
//echo OK Password;
break;
}else{
$password_check = false;
}
}
}

}else{
echo Username is invalid.;
}
if ($password_check == false) {
echo Password is invalid.;
}

if ($username_check == true && $password_check) {
$_SESSION[login] = true;
Header(Location: index.php);
}

}else{
echo Please fill in all fields.;
}
}
ob_end_flush();

?>
<head><title>AppBukkit - Login</title></head>
<form style = font-family: Open Sans, sans-serif; text-align:center; action =
login.php method = POST>
<input style = font-family: Open Sans, sans-serif; padding-left: 15px; line-height:
2em; font-size: 18px; width:300px; height:30px; type = text name = username id =
username value = username
onClick=javascript: document.getElementById(username).value=><br><br>
<input style = font-family: Open Sans, sans-serif; padding-left: 15px; line-height:
2em; font-size: 18px; width:300px; height:30px; type = text name = password id =
password value = password
onClick=javascript: document.getElementById(password).value=><br><br>
<div id = makeCenter> <input style = font-family: Open Sans, sans-serif;
openheight: 30px; width: 7em; font-size: 24px; type = submit value = Login> </div>
</form>

Chapter 14
Registration System Creation

A registration system is similar to a login system except the MySQL query would be to
insert data rather than select/search for data in a MySQL database. Since we have covered
a lot of what forms and their attributes mean, were going to go by quick in this section.

The first thing we must do is create a form for our registration. We want the user to type in
the username they want, their email, password and finally password verification. This is a
rather simple registration form but is effective enough to have you understand the idea
how it works. Our form would now look like this:

<form action = register.php method = POST>
<input type = text name = username id = username value = username>
<input type = text name = email id = email value = email>
<input type = password name = password id = password value = password>
<input type = password name = password_verify id = password_verify value =
password>
<input type = submit value = Register> </div>
</form>
As shown above, we are going to be using a POST method for this registration form for
security purposes. The next thing we must do is connect to the MySQL Server.
require_once functions/connect.php;
$connect = new connect;
$connect->mysqli_connect();
$con = mysqli_connect(localhost, appbukki_admin, battle123, appbukki_database);
Once we have connected, we must check if all our fields arent empty and whether or
not the data has been received successfully.
if
(isset($_POST[username])
&&
isset
($_POST[password])
isset($_POST[email]) && isset($_POST[password_verify])) {

&&

if (!empty($_POST[username]) && !empty ($_POST[password])


!empty($_POST[email]) && !empty($_POST[password_verify])) {

&&

Next, we are going to assign our variables to the fields.


$username = $_POST[username];
$password = $_POST[password];

$password_verify = $_POST[password_verify];
$email = $_POST[email];

$username_check = false;
$password_check = false;
$email_check = filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match(/@.+./, $email);
$email_check_db = false;
As shown in the $email_check variable, we are simply making sure that it was a valid
email that the user used to sign up. Next, we are going to check if the passwords exist in
the system, the username and finally the email with the following code:
if ($password != $password_verify) {
echo Passwords do not match.;
}else{
$password_check = true;
}

$query = SELECT `username` FROM `users_list` WHERE 1;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row[username]) {
$username_check = false;
echo Username already in use.;
break;
}else{
$username_check = true;
}
}
}

$query = SELECT `email` FROM `users_list` WHERE 1;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {

if ($username == $row[email]) {
$email_check_db = false;
echo That is an invalid email.;
break;
}else{
$email_check_db = true;
}
}
}
Then finally we do a final if statement to check if everything came out to be true, and if
so, it will invoke the registration as successful.
if ($username_check == true && $password_check == true && $email_check
== true && $email_check_db == true) {
$query = INSERT INTO `appbukki_database`.`users_list` (`id`,
`username`, `password`, `email`, `paypal`) VALUES (NULL, $username, $password,
$email, NULL);
if ($result = mysqli_query($con, $query)) {
echo Registration Successful!;
}else{
echo Error;
}
}
The total document looks like this (with CSS):
<?php
require_once structure/template_nologin.php;
require_once functions/connect.php;

$connect = new connect;
$connect->mysqli_connect();
$con = mysqli_connect(localhost, appbukki_admin, battle123, appbukki_database);

if
(isset($_POST[username])
&&
isset
($_POST[password])
isset($_POST[email]) && isset($_POST[password_verify])) {
if

(!empty($_POST[username])

&&

!empty

($_POST[password])

&&
&&

!empty($_POST[email]) && !empty($_POST[password_verify])) {



$username = $_POST[username];
$password = $_POST[password];
$password_verify = $_POST[password_verify];
$email = $_POST[email];

$username_check = false;
$password_check = false;
$email_check = filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match(/@.+./, $email);
$email_check_db = false;
//if ($email_check) {echo true;}else{echo false;}

if ($password != $password_verify) {
echo Passwords do not match.;
}else{
$password_check = true;
}

$query = SELECT `username` FROM `users_list` WHERE 1;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row[username]) {
$username_check = false;
echo Username already in use.;
break;
}else{
$username_check = true;
}
}
}

$query = SELECT `email` FROM `users_list` WHERE 1;


if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row[email]) {
$email_check_db = false;
echo That is an invalid email.;
break;
}else{
$email_check_db = true;
}
}
}

if ($username_check == true && $password_check == true && $email_check
== true && $email_check_db == true) {
$query = INSERT INTO `appbukki_database`.`users_list` (`id`,
`username`, `password`, `email`, `paypal`) VALUES (NULL, $username, $password,
$email, NULL);
if ($result = mysqli_query($con, $query)) {
echo Registration Successful!;
}else{
echo Error;
}
}

}else{
echo Please fill in all fields.;
}
}

?>
<head><title>AppBukkit - Registration</title></head>
<table cellpadding = 30px cellspacing = 0 align = center border = 1 style =

background: rgba(0,0,0,0.5); border: 1px solid white;>


<tr><td>
<form style = font-family: Open Sans, sans-serif; text-align:center; action =
register.php method = POST>

<input style = border: 1px solid white; color: white; background: rgba(0, 0, 0, 0.5);
font-family: Open Sans, sans-serif; padding-left: 15px; padding-bottom: 2px; lineheight: 2em; font-size: 18px; width:300px; height:30px; type = text name =
username id = username value = username
onClick=javascript: document.getElementById(username).value=><br><br>
<input style = border: 1px solid white; color: white; background: rgba(0, 0, 0, 0.5);
font-family: Open Sans, sans-serif; padding-left: 15px; padding-bottom: 2px; lineheight: 2em; font-size: 18px; width:300px; height:30px; type = text name = email id
= email value = email
onClick=javascript: document.getElementById(email).value=><br><br>
<input style = border: 1px solid white; color: white; background: rgba(0, 0, 0, 0.5);
font-family: Open Sans, sans-serif; padding-left: 15px; padding-bottom: 2px; lineheight: 2em; font-size: 18px; width:300px; height:30px; type = password name =
password id = password value = password
onClick=javascript: document.getElementById(password).value=><br><br>
<input style = border: 1px solid white; color: white; background: rgba(0, 0, 0, 0.5);
font-family: Open Sans, sans-serif; padding-left: 15px; padding-bottom: 2px; lineheight: 2em; font-size: 18px; width:300px; height:30px; type = password name =
password_verify id = password_verify value = password

onClick=javascript:
<br>

document.getElementById(password_verify).value=><br>

<div id = makeCenter> <input style = font-family: Open Sans, sans-serif;


openheight: 10px; width: 7em; font-size: 18px; type = submit value = Register>
</div>
</form>
</td></tr>
</table>
<br><br><br><br><br><br>
This is the document with the GET statements:
<?php
require_once structure/template_nologin.php;

require_once functions/connect.php;

$connect = new connect;
$connect->mysqli_connect();
$con = mysqli_connect(localhost, appbukki_admin, battle123, appbukki_database);

if (isset($_GET [username]) && isset ($_GET [password]) && isset($_GET [email])
&& isset($_GET [password_verify])) {
if (!empty($_POST[username]) && !empty ($_POST[password])
!empty($_POST[email]) && !empty($_POST[password_verify])) {

&&


$username = $_POST[username];
$password = $_POST[password];
$password_verify = $_POST[password_verify];
$email = $_POST[email];

$username_check = false;
$password_check = false;
$email_check = filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match(/@.+./, $email);
$email_check_db = false;
//if ($email_check) {echo true;}else{echo false;}

if ($password != $password_verify) {
echo Passwords do not match.;
}else{
$password_check = true;
}

$query = SELECT `username` FROM `users_list` WHERE 1;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row[username]) {

$username_check = false;
echo Username already in use.;
break;
}else{
$username_check = true;
}
}
}

$query = SELECT `email` FROM `users_list` WHERE 1;
if ($result = mysqli_query($con, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row[email]) {
$email_check_db = false;
echo That is an invalid email.;
break;
}else{
$email_check_db = true;
}
}
}

if ($username_check == true && $password_check == true && $email_check
== true && $email_check_db == true) {
$query = INSERT INTO `appbukki_database`.`users_list` (`id`,
`username`, `password`, `email`, `paypal`) VALUES (NULL, $username, $password,
$email, NULL);
if ($result = mysqli_query($con, $query)) {
echo Registration Successful!;
}else{
echo Error;
}
}


}else{
echo Please fill in all fields.;
}
}

?>
<head><title>AppBukkit - Registration</title></head>
<table cellpadding = 30px cellspacing = 0 align = center border = 1 style =
background: rgba(0,0,0,0.5); border: 1px solid white;>
<tr><td>
<form style = font-family: Open Sans, sans-serif; text-align:center; action =
register.php method = POST>

<input style = border: 1px solid white; color: white; background: rgba(0, 0, 0, 0.5);
font-family: Open Sans, sans-serif; padding-left: 15px; padding-bottom: 2px; lineheight: 2em; font-size: 18px; width:300px; height:30px; type = text name =
username id = username value = username
onClick=javascript: document.getElementById(username).value=><br><br>
<input style = border: 1px solid white; color: white; background: rgba(0, 0, 0, 0.5);
font-family: Open Sans, sans-serif; padding-left: 15px; padding-bottom: 2px; lineheight: 2em; font-size: 18px; width:300px; height:30px; type = text name = email id
= email value = email
onClick=javascript: document.getElementById(email).value=><br><br>
<input style = border: 1px solid white; color: white; background: rgba(0, 0, 0, 0.5);
font-family: Open Sans, sans-serif; padding-left: 15px; padding-bottom: 2px; lineheight: 2em; font-size: 18px; width:300px; height:30px; type = password name =
password id = password value = password
onClick=javascript: document.getElementById(password).value=><br><br>
<input style = border: 1px solid white; color: white; background: rgba(0, 0, 0, 0.5);
font-family: Open Sans, sans-serif; padding-left: 15px; padding-bottom: 2px; lineheight: 2em; font-size: 18px; width:300px; height:30px; type = password name =
password_verify id = password_verify value = password

onClick=javascript:
<br>

document.getElementById(password_verify).value=><br>

<div id = makeCenter> <input style = font-family: Open Sans, sans-serif;

openheight: 10px; width: 7em; font-size: 18px; type = submit value = Register>
</div>
</form>
</td></tr>
</table>

Chapter 15
In Closing

This is the start of your journey as a MySQL and PHP programmer. You have barely
scratched the surface with this guide as learning the syntax and conventions of a language
is just the beginning. The most important part of programming is the logical aspect of it.
Sure, you may know how to loop through an array of variables like a list of shopping
items but if someone asks you to process an image using your knowledge of
programming, and with the help of an API and some thinking, you can figure out how you
are able to invert colors of an image, flip it, rotate it, scale it, etc.

The real programming comes in the logical portion of the mind. Its similar to when
youre learning any other language, like English for example. You may understand the
grammar rules and the conventions like adding periods to the end of sentences, but to be
able to write clean and logical thought-out and structured essays is where the true skill
lies. The same concept applies to programming where the person writing the code, must
know how to apply his knowledge of the rules in the considered language, like MySQL
and PHP, and use it to his advantage to come up with neat programs.

The knowledge and understanding of programming is truly great because its the closest
thing to having a power. You can literally create something out of an empty notepad, from
scratch and have it function to do things you want it to do. Whether it be a bot to analyze
the stock market and come up with predictions or creating a game. That choice is yours.

In this guide, you have learned the fundamentals of MySQL and PHP. You havent learned
all the possible methods that can be used in the language, but that isnt the point. The point
of this guide was to set you on a journey to discover objects and methods that you need in
order to help you to create programs that you desire. You have been given the optimum
knowledge to understand reading an API and be able to understand what it is saying and
adding to your code.

Good luck as a new-born MySQL and PHP programmer!
Eprogramy


PD: One more thing. here in Eprogramy we want to to give you a gift. If you enjoy
JavaScript as much as we do, youll probably will love Java too. So In the next section
you will find a preview our JAVA CRASH COURSE - The Ultimate Beginners
Course to Learning Java Programming in Under 12 Hours


I know youll love it!

You can find it on Amazon, under our name, Eprogramy, or by following this link:

http://www.amazon.com/Java-Ultimate-Beginners-Learning-Programmingebook/dp/B00Y96U1D2

Preview of JAVA CRASH COURSE - The Ultimate Beginners Course to


Learning Java Programming in Under 12 Hours

Introduction
Welcome to Your New Programming Language

So, youve decided to learn Java Programming? Well, congratulations and welcome to
your new Programming Language! Youre going to love it!

In Eprogramy we believe that the foundation of a good education is to provide the tools
able to open the doors of the future. It is indisputable that the world has entered an era in
which we all have everything at the fingertips. Social needs have changed. Thus, today
communication has changed. Communication opens doors, so it is our challenge to learn
how to communicate. In Eprogramy we want you to learn how to communicate with a
new language: The programming language. This language allows us to use our PC or
notebook to create.

Maybe the road is difficult and hard, but we will give the reader the tools to make learning
enjoyable and fruitful. Well show all aspects necessary to learn how to program. From
the installation of software to the solution of the most common programming problems
and much, much more. Always with the help of numerous examples that will contribute to
a better understanding

We know what we do and believe that you are fully capable of incorporating our
teachings.

The doors of the future are here. Lets go step by step together.

Lets get started!

Eprogramy Team

Chapter 1
Java Programing Language

History of Java

Java is a programming language that was first publicly available in 1995, created by James
Gosling from Sun Microsystems (Sun) in 1991. Sun Microsystems was then inherited by
Oracle, and is the corporation in charge of the programming languages faith. Java then
became open source available under the GNU General Public License (GPL).

The language gets much of its syntax from C and C++ but isnt as powerful because it
requires less for the user to do (less customization but more simple). Something like
garbage collection, the process of reducing memory being used from the program, is
automated in Java.

It was originally designed for interactive television but surpassed the technology and
design of the digital cable television industry at the time. There were five principles that
were used in the creation of the Java programming language:

1. It must be simple, object-oriented and familiar

2. It must be robust and secure

3. It must be architecture-neutral and portable

4. It must execute with high performance

5. It must be interpreted, threaded, and dynamic

Another important design goal to note is portability, which is was a key factor in Javas
sudden popularity. The portability in this context means that the code written in the Java
platform can be executed in any combination of hardware and operating system.

Unfortunately, Java has a reputation for being a slower programming language (requiring
more memory) than other languages like C++ but as time went, Java 1.1 was introduced
and program execution times were significantly improved.

Java was built exclusively as an object-oriented programming language, which doesnt
mean much right now, but it will later in the guide. Object-Oriented programming allows

for efficient, organized and powerful code to be created and will be seen throughout this
guide.

What is Java?

Java is a programming language that has multi-platform capability, meaning that you can
program Java for any type of device, whether it is an Android phone, a Windows
computer or an Apple product. Due to the flexibility of Java, it has made it one of the most
popular programming languages used through the globe by many programmers. Java can
be used to create web applications, games, windows applications, database systems,
Android apps and much more.

Java is different from other programming languages because of its simplicity and powerful
nature. That combination makes the Java programming language great to use. Java is a
simple programming language because it doesnt expect too much from the user in terms
of memory management or dealing with a vast and complex hive of intricate classes
extending from each other. Although this doesnt make much sense right now, it will make
sense when reaching the point of learning inheritance in Java.

A Java program is run through a Java Virtual Machine (JVM) and is essentially a software
implementation of an Operating System which is used as a way to execute Java programs.
The compiler (process of converting code into readable instructions for the computer)
analyzes the Java code and converts it in to byte code, allowing the computer to
understand the instructions issued by the programmer and execute them accordingly.

When downloading and installing Java, the distribution of the platform comes in two
ways; the Java Runtime Environment (JRE) and the Java Development Kit (JDK). The
JRE is essentially the Java Virtual Machine (JVM) where the Java programs will run on.
JDK on the other hand is a fully featured Software Development kit for Java which
includes the JRE, compilers, tools, etc.

A casual user wanting to run Java programs on their machine would only need to install
JRE as it contains the JVM which allows Java programs to be executed as explained
before. On the other hand, a Java programmer must download JDK in order to actually
program Java programs.

Chapter 2
Installation of Java

In order to install Java on to a machine, you must download the following:

1. IDE for Java Developers

2. Java JDK

The download of these two tools will put you on your way to becoming a Java
programmer. An IDE (integrated development environment) is a packaged application
program used by programmers because it contains necessary tools in order to process and
execute code. An IDE contains a code editor, a compiler, a debugger, and a graphical user
interface (GUI). There are many different type of IDEs but the most commonly used ones
are:

1. Netbeans

2. Eclipse

In this guide, it would be recommended to use Eclipse because of its simplistic nature. In
order to download Eclipse, please use the following link:

https://eclipse.org/downloads/

Once you have reached this link, you will have to find this:

Then, select either the Windows 32 Bit OS or Windows 64 depending on the type of OS /
processor you have.

Once the IDE has been installed, well move on to downloading and installing the JDK
which will allow us to interact with a coding editor in order to execute and create Java
code.

To download the JDK, go to the following link:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Upon entering this link, find this figure:


Once youve installed the JDK, you are able to launch Eclipse accordingly.

The folder that was extracted from the Eclipse download will contain an eclipse.exe that
can be launched. Once this has been launched, you will be met with the following figure:


All this prompt is asking for is where to set up the output directory for where all the code
written by you is going to be saved. Once this has been selected accordingly, click OK
to continue.

You should now be on this screen (or something similar):


Instructions:

1. Click File

2. Click New Java Project


3. Type in a project name in the Project name: field

4. Click Finish

5. Now right click src New Class


6. Fill in the name field to anything with *letters* and no special characters.
Example: ThisIsAClass

7. Click Finish

8. You will now be presented with a screen that says:

public class ThisIsAClass {

}

You have successfully completed the installation of Java!

Check Out My Other Books



Are you ready to exceed your limits? Then pick a book from the one below and start
learning yet another new craft. I cant imagine anything more fun, fulfilling, and exciting!

If youd like to see the entire list of programming guides (there are a ton more!), go to:

>>http://www.amazon.com/Eprogramy/e/B00Y9CTNTO <<

About the Author



Eprogramy Academy was created by a group of
professionals from various areas of IT with a single
purpose: To provide knowledge in the 3.0 era.

Education is changing as well as social needs. Today, in the
era of information, education should provide the tools to
create and to solve problems in a 3.0 world.

At Eprogramy we understand this and work to give people appropriate responses in this
context.

Keeping this objective in mind, we offer a wide variety of courses to teach the basics of
many programming languages. We believe that anyone can learn a programming language
and apply the lessons in order to solve problems. In our academy we provide the essential
tools to allow everyone to incorporate into the daily life a set of solutions obtained through
programming.

Possibilities and solutions are endless.

In short, at Eprogramy we are committed to help everybody to decodify the messages of
the future.

You might also like