Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
306 views

CSC209 PHP-MySQL LECTURE NOTE PDF

This document provides an introduction and overview of PHP and how to set up a PHP development environment on a local computer. It discusses that PHP is a server-side scripting language used for web development. It then describes how to install and configure WAMP/XAMPP on Windows to allow testing PHP projects locally before deployment. This includes downloading, installing, and configuring the web server, database, and PHP parser components as well as optional steps like configuring phpMyAdmin.

Uploaded by

sadiqaminu931
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
306 views

CSC209 PHP-MySQL LECTURE NOTE PDF

This document provides an introduction and overview of PHP and how to set up a PHP development environment on a local computer. It discusses that PHP is a server-side scripting language used for web development. It then describes how to install and configure WAMP/XAMPP on Windows to allow testing PHP projects locally before deployment. This includes downloading, installing, and configuring the web server, database, and PHP parser components as well as optional steps like configuring phpMyAdmin.

Uploaded by

sadiqaminu931
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Department of Computer Science, FUGUS

FEDERAL UNIVERSITY GUSAU, ZAMFARA


FACULTY OF SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
FIRST SEMESTER 2019/2020 ACADEMIC SESSION

COURSE CODE: CSC 209

COURSE TITLE: INTRODUCTION TO WEB PROGRAMMING (PHP)

LECTURE NOTE

1 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

INTRODUCTION

PHP (recursive acronym for "PHP: Hypertext Preprocessor"—formerly the acronym for
"Personal Home Page") is a server-side scripting language designed for use in web based
applications, Static websites or Dynamic websites. As it is a server side scripting language, its
use requires a web server installed, configured and enabled with PHP.

PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.

 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

 PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.

 It is integrated with a number of popular databases, including MySQL, PostgreSQL,


Oracle, Sybase, Informix, and Microsoft SQL Server.

 PHP is pleasingly zippy in its execution, especially when compiled as an Apache module
on the Unix side. The MySQL server, once started, executes even very complex queries
with huge result sets in record-setting time.

 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. PHP4
added support for Java and distributed object architectures (COM and CORBA), making
entire development a possibility for the first time.

 PHP is forgiving: PHP language tries to be as forgiving as possible.

 PHP Syntax is C-Like.

Common uses of PHP

 PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.

 PHP can handle forms, i.e. gather data from files, save data to a file, through email you
can send data, return data to the user.

2 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

 You add, delete and modify elements within your database through PHP.

 Access cookies variables and set cookies.

 Using PHP, you can restrict users to access some pages of your website.

 It can encrypt data.

Characteristics of PHP

Five important characteristics make PHP's practical nature possible −

 Simplicity

 Efficiency

 Security

 Flexibility

 Familiarity

Setting up Our PHP Environment

In order to start working with PHP on your local computer, you need to install a development
environment. Why is this so? Because PHP is a server-side language; so in essence, you need to
install a “local server” on your computer in order to run PHP code. There are many solutions that
provide PHP packages, but the most common form is known as a LAMP bundle. There are many
LAMP bundles out there that fit different operating systems. The most common are: XAMPP –
an Apache distribution wit h PHP, My SQL and Perl. Support available for Windows, Linux and

Mac;

 XAMPP – an Apache distribution with PHP, MySQL and Perl. Support available for
Windows, Linux and Mac;
 WAMP – specific for Windows;
 MAMP – specific for Mac;
 LAMP - specific for Linux.
3 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

We have to Pick one out of the above software and install, all the software mentioned above are
free open source software’s that one can just download from Google and follow the down load
link and instructions and you’ll be all set to go.

We will also need some form of text editor. There are many free and paid programs you can find.
The one we are using for this course is called Notepad++.

Before we proceed it is important to make sure that we have proper environment setup on our
machine to develop our web programs using PHP.

Note: once more, In order to develop and run PHP Web pages three vital components need to be
installed on your computer system.

 Web Server − PHP will work with virtually all Web Server software, including
Microsoft's Internet Information Server (IIS) but then most often used is freely available
Apache Server.

 Database − PHP will work with virtually all database software, including Oracle and
Sybase but most commonly used is freely available MySQL database.

 PHP Parser − In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser.

Configuring a WAMP Server on Your Computer

There are times when we are so anxious to jump into creating something new that we forget to
cover the basics. For web developers it is important, actually vital, to have the ability to test your
projects locally before they go live.

Those who prefer Windows can still replicate how their code will work by using WAMP to
replicate a live web environment right on their own computer with the only difference being
substituting the Linux operating system in the stack for Windows.

Professional developers always prefer to test their projects locally before they make them live.
And if you also wish to test your site locally before you actually make it live for the users, then
4 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

install WAMP/XAMP on your Windows computer and begin the testing now. In this lecture, I
will show you how to install WAMP/XAMP on Windows machine effortlessly.

First off, for all the beginners it is essential to understand the purpose of using WAMP and the
significance of WAMP. Basically, WAMP stands for Windows (operating system), Apache (web
server), MySQL (database), and PHP programming language. It is a popular alternative of
XAMPP for Windows. While XAMPP also stands for Cross-Platform (X), Apache (A), MySQL
DB (M), PHP (P) and Perl (P). However, you can use XAMPP as well and it doesn’t take much
time to install XAMPP either. But developers may prefer to use WAMP since it is specifically
crafted for Windows only. Unlike, XAMPP, which can be used for Linux and Mac OS as well.
However, both the platforms are equally stable and provide the same functionality.

So you can choose any platform amongst the two to fulfil the objective. Below is the guidance on
how to install WAMP/XAMPP on Windows system. So let’s get started.

Obtain a copy of WAMP

Before you do anything you need to download WAMP/XAMPP from


www.wampserver.com/en/download.php. or www.xamppserver.com/en/download.php.
You will have the option to choose wither a 32 or 64-bit environment depending upon your
computer’s configuration. In addition to Apache, PHP and MySQL this download includes
phpMyAdmin and SQLBuddy to better help you manage your databases through web based GUI
rather than having to use a terminal interface.

Install the software

Once you have downloaded and uncompressed your WAMP/XAMPP executable you will need
to go ahead and launch it to start the installation process.

5 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

When you click next you will be asked to accept the license agreement. Since it is a GPL license
you are free to do just about anything with it so you can go ahead and accept.

The next step requires you to select the folder where you would like to install your WAMP
server. The default will be c:\wamp however you can change this to install the server into any
directory or partition you choose.

Chose where to install the software

After you choose your directory you will have the option to setup icons. Once you decide on this
click Next and then confirm the installation settings again by clicking Install.

6 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Once the installation runs its course you will be asked to choose your default browser. Internet
Explorer is the default choice but you can navigate your way to any other browser of your
choosing.

NOTE: – if your Windows firewall pops up at this point make sure to grant Apache access.

The next decision you will have to make is to set the PHP mail parameters. Many people leave
this set to the defaults when setting up a testing server on their local computer. If you wish to
configure it to connect to your SMTP server you may do so here but unless you plan on testing
email capabilities the default entries can be left and all you need to do is click Next.

Setting the SMTP server (optional). Congratulations, WAMP is now installed on your local
computer.

Now we want to test to see if everything was installed correctly. In the WAMP management
console, click on Localhost. If you see the following screen below pop up in your browser then
everything is working!

If WAMP is not started go ahead and click Start All Services. If you are not sure whether or not
WAMP is running, look for the small green W icon in your toolbar. If it is red, WAMP services
are stopped; green means everything is running while orange means some services are running.

7 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Congratulations, XAMPP is now installed on your local computer and running by seeing the
below screen.

Configuring phpMyAdmin

The last step is to set a password for phpMyAdmin. Many people forgo this step because the
server is not going to be live so they don’t see the need to protect the database if it is only sample
data. You can decide what practice to follow.

In order to change the password you will need to navigate to your phpMyAdmin file, located at
C:/wamp/apps/phpmyadmin3.x.x and open the config.inc.php file for editing.

Once opened, navigate to the lines that read,

$cfg['Servers'][$i]['user'] = 'root';

8 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

$cfg['Servers'][$i]['password'] = 'xxxxx';

$cfg['Servers'][$i]['AllowNoPassword'] = true;

Where the example reads xxxxx insert your password. Under AllowNoPassword, change the
value to false.

1. To check that the PHP engine has been installed successfully and PHP processing has
been enabled in the Apache configuration:

Open Notepad++ or another text editor. Create a file and type the following text:

<!DOCTYPE html>
<html>
<body>
<?php
echo'PHP has been installed successfully!';
?>
</body>
</html>

Save the file in the htdocs folder as test.php. The default path for my system is
C:\xampp\htdocs\test.php

Run the browser and enter the following URL: http://localhost:<port>/test.php. The following
page opens:

9 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

PHP Codes Style

Source code development usually involves balancing requirements, some of which are often in
conflict. For example, from a computer's perspective, the best source code requires the least
interpretation at run time to achieve maximum efficiency. From a network's perspective, the best
source code has the least total number of bytes transmitted to achieve maximum efficiency. For
someone doing maintenance, source code that is neatly formatted, well commented, and blocked
into logical groups of statements will require the least effort to do their job, and is therefore most
efficient. For the original programmer, writing code in a creative streak, using only enough
structure to keep the code organized in their mind will seem to be the most efficient pattern -
until it's time to debug the code, and to insure all of the requirements are met. When that mindset
change occurs, the original programmer suddenly finds their needs to be quite similar to those of
the maintainer, and stopping to fix the code structure and add documentation makes sense.

For compiled languages such as C and C++, the conflict between the formatted source and least
interpretation requirements is resolved by the compiler, but that adds at least one more step to the
development process, and makes the code able to run on only one type of platform. Languages
that use a just-in-time (JIT) "compiler" such as PHP, Python and Java or C# doesn’t require
additional steps in development, but the "compiler" must run each time the code is used,
generally producing "bytecodes" that are then interpreted by a virtual machine. This reduces
portability issues but increases the processing requirements. If a bytecode cache is used, the JIT
compiler only has to be run when a source code change is detected, but the bytecode interpreter
is still less efficient than running native code directly on the underlying hardware. In most cases,
the difference is negligible, and the increased portability is used to justify the loss of efficiency.
The Style Guide

Comments

Want to leave messages for your future self or other members of your team? Then comments
save you the trouble of having to remember your train of thought and make for an excellent way
to document what your thoughts were at the time. They can also be used to exclude certain
pieces of code all together.

10 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

// This is a single line comment

# This is another single line comment

/*

This is a comment block. Everything in here will be ignored and can span multiple lines.

*/

For example, let look at the below php code and see the comment made:

<?php

//whether ip is from share internet

if (!empty($_SERVER['HTTP_CLIENT_IP']))

$ip_address = $_SERVER['HTTP_CLIENT_IP'];

//whether ip is from proxy

elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))

$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];

//whether ip is from remote address

else

11 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Semicolons End Statements

PHP generally uses semicolons “;” to mark the end of a statement. However, if the PHP closing
tag is on the same line after a statement, the semicolon is optional and should not be used.

A code block, enclosed in braces “{}” is not a statement, it is a group of statements. Each
statement within the code block must be terminated with a semicolon, but the code block itself is
NOT terminated with a semicolon.

The example above also shows how a code block enclosed in braces “{}”.

$ip_address = $_SERVER['REMOTE_ADDR'];

echo $ip_address;

?>

No PHP Closing Tag At EOF

The closing “?>” tag at the end of a PHP file is optional to the PHP parser and is not required.
However, if used, any whitespace following the closing tag, whether introduced by the
developer, user, or an FTP application, will be immediately written to the output. This will
prevent any more headers from being sent to the browser, can cause PHP errors.

Line Lengths

Source code statements should always be limited to 80 characters per line, taking into account
expansion of tabs to four character spaces. While wide desktop display screens and horizontally
scrolling editors make it possible to create and view longer lines in an original development
environment, the longer lines are more difficult to comprehend, and will cause wrapping issues
on less capable displays. (The first time you open a file with long lines in a terminal window on
your smart phone you'll understand the problem.) In addition, when attempting to do side-by-side

12 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

comparisons of different versions of the same file, the longer lines will either cause wrapping or
scrolling issues in the comparison utility.

If necessary, an empty PHP segment can be inserted to wrap a long line of HTML code and keep
it within the 80 character line length.

<?php
// For example: ?>
<a href="http://www.example.com/n/deeply/nested/page.php" rel="external" <?php
?>class="anchor-class-name">The Anchor Text</a>

There will be times when limiting lines to 80 characters will be impossible, when there isn't a
mechanism available for folding long lines. Such cases are generally rare, so following the 80
character limit usually should not be an issue.

One Statement per Line

Do not combine statements on one line. Doing so reduces the line count (volume) but increases
the line density, and more dense lines are harder to comprehend. In addition, the fact that
multiple statements are combined on one line may be overlooked when quickly reading code
during maintenance, resulting in confusion at best, and quite probably, leading to insertion of
additional errors.

<?php
// INCORRECT:
$foo='this'; $bar='that'; $bat=str_replace($foo,$bar,$bag);

// CORRECT:
$foo='this';
$bar='that';
$bat=str_replace($foo,$bar,$bag);

There are a few cases where this rule may be broken to improve readability of the code. The
permitted exceptions are:

13 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

 A single statement may be included on the same line with one of the PHP control
structure statements - if, else, for, foreach, do while or while - as long as line length limits
are maintained.

 Nested assignments where the value being assigned is immediately used in another
assignment or computation. This type of construct has been known to improve processing
speed by avoiding swapping variables out of the processor's registers. Don't nest the
assignments too heavily, though, or the increased line density will have an adverse effect
on readability.

 Simple case assignments within a switch block where the case, assignment and break can
all fit within the line length limits:

<?php
switch ($_REQUEST['tag'])
{ default: $string=FALSE; break;
case 1: $string='first choice'; break;
case 2: $string='another possible choice'; break;
case 3: $string='maybe something else'; break;
case 4: $string='yet another idea'; break;
}

Whitespace

The PHP parser ignores whitespace outside of quoted strings. Whitespace is solely used for the
convenience and comprehension of human readers.

No whitespace can precede a file's opening PHP tag or follow a closing PHP tag: extraneous
whitespace at the boundaries of your files can cause output to begin before it is supposed to,
leading to errors and, potentially, blank pages.

Whitespace is required after the PHP start tag - a single space, one or more tab characters, or a
newline. For single line statements or control structures where an opening brace starts the next
line, the start tag and statement can be on the same line - use a space as the separator if the

14 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

current indentation level is less than two tabstops from the left margin, otherwise use the correct
number of tabs to indent the statement for the current indentation level.

A single space should be used between the PHP code and the close tag unless the close tag is at
the start of a new line where there should be no leading space.

In general, parenthesis and brackets should not use any additional spaces. The exception is a
space must always follow PHP control structure keywords that take arguments with parenthesis
(declare, do-while, while, if-else, switch, for, foreach), to help distinguish them from function
calls and increase readability. Function names should not have any whitespace between them and
the parentheses enclosing their argument list. When referring to array items, never use spaces
around the index.

<?php
// INCORRECT:
foreach( $query->result() as $row )
// CORRECT:
foreach ($query->result() as $row) // single space after PHP keyword, not within parenthesis

// INCORRECT:
function Foo ( $bar )
{
}
// CORRECT:
function Foo($bar) // no spaces around parenthesis in function declarations
{
}

// INCORRECT:
$arr[ $foo ] = 'foo';
// CORRECT:
$arr[$foo]='foo'; // no spaces around array keys

15 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Remove trailing spaces

Remove trailing spaces at the end of each line of code. Extraneous whitespace at the end of a line
serves no useful purpose, may cause errors, and increases network overhead. Your text editor
should have an option to assist in meeting this requirement.

Alignment of assignments

To support readability, the equal signs may be aligned in block-related assignments:

<?php
$short =foo($bar);
$longername=foo($baz);

The rule should be broken when the length of the variable name is at least eight characters longer
or shorter than the surrounding ones:

<?php
$short=foo($bar);
$thisVariableNameIsVeeeeeeeeeeryLong=foo($baz);

When PHP emits whitespace

One thing that needs to be understood to have PHP generate readable HTML code is when PHP
sends whitespace to the browser.

Any whitespace to the left of a PHP opening tag will be emitted - once. This means that if you
indent an opening tag for an include statement, the first line, and only the first line, of any
HTML or text in the included file will be indented by the whitespace to the left of the opening
tag: PHP does not interpret indenting an include statement to mean "indent each line in the file
by the amount the include statement was indented by."

Indentation

The PHP parser doesn't care about indentation, it is solely used for the convenience and
comprehension of human readers. Consequently, indentation should be used to enhance

16 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

readability of the source code. Three simple rules that stir the rest of the indentation patterns to
be used:

1. don't indent unnecessarily

2. indent on purpose

3. indent consistently

Your indentation should always reflect the logical structure of the code.

At the start of a code module, the code is at the [local] root level - so start all code lines in
column 1 (the leftmost column of the page). Each time a new nesting level is entered, whether
braces or parentheses are present or not, indent one tab, and use that level of indentation until the
nesting level changes - whether indenting another tab to enter another nesting level, or
outdenting when leaving the current nesting level.

Most people find that 4-space tabstops provide the best balance between making indentation
visible and using screen space. By using tabs, rather than spaces, for indentation, that preference
can be adjusted without reformatting the code: If you think four spaces is too much for each
indentation level, set your editor to use two or three space tabstops and the tab width will adjust
to suit your view. On the other hand, if you want more indentation, you can use eight space
tabstops with the same file. Just be sure that when you save the file that you are using TAB
characters, not SPACES, for the indentation written to permanent storage.

Within switch statements, the switch statement is the parent indentation level, the case
statements (including the default statement, if present) are the next indentation level, and the
action statements within each case, including the break statement, are at the next indentation
level. Thus, the correct indentation structure for a switch block is:

<?php
switch (condition)
{
case 1:
action1;

17 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

break;

case 2:
action2;
break;

default:
defaultaction;
break;
}

Use real tabs and not spaces, allowing the most flexibility across editors and operating systems.
An acceptable exception is if you have a block of code that would be more readable if things are
aligned, use spaces:

<?php
[tab]$foo ='somevalue';
[tab]$foo2 ='somevalue2';
[tab]$foo34='somevalue3';
[tab]$foo5 ='somevalue4';

For associative arrays, values should start on a new line. Note the comma after the last array
item: This is recommended because it makes it easier to change the order of the array. (Unlike
Javascript running in InternetExploiter, PHP ignores a trailing comma in an array declaration.)

<?php
$my_array=array
([tab]'foo' =>'somevalue',
[tab]'foo2' =>'somevalue2',
[tab]'foo3' =>'somevalue3',
[tab]'foo34'=>'somevalue3',
);

18 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

The rule of thumb here is that tabs should be used for indentation at the beginning of the line and
spaces for alignment within the line.

When concatenating strings in an assignment, long lines should be broken at clauses to improve
readability or if the line length limit would be exceeded. In these cases, each successive line
should be padded with white space so the "." operator is aligned under the "=" operator:

<?php
$sql='SELECT id,name FROM people '
."WHERE name='Susan' "
.'ORDER BY name ASC';

Exceptions: try and catch

The exception handling try and catch mark control structure blocks, just as if and else do. They
are indented to the same level as the surrounding code, with try and catch aligned with each
other, and with the braces surrounding their code blocks:

<?php
try
{
// code that might fail
}
catch (FirstExceptionType $e)
{
// first catch body
}
catch (OtherExceptionType $e)
{
// other catch body
}

19 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Interspersed PHP and HTML

When HTML and PHP are interspersed, ALWAYS put PHP start tags (“<?php”) at the left
margin unless one of these specific conditions exists:

1. The PHP code will be emitting [HTML] which should be indented. In this case, include a
comment within the PHP to indicate the indentation is intentional:

<?php
<p><strong>Area</strong><br />
<?php /* intentional indent */ echo $person['AREANAME'] ?></p>

2. The PHP code is emitting output inline

<?php
<a href="<?php echo $theLink ?>"><?php echo $theAnchorText ?></a>

When HTML and PHP are interspersed, indent the PHP statements at the indentation level that
would be in force if there were no HTML tags: The HTML and PHP codes should be considered
as maintaining separate indentation levels.

Parentheses

As a general rule, only use parentheses where they are required. Additional parentheses may be
used to clarify groupings in complex conditional constructs, but knowing operator precedence
should eliminate their necessity.

Do not use parentheses when using language constructs such as echo, print, include, or require.
These are not functions and don't require parentheses around their parameters.

When calling class constructors with no arguments, always include parentheses: The constructors
are functions, so constructor calls need to look like function calls.

Differences and Similarities between PHP and JAVA

20 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

A comparison between PHP and Java is needed because many have doubts in which language to
use for software development. PHP and Java being one of the most popular programming
languages for web development, a comparison is definitely required between the two.

PHP has become the most prevalent server side scripts on the web. PHP is a general purpose
scripting language at the server side while Java is general-purpose and compiled programming
language. While designing Java, developers had only one thing in mind i.e. they wanted to
design a language using which one can write the code once and run the code anywhere. Both the
languages create powerful dynamic web applications and sites using their own set of strengths
and nuances.

It is vital for you to choose the correct language for your project before starting the project
because after you have started off, it is an arduous task to transition from the language you have
chosen until you perform a major overhaul down the line. Therefore, if you choose the language
that is right for your project initially you will be able to build a successful site that is scalable and
fulfils your requirement from the website. So in brief we will review what PHP is all about and
compare it with Java

What is PHP?

PHP is one of the most popular server-side scripting languages on the web as said earlier. PHP
is considered as the most versatile language that is gaining popularity now. PHP is finding its
prominent utility in the field of web development. It is a developing scripting language and is a
robust tool for developing dynamic and interactive web pages. The PHP programming language
was designed for retrieving and updating information from the database. The basic function of
PHP is to develop applications that are executed on the server side and to generate dynamic web
pages.

What is Java?

When initially released in 1991 by Sun Microsystems, Java was used for programming consumer
electronics such as VCR’s. Java was basically designed to build standalone applications as a
general purpose programming language. Java was originally developed as a platform
independent language. Java was designed to gain flexibility and making it possible for the

21 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

developers to run it on any machine; regardless of platform or architecture. Java is a high-level


language.

When a Java code is compiled it converts into intermediate binary language for the particular
operating system on which your software is running, that is why Java is said to be a compiled
language. The intermediate binary code is the bytecode that can on implementations of the Java
Virtual Machine (JVM). Any system can run Java if it has Java Virtual Machine (JVM) installed
on it.

Java is also primarily a server side language for web development and most widely chosen for
the mobile app development on Android platforms.

Similarities between PHP and Java

Some similarities between PHP and Java are as follows:

1. Object-Oriented Programming (OOP).

Both PHP and Java have some features of Object Oriented Programming (OOP). They do have a
few similar features of Object Oriented Programming that are encapsulation, polymorphism
and inheritance. The primary advantage of using Object Oriented languages is that your
program contains separate modules for each function that can be used separately for other
programs too.

2. Back-End Development.

Both PHP and Java are executed on the server-side. Both are also used for the back end
technologies.

3. Syntax.

The syntax of PHP and Java has many similarities such as classes, declaring and initializing of
variables, looping structures and conditional operators are very similar in both languages. In
short they both have C-like syntax (curly braces and semicolons).

4. Entry points.

22 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Entry points in both PHP and Java are also similar i.e. when your program starts to execute the
compiler or interpreter searches for the point where it needs to start the execution from.

The similarities between PHP and Java still continue

 They both work with a ‘runtime engine’ (although Java’s engine is strictly typed, and
PHP does not compile to files)

 They both have C-like syntax (curly braces and semicolons)

 They are both used on the web (although Java less and less)

 They are both Object Oriented languages (although Java is strict about it, and PHP is very
flexible)

 They are both procedural languages (although both implement a hint of functional
programming)

 They are both the same age (they both started their lives around 1990’s)

Differences between PHP and Java

Even though PHP and Java have many similarities they do have some major differences which
are listed below:

1. Interpreted and Compiled.

PHP is an interpreted programming language while Java is a compiled programming


language.PHP is considered to be an interpreted language, or “script”—the one in which
instructions are executed directly without initially compiling the code into machine language
instructions.

In scripts, the code can run as it is, in their respective runtime environments (i.e. the server).
There is always a debate on which language to use, compiled or interpreted, it is believed that
scripts offer good programmer productivity and are easy to use. Regardless of the origin i.e.
where it was initially written, a java code can run anywhere i.e. on any operating system, this is
possible because it is a compiled programming language. Java works on different
23 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

implementations. It is first compiled into the bytecode and then runs on the Java Virtual
Machine.

2. Memory safe.

Java is designed in a manner that makes it a memory-safe language. This means that the
developer will receive an error if he tries assigning values to variables outside the given array
parameters.

3. Dynamic and Static Type Checking.

PHP uses Dynamic Type Checking while Java uses Static Type Checking. In Dynamic Type
Checking that is used by PHP, the type information is required at the run time. Dynamic Type
Checking offers better programmer productivity i.e. the programmer can assign the types
according to his comfort, hence, the major advantage of using Dynamic Type Checking. While
in the Static Type Checking which is used by Java, the type of a variable is checked at compile-
time. The developer needs to specify the type (i.e. integer, double, string, etc.) of any variable
they create. The major benefit of using Static Type Checking is that type errors are caught by the
compiler earlier during the process of development because the compiler knows exactly the types
of data that are being used in the program and the execution of the code is faster and uses and
uses less memory.

4. Concurrency.

The programming language being used should have the capability of handling the execution of
multiple instruction sequences at the same time. PHP just as majority of server side languages,
uses multi-threaded, it blocks I/O for performing multiple tasks in parallel. While Java uses
multiple threads to carry out tasks in parallel. In majority of the cases both the methods works
fine, but thread to thread sharing is much faster when compared to inter process communication,
thus making Java to be faster when compared to PHP.

5. Prototype Based and Class Based.

PHP is Prototype Based while Java is Class Based. PHP uses Prototype based programming in
which the existing objects are reused using the process of cloning that serve as prototypes. While

24 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Java follows Class Based Inheritance in which the properties are defined inside a class which is
later inherited by the instance of that particular class. It is a typical top down, hierarchical, class-
based relationship.

Both Java and PHP have proved to be excellent foundations for a wide variety of software
projects. Your choice of the language would depend on the requirements of your software
project. Therefore, a much needed comparison between PHP and Java will be given to you all as
addition note.

PHP PROGRAMMING

PHP is not the language to jump straight into if you have had no experience at all. Getting a
grasp of the basic programming concepts might be easier in a language such as Visual Basic as
the syntax and concepts in PHP might be quite confusing for a beginner. If you have no
experience in scripting, I might also suggest taking a look at JavaScript which is a client-side
scripting language, making it limited when compared to PHP. But don’t let that scare you, PHP
teaches some great coding habits and if you are capable of picking things up quickly then you
should be just fine. Let’s take a little look at the syntax first, here’s how you would tell PHP to
output the text “Welcome to my website” to a browser:

<?php

echo 'Welcome to my website';

?>

It all looks pretty logical, right? You are echoing out the sentence enclosed in the quotation
marks to the web browser. And each statement in PHP must end with a “;” to notify the
processor module that we have ended our statement. New lines and blank space are not
recognised. You must also wrap PHP code inside “<?php” and “?>” tags to notify the server
when a PHP script will start and end.

Let us try another example:

E.g : To write a PHP script to sort the following associative array

25 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

array("Fatima"=>"31","Jumai"=>"41","Wakkala"=>"39","Rashida"=>"40") in

a) ascending order sort by value

b) ascending order sort by Key

c) descending order sorting by Value

d) descending order sorting by Key

<?php

echo "

Associative array : Ascending order sort by value

";

$array2=array("Fatima"=>"31","Jamiu"=>"41","Wakkala"=>"39","Rashida"=>"40");
asort($array2);

foreach($array2 as $y=>$y_value)

echo "Age of ".$y." is : ".$y_value."

";

echo "

Associative array : Ascending order sort by Key

";

$array3=array("Fatima"=>"31","Jamiu"=>"41","Wakkala"=>"39","Rashida"=>"40");
ksort($array3);

26 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

foreach($array3 as $y=>$y_value)

echo "Age of ".$y." is : ".$y_value."

";

echo "

Associative array: Descending order sorting by Value

";

$age=array("Fatimaa"=>"31","Jamiu"=>"41","Wakkala"=>"39","Rashida"=>"40");

arsort($age);

foreach($age as $y=>$y_value)

echo "Age of ".$y." is : ".$y_value."

";

echo "

Associative array : Descending order sorting by Key

";

$array4=array("Fatimaa"=>"31","Jamiu"=>"41","Wakkala"=>"39","Rashida"=>"40");
krsort($array4);

foreach($array4 as $y=>$y_value)

27 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

echo "Age of ".$y." is : ".$y_value."

";

?>

Sample Output 2:

Associative array : Ascending order sort by value

Age of Fatima is : 31

Age of Wakkala is : 39

Age of Rashida is : 40

Age of Jamiu is : 41

Associative array : Ascending order sort by Key

Age of Jamiu is : 41

Age of Rashida is : 40

Age of Fatima is : 31

Age of Wakkala is : 39

Associative array : Descending order sorting by Value

Age of Jamiu is : 41

Age of Rashida is : 40

Age of Wakkala is : 39

Age of Fatima is : 31
28 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

Associative array : Descending order sorting by Key

Age of Wakkala is : 39

Age of Fatima is : 31

Age of Rashida is : 40

Age of Jamiu is : 41

E.g3 : To write a PHP script using a for loop to add all the integers between 0 and 30 and display
the sum.

<?php

$sum = 0;

for($x=1; $x<=30; $x++)

$sum +=$x;

echo "The sum of the numbers 0 to 30 is $sum"."\n";

?>

Sample Output3:

The sum of the numbers 0 to 30 is 465

We are going to examine more examples as we advance further. So before we proceed with our
PHP programming we need to get familiar with Data and Information, most precisely what a
DATABASE is all about.

29 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

INTRODUCTION TO DATABASE USING MySQL

MySQL is an open-source Relational Database Management System (RDBMS) that is developed


and supported by Oracle Corporation. It is currently the most popular open source database
server in existence with over ten million installations. MySQL is supported on a large number of
platforms, including Linux variants, mac OS, and Windows. It also has application programming
interfaces (APIs) for a large number of languages, including C, C++, Java, .Net, Perl, PHP,
Python, and Ruby. However, MySQL is very commonly used in conjunction with PHP scripts to
create powerful and dynamic server-side applications.

Developed in the mid-1990s, it’s now technology that powers many of today’s most-visited
Internet destinations. The various versions of MySQL is given below:

Version Release Date

1.0 1995-05-23

3.19 1996-12-01

3.20 1997-01-01

3.21 1998-10-01

3.22 1999-10-01

3.23 2001-01-22

4.0 2003-03-01

4.1 2004-10-01

5.0 2005-10-01

5.1 2008-11-27

5.5 2010-11-01

5.6 2013-02-01

30 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

5.7 2015-10-21

8.0 2018-04-19

What is Database?

A database is a structured collection of records or data stored in a computer system and


organized in such a way that it can be searched quickly and information can be retrieved rapidly.

A database is a structure that comes in two flavors: a flat database and a relational database. A
relational database is much more oriented to the human mind and is often preferred over the
gobbledygook flat database that are just stored on hard drives like a text file. MySQL is a
relational database.

A MySQL database contains one or more tables, each of which contains records or rows. Within
these rows are various columns or fields that contain the data itself. Table 2 shows the contents of
an example database of five publications detailing the author, title, type, and year of publication.

Table 2: Example of a simple database

Author Title Type Year

Mark Twain The Adventures of Tom Sawyer Fiction 1876

Jane Austen Pride and Prejudice Fiction 1811

Charles Darwin The Origin of Species Non-Fiction 1856

Charles Dickens The Old Curiosity Shop Fiction 1841

William Shakespeare Romeo and Juliet Play 1594

Each row in the table is the same as a row in a MySQL table, and each element within a row is
the same as a MySQL field.

Summary of Database Terms


31 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

The main terms you need to acquaint yourself with for now are:

 Database: The overall container for a collection of MySQL data.

 Table: A sub-container within a database that stores the actual data.

 Row: A single record within a table, which may contain several fields.

 Column: The name of a field within a row.

ACCESSING MYSQL VIA THE COMMAND LINE

There are three main ways in which you can interact with MySQL: using a command line, via a
web interface such as phpMyAdmin, and through a programming language like PHP. We’ll look
at them all.

Starting the Command-Line Interface

The following sections describe relevant instructions for Windows Operating System.

Windows users

If you installed the XAMPP server as explained in the beginning of this course, you will be able
to access the MySQL executable from one of the following directories:

C:\Xampp\MySQL\bin

If you installed XAMPP Server in a place other than this, you will need to use that directory
instead. By default, the initial MySQL user will be root and will not have had a password set.

So, to enter MySQL’s command-line interface, select Start→Run and enter CMD into the Run
box, then press Enter/Return key. This will call up a Windows Command prompt. From there,
enter one of the following (making any appropriate changes as just discussed):

"C:\Xampp\MySQL\bin" -u root

This command tells MySQL to log you in as the user root, without a password. You will now be
logged in to MySQL and can start entering commands. To be sure everything is working as it
should be, enter the following—the results should be similar to Figure 1:
32 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

SHOW databases;

Fig. 1: Accessing MySQL from a Windows Command prompt

Using the Command-Line Interface

The semicolon

Let’s start with the basics. The semicolon at the end of SHOW database is used by MySQL to
separate or end commands. If you forget to enter it, MySQL will issue a prompt and wait for you
to do so. The required semicolon was made part of the syntax to let you enter multipleline
commands. It also allows you to issue more than one command at a time by placing a semicolon
after each one.

There are six different prompts that MySQL may present you with, so you will always know
where you are during a multiline input.

MySQL prompt Meaning

mysql> MySQL is ready and waiting for a command

-> Waiting for the next line of a command

'> Waiting for the next line of a string started with a single quote

33 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

"> Waiting for the next line of a string started with a double quote

`> Waiting for the next line of a string started with a backtick

/*> Waiting for the next line of a comment started with /*

Table 3: MySQL’s six command prompts

MySQL Commands

You’ve already seen the SHOW command, which lists tables, databases, and many other items.
The commands you’ll use most often are listed in Table 4.

Command Parameter(s) Meaning

ALTER database, table Alter database or table

BACKUP Table Back up table

/c Cancel input

CREATE database, table Create database or table

DELETE Expression with table and row Delete row from table

DESCRIBE Table Describe the table’s columns

DROP database, table Delete database or table

EXIT(Ctrl-C) user details Exit

GRANT Change user privileges

INSERT Expression with data Insert data

LOCK table(s) Lock table(s)

QUIT (\q) Same as EXIT

34 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

RENAME Table Rename table

SHOW Too many items to list List item’s details

SOURCE Filename Execute commands from filename

STATUS(\s) Display current status

TRUNCATE Table Empty table

UNLOCK table(s) Unlock table(s)

UPDATE Expression with data Update an existing record

USE Database Use database

Table 4: A selection of common MySQL commands

However, you need to remember a couple of points about MySQL commands before you start
using them:

 SQL commands and keywords are case-insensitive. CREATE, create, and CrEaTe all
mean the same thing. However, for the sake of clarity, the recommended style is to use
uppercase.

 Table names are case-insensitive on Windows, but case-sensitive on Linux and mac OS.
So, for portability purposes, you should always choose a case and stick to it. The
recommended style is to use lowercase or mixed upper- and lowercase for table names.

Creating a Database

Start by issuing the following command to create a new database called publications:

CREATE DATABASE publications;

A successful command will return a message that doesn’t mean much yet—“Query OK, 1 row
affected (0.00 sec)”—but will make sense soon. Now that we’ve created the database, we want to
work with it, so issue:

35 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

USE publications;

You should now see the message “Database changed.”

Creating a table

Enter the following commands one line at a time to create now table.

CREATE TABLE classics (

author VARCHAR(128),

title VARCHAR(128),

type VARCHAR(16),

year CHAR(4));0

MySQL should then issue the response “Query OK, 0 rows affected,” along with a note of how
long it took to execute the command. Every parenthesis and comma counts, and typing errors are
easy to make.

Creating and checking a new table

mysql> USE publications;

Database changed

mysql> CREATE TABLE classics (

-> author VARCHAR(128),

-> title VARCHAR(128),

-> type VARCHAR(16),

-> year CHAR(4)) ENGINE MyISAM;

Query OK, 0 rows affected (0.03 sec)

36 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

mysql> DESCRIBE classics;

+--------+--------------+------+-----+---------+-------+ |

| Field | Type | Null | Key | Default | Extra | |

+--------+--------------+------+-----+---------+-------+ |

| author | varchar(128) | YES | | NULL | | |

| title | varchar(128) | YES | | NULL | | |

| type | varchar(16) | YES | | NULL | | |

| year | char(4) | YES | | NULL | | |

+--------+--------------+------+-----+---------+-------+ |

4 rows in set (0.00 sec)

The DESCRIBE command is an invaluable debugging aid when we need to ensure that we have
correctly created a MySQL table. We can also use it to remind ourselves about a table’s field or
column names and the types of data in each one. Let’s look at each of the headings in detail:

Field

The name of each field or column within a table.

Type

The type of data being stored in the field.

Null

Whether the field is allowed to contain a value of NULL.

Key

MySQL supports keys or indexes, which are quick ways to look up and search for data.
The Key heading shows what type of key (if any) has been applied.

Default

37 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

The default value that will be assigned to the field if no value is specified when a new
row is created.

Extra

Additional information, such as whether a field is set to autoincrement.

Data Types

In the Example above, you may have noticed that three of the table’s fields were given the data
type VARCHAR, and one was given the type CHAR. The term VARCHAR stands for VARiable
length CHARacter string and the command takes a numeric value that tells MySQL the
maximum length allowed for a string stored in this field. This data type is very useful, as it
allows MySQL to plan the size of a database and perform lookups and searches more easily. The
downside is that if you ever attempt to assign a string value longer than the length allowed, it
will be truncated to the maximum length declared in the table definition.

Adding Data to a Table

To add data to a table, use the INSERT command. Let’s see this in action by populating the table
classics with the data from Table 1, using one form of the INSERT command repeatedly.

INSERT INTO classics(author, title, type, year)

VALUES('Mark Twain','The Adventures of Tom Sawyer','Fiction','1876');

INSERT INTO classics(author, title, type, year)

VALUES('Jane Austen','Pride and Prejudice','Fiction','1811');

INSERT INTO classics(author, title, type, year)

VALUES('Charles Darwin','The Origin of Species','Non-Fiction','1856');

INSERT INTO classics(author, title, type, year)

VALUES('Charles Dickens','The Old Curiosity Shop','Fiction','1841');

INSERT INTO classics(author, title, type, year)


38 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

VALUES('William Shakespeare','Romeo and Juliet','Play','1594');

Once all lines have been entered, type the following command, which will display the table’s
contents—the result should look like Figure 5:

SELECT * FROM classics;

Fig.5: Result after inserting data into the classics table.

The first part, INSERT INTO classics, tells MySQL where to insert the following data. Then,
within parentheses, the four column names are listed—author, title, type, and year—all separated
by commas. This tells MySQL that these are the fields into which the data is to be inserted.

The second line of each INSERT command contains the keyword VALUES followed by four
strings within parentheses, separated by commas. This supplies MySQL with the four values to
be inserted into the four columns previously specified.

Each item of data will be inserted into the corresponding column, in a one-to-one
correspondence. If you accidentally listed the columns in a different order from the data, the data
would go into the wrong columns. The number of columns must match the number of data items.

39 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Adding a new column

Let’s suppose that you have created a table and populated it with plenty of data, only to discover
you need an additional column. Here’s how to add the new column pages, which will be used to
store the number of pages in a publication:

ALTER TABLE classics ADD pages SMALLINT UNSIGNED;

This adds the new column with the name pages using the UNSIGNED SMALLINT data type,
sufficient to hold a value of up to 65,535.

If you now ask MySQL to describe the updated table using the DESCRIBE command, as
follows, you will see the change has been made (see Figure 6):

DESCRIBE classics;

Fig. 6: Result of Alter command

Removing a column

You may also decide, upon reflection, that the page count column pages isn’t actually all that
useful for this particular database, so here’s how to remove that column using the DROP
keyword:

40 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

ALTER TABLE classics DROP pages;

Deleting a Table

Deleting a table is very easy indeed. But, because we don’t want to reenter all the data for the
classics table, we won’t delete that one. Instead, let’s quickly create a new table, verify its
existence, and then delete it by typing in the commands below. The result of these four
commands should look like Figure 7.

CREATE TABLE disposable(trash INT);

DESCRIBE disposable;

DROP TABLE disposable;

SHOW tables;

Fig. 7: Deleting a table

Indexes

As things stand, the table classics works, and MySQL won’t have any problem searching it—
until it grows to more than a couple of hundred rows, that is. At that point, database accesses will
get slower and slower with every new row added, because

41 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

MySQL has to search through every row whenever a query is issued. This is like searching
through every book in a library whenever you need to look something up.

Of course, you don’t have to search libraries that way, because they have either a card index
system or, most likely, a database of their own.

And the same goes for MySQL—at the expense of a slight overhead in memory and disk space,
you can create a “card index” for a table that MySQL will use to conduct lightning-fast searches.

Creating an Index

The way to achieve fast searches is to add an index, either when creating a table or at any time
afterwards. There are different index types, such as a regular INDEX, PRIMARY KEY, and
FULLTEXT. One must decide which columns require an index, a judgment that requires you to
predict whether he will be searching any of the data in those columns. However, indexes can get
complicated, because you can combine multiple columns in one index. And even when you’ve
gotten to grips with all of that, you still have the option of reducing index size by limiting the
amount of each column to be indexed.

Let’s add an index to each of the columns we’ve created in the classics table, using the following
commands:

ALTER TABLE classics ADD INDEX(author(20));

ALTER TABLE classics ADD INDEX(title(20));

ALTER TABLE classics ADD INDEX(category(4));

ALTER TABLE classics ADD INDEX(year);

DESCRIBE classics;

The first two commands create indexes on both the author and title columns, limiting each index
to only the first 20 characters. For instance, when MySQL indexes the following title:

The Adventures of Tom Sawyer

It will actually store in the index only the first 20 characters:


42 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

The Adventures of To

This is done to minimize the size of the index, and to optimize database access speed.

The results of issuing these commands (and a DESCRIBE command to confirm that they
worked) can be seen in Figure 8, which shows the key MUL for each column. This key means
that multiple occurrences of a value may occur within that column, which is exactly what we
want, as authors may appear many times, the same book title could be used by multiple authors,
and so on.

Fig. 8: Result of adding indexes to the fields

Adding indexes when creating tables

You don’t have to wait until after creating a table to add indexes. In fact, doing so can be time-
consuming, as adding an index to a large table can take a very long time. Therefore, let’s look at
a command that creates the table classics with indexes already in place.

CREATE TABLE classics (

author VARCHAR(128),

title VARCHAR(128),

43 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

category VARCHAR(16),

year SMALLINT,

INDEX(author(20)),

INDEX(title(20)),

INDEX(category(4)),

INDEX(year));

Primary keys

So far we’ve created the table classics and ensured that MySQL can search it quickly by adding
indexes, but there’s still something missing. All the publications in the table can be searched, but
there is no single unique key for each publication to enable instant accessing of a row.

So, let’s go ahead and create a new column for this key. Now, bearing in mind that ISBN
numbers are 13 characters long,

ALTER TABLE classics ADD isbn CHAR(13) PRIMARY KEY;

In a nutshell, the following commands create indexes within classics table together with primary
key:

CREATE TABLE classics (

author VARCHAR(128),

title VARCHAR(128),

category VARCHAR(16),

year SMALLINT,

isbn CHAR(13),

INDEX(author(20)),

44 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

INDEX(title(20)),

INDEX(category(4)),

INDEX(year),

PRIMARY KEY (isbn));

Querying a MySQL Database

So far we’ve created a MySQL database and tables, populated them with data and added indexes
to make them fast to search. Now it’s time to look at how these searches are performed, and the
various commands and qualifiers available.

SELECT

As you saw before, the SELECT command is used to extract data from a table. In that section,
we used its simplest form to select all the data and display it.

The basic syntax is:

SELECT something FROM tablename;

The something can be an * (asterisk), as you saw before, to indicate “every column,” or you can
choose to select only certain columns.

SELECT author,title FROM classics;

SELECT title,isbn FROM classics;

45 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Fig. 9: Effect of SELECT command

SELECT COUNT

Another option for the something parameter is COUNT, which can be used in many ways. In the
command below, it displays the number of rows in the table by passing * as a parameter, which
means “all rows.” As you’d expect, the result returned is 5, as there are five publications in the
table.

SELECT COUNT(*) FROM classics;

46 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Fig.10: SELECT COUNT effect

SELECT DISTINCT

This qualifier (and its synonym DISTINCTROW) allows you to weed out multiple entries when
they contain the same data. For instance, suppose that you want a list of all authors in the table. If
you select just the author column from a table containing multiple books by the same author,
you’ll normally see a long list with the same author names over and over. But by adding the
DISTINCT keyword, you can show each author just once. Let’s test that out by adding another
row that repeats one of our existing authors

INSERT INTO classics(author, title, category, year, isbn)

VALUES ('Charles Dickens','Little Dorrit', 'Fiction', '1857', '9780141439969');

Now that Charles Dickens appears twice in the table, we can compare the results of using
SELECT with and without the DISTINCT qualifier. Figure 11 show that the simple SELECT
lists Dickens twice, and the command with the DISTINCT qualifier shows him only once.

SELECT author FROM classics;

SELECT DISTINCT author FROM classics;

Fig. 12:
47 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

DELETE

When you need to remove a row from a table, use the DELETE command. Its syntax is similar to
the SELECT command and allows you to narrow down the exact row or rows to delete using
qualifiers such as WHERE and LIMIT.

DELETE FROM classics WHERE title='Little Dorrit';

This example issues a DELETE command for all rows whose title column contains the string
'Little Dorrit'.

WHERE

The WHERE keyword enables you to narrow down queries by returning only those where a
certain expression is true. Example above returns only the rows where the title column exactly
matches the string 'Little Dorrit', using the equality operator =.

SELECT author,title FROM classics WHERE author="Mark Twain";

SELECT author,title FROM classics WHERE isbn="9781598184891 ";

Given our current table, the two commands above display the same results. But we could easily
add more books by Mark Twain, in which case the first line would display all titles he wrote and
the second line would continue (because we know the ISBN is unique) to display only The
Adventures of Tom Sawyer. In other words, searches using a unique key are more predictable.

UPDATE…SET

This construct allows you to update the contents of a field. If you wish to change the contents of
one or more fields, you need to first narrow in on just the field or fields to be changed, in much
the same way you use the SELECT command.

UPDATE classics SET author='Mark Twain (Samuel Langhorne Clemens)'

WHERE author='Mark Twain';

UPDATE classics SET category='Classic Fiction'

48 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

WHERE category='Fiction';

Fig. 12: Effect of Update command

In the first query, Mark Twain’s real name (Samuel Langhorne Clemens) was appended to his
pen name in parens, which affected only one row. The second query, however, affected three
rows, because it changed all occurrences of the word Fiction in the category column to the term
Classic Fiction.

ORDER BY

ORDER BY sorts returned results by one or more columns, in ascending or descending order.
Example below shows two such queries, the results of which can be seen in Figure 13.

SELECT author,title FROM classics ORDER BY author;

SELECT author,title FROM classics ORDER BY title DESC;

49 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Fig. 13: Ordser_By

As you can see, the first query returns the publications by author in ascending alphabetical order
(the default), and the second returns them by title in descending order. If you wanted to sort all
the rows by author and then by descending year of publication (to view the most recent first),
you would issue the following query:

SELECT author,title,year FROM classics ORDER BY author,year DESC;

GROUP BY

In a similar fashion to ORDER BY, you can group results returned from queries using GROUP
BY, which is good for retrieving information about a group of data. For example, if you want to
know how many publications there are in each category in the classics table, you can issue the
following query:

SELECT category,COUNT(author) FROM classics GROUP BY category;

ACCESSING MySQL VIA phpMyAdmin

Although to use MySQL it is essential to learn these main commands and how they work, once
you have learned them, it can be much quicker and simpler to use a program such as
phpMyAdmin to manage your databases and tables.

50 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Ensure that you have Xampp Server up and running so that the MySQL database is ready, then
type the following into the address bar of your browser: http://localhost/phpMyAdmin

Fig. 15: phpMyAdmin

Using phpMyAdmin

In the left-hand pane of the main phpMyAdmin screen, we can click on the drop-down menu that
says “(Databases)” and select the database publications. This will open the database and display
its two tables just below. Click on the classics table, and you’ll see a host of information about it
appear in the right-hand frame (see Figure 16).

From here you can perform all the main operations for your databases, such as creating
databases, adding tables, creating indexes, and much more. To read the supporting
documentation for phpMyAdmin, visit http://www.phpmyadmin.net/documentation/.

51 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Fig. 17:

Exercise

1. What is the purpose of the semicolon in MySQL queries?

2. Which command would you use to view the available databases or tables?

3. How would you create a new MySQL user on the local host called newuser with a password
of newpass and with access to everything in the database newdatabase?

4. How can you view the structure of a table?

5. What is the purpose of a MySQL index?

6. Both SELECT DISTINCT and GROUP BY cause the display to show only one output row for
each value in a column, even if multiple rows contain that value. What are the main differences
between SELECT DISTINCT and GROUP BY?
52 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

7. Using the SELECT...WHERE construct, how would you return only rows containing the word
Langhorne somewhere in the author column of the classics table used in this chapter?

ACCESSING MySQL USING PHP

Querying a MySQL Database with PHP

The reason for using PHP as an interface to MySQL is to format the results of SQL queries in a
form visible in a web page. As long as you can log in to your MySQL installation using your
username and password, you can also do so from PHP. However, instead of using MySQL’s
command line to enter instructions and view output, you will create query strings that are passed
to MySQL. When MySQL returns its response, it will come as a data structure that PHP can
recognize instead of the formatted output you see when you work on the command line. Further
PHP commands can retrieve the data and format it for the web page.

The process of using MySQL with PHP is:

i. Connect to MySQL.

ii. Select the database to use.

iii. Build a query string.

iv. Retrieve the results and output them to a web page.

v. Repeat Steps 3 through 5 until all desired data has been retrieved.

vi. Disconnect from MySQL.

We’ll work through these sections in turn, but first it’s important to set up a login details in a
secure manner.

Creating a Login File

Most websites developed with PHP contain multiple program files that will require access to
MySQL and will therefore need your login and password details. So, it’s sensible to create a
single file to store these and then include that file wherever it’s needed.

53 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

<?php // login.php

$db_hostname = 'localhost';

$db_database = 'publications';

$db_username = 'username';

$db_password = 'password';

?>

The enclosing <?php and ?> tags are especially important for the login.php file in the above
Example, because they mean that the lines between can be interpreted only as PHP code. If you
were to leave them out and someone were to call up the file directly from your website, it would
display as text and reveal your secrets. However, with the tags in place, all they will see is a
blank page. The file will correctly include in your other PHP files.

The $db_hostname variable will tell PHP which computer to use when connecting to a database.
The database we’ll be using, $db_database, is the one called publications, which we created. The
variables $db_username and $db_password should be set to the username and password that you
have choosing.

Connecting to MySQL

Now that we have the login.php file saved, we can include it in any PHP files that will need to
access the database by using the require_once statement. This has been chosen in preference to
an include statement, as it will generate a fatal error if the file is not found. Not finding the file
containing the login details to our database is a fatal error. Also, using require_once instead of
require means that the file will be read in only when it has not previously been included, which
prevents wasteful duplicate disk accesses.

<?php

require_once 'login.php';

$db_server = mysql_connect($db_hostname, $db_username, $db_password);

54 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());

?>

This example runs PHP’s mysql_connect function, which requires three parameters, the
hostname, username, and password of a MySQL server. Upon success it returns an identifier to
the server; otherwise, FALSE is returned. Notice that the second line uses an if statement with
the die function, which does what it sounds like and quits from PHP with an error message if
$db_server is not TRUE.

The die message explains that it was not possible to connect to the MySQL database, and—to
help identify why this happened—includes a call to the mysql_error function. This function
outputs the error text from the last called MySQL function.

Selecting a database

Having successfully connected to MySQL, we are now ready to select the database that we will
be using. The example below shows how to do this.

<?php

mysql_select_db($db_database)

or die("Unable to select database: " . mysql_error());

?>

The command to select the database is mysql_select_db. Pass it the name of the database you
want and the server to which you connected. As with the previous example, a die statement has
been included to provide an error message and explanation, should the selection fail.

Building and executing a query

Sending a query to MySQL from PHP is as simple as issuing it using the mysql_query function.
The following code shows you how to use this function.

<?php

55 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

$query = "SELECT * FROM classics";

$result = mysql_query($query);

if (!$result) die ("Database access failed: " . mysql_error());

?>

First, the variable $query is set to the query to be made. In this case it is asking to see all rows in
the table classics. Note that, unlike when using MySQL’s command line, no semicolon is
required at the tail of the query. This is because the mysql_query function is used to issue a
complete query, and cannot be used to query by sending multiple parts, one at a time. Therefore,
MySQL knows the query is complete and doesn’t look for a semicolon.

This function returns a result that we place in the variable $result. Having used MySQL at the
command line, you might think that the contents of $result will be the same as the result returned
from a command-line query, with horizontal and vertical lines, and so on. However, this is not
the case with the result returned to PHP. Instead, upon success, $result will contain a resource
that can be used to extract the results of the query.

Fetching a result

Once you have a resource returned from the mysql_query function, you can use it to retrieve the
data you want. The simplest way to do this is to fetch the cells you want, one at a time, using the
mysql_result function. The code below combines and extends the previous examples into a
program that we can run to retrieve the returned results. We should save it in the same folder as
login.php and give it the name query.php.

<?php // query.php

require_once 'login.php';

$db_server = mysql_connect($db_hostname, $db_username, $db_password);

if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db($db_database)

56 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

or die("Unable to select database: " . mysql_error());

$query = "SELECT * FROM classics";

$result = mysql_query($query);

if (!$result) die ("Database access failed: " . mysql_error());

$rows = mysql_num_rows($result);

for ($j = 0 ; $j < $rows ; ++$j)

echo 'Author: ' . mysql_result($result,$j,'author') . '<br />';

echo 'Title: ' . mysql_result($result,$j,'title') . '<br />';

echo 'Category: ' . mysql_result($result,$j,'category') . '<br />';

echo 'Year: ' . mysql_result($result,$j,'year') . '<br />';

echo 'ISBN: ' . mysql_result($result,$j,'isbn') . '<br /><br />';

?>

We start by setting the variable $rows to the value returned by a call to mysql_num_rows. This
function reports the number of rows returned by a query.

Armed with the row count, we enter a for loop that extracts each cell of data from each row using
the mysql_result function. The parameters supplied to this function are the resource $result,
which was returned by mysql_query, the row number $j, and the name of the column from which
to extract the data.

The results from each call to mysql_result are then incorporated within echo statements to
display one field per line, with an additional line feed between rows. Figure 18 shows the result
of running this program.

57 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

As you may recall, we populated the classics table with five rows in the previous section, and
indeed, five rows of data are returned by query.php. But, as it stands, this code is actually
extremely inefficient and slow, because a total of 25 calls are made to the function mysql_result
in order to retrieve all the data, a single cell at a time. Luckily, there is a much better way of
retrieving the data: getting a single row at a time using the mysql_fetch_row function.

Fetching a row

It was important to show how we can fetch a single cell of data from MySQL, but fetching a row
is a much more efficient method. Replace the for loop of query.php with the new loop in below,
and you will find that we get exactly the same result that was displayed in Figure 18.

<?php

for ($j = 0 ; $j < $rows ; ++$j)

{
58 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

$row = mysql_fetch_row($result);

echo 'Author: ' . $row[0] . '<br />';

echo 'Title: ' . $row[1] . '<br />';

echo 'Category: ' . $row[2] . '<br />';

echo 'Year: ' . $row[3] . '<br />';

echo 'ISBN: ' . $row[4] . '<br /><br />';

?>

In this modified code, only one-fifth as many calls are made to a MySQL-calling function (a full
80 percent less), because each row is fetched in its entirety using the mysql_fetch_row function.
This returns a single row of data in an array, which is then assigned to the variable $row.

All that’s necessary then is to reference each element of the array $row in turn (starting at an
offset of zero). $row[0] contains the author data, $row[1] the title, and so on, because each
column is placed in the array in the order in which it appears in the MySQL table. Also, by using
mysql_fetch_row instead of mysql_result, we use substantially less PHP code and achieve much
faster execution time, due to simply referencing each item of data by offset rather than by name.

Closing a connection

When you have finished using a database, you should close the connection. This is done by
issuing the command:

<?php

mysql_close($db_server);

?>

We have to pass the identifier returned by mysql_connect back in the beginning, which we stored
in the variable $db_server.
59 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

PHP for Database Application

It’s time to write our first example of inserting data in and deleting it from a MySQL table using
PHP. We’ll save it to our web development directory using the filename sqltest.php.

<?php // sqltest.php

require_once 'login.php';

$db_server = mysql_connect($db_hostname, $db_username, $db_password);

if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db($db_database, $db_server)

or die("Unable to select database: " . mysql_error());

if (isset($_POST['delete']) && isset($_POST['isbn'])){

$isbn = get_post('isbn');

$query = "DELETE FROM classics WHERE isbn='$isbn'";

if (!mysql_query($query, $db_server))

echo "DELETE failed: $query<br />" .

mysql_error() . "<br /><br />";

if (isset($_POST['author']) &&

isset($_POST['title']) &&

isset($_POST['category']) &&

isset($_POST['year']) &&

isset($_POST['isbn']))

60 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

$author = get_post('author');

$title = get_post('title');

$category = get_post('category');

$year = get_post('year');

$isbn = get_post('isbn');

$query = "INSERT INTO classics VALUES" .

"('$author', '$title', '$category', '$year', '$isbn')";

if (!mysql_query($query, $db_server))

echo "INSERT failed: $query<br />" .

mysql_error() . "<br /><br />";

echo <<<_END

<form action="sqltest.php" method="post"><pre>

Author <input type="text" name="author" />

Title <input type="text" name="title" />

Category <input type="text" name="category" />

Year <input type="text" name="year" />

ISBN <input type="text" name="isbn" />

<input type="submit" value="ADD RECORD" />

</pre></form>
61 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

_END;

$query = "SELECT * FROM classics";

$result = mysql_query($query);

if (!$result) die ("Database access failed: " . mysql_error());

$rows = mysql_num_rows($result);

for ($j = 0 ; $j < $rows ; ++$j)

$row = mysql_fetch_row($result);

echo <<<_END

<pre>

Author $row[0]

Title $row[1]

Category $row[2]

Year $row[3]

ISBN $row[4]

</pre>

<form action="sqltest.php" method="post">

<input type="hidden" name="delete" value="yes" />

<input type="hidden" name="isbn" value="$row[4]" />

<input type="submit" value="DELETE RECORD" /></form>


62 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

_END;

mysql_close($db_server);

function get_post($var)

return mysql_real_escape_string($_POST[$var]);

?>

63 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

The $_POST Array

Browser sends user input through either a GET request or a POST request. The POST request is
usually preferred. The web server bundles up all the user input (even if the form was filled out
with a hundred fields) and puts it into an array named $_POST. Depending on whether a form
has been set to use the POST or the GET method, either the $_POST or the $_GET associative
array will be populated with the form data. They can both be read in exactly the same way.

Deleting a Record

Having loaded up the various possible variables that could have been posted with any values that
were passed, the program then checks whether the variable $_POST['delete'] has a value. If so,
the user has clicked on the DELETE RECORD button to erase a record. In this case, the value of
$isbn will also have been posted.

As you’ll recall, the ISBN uniquely identifies each record. The HTML form appends the ISBN to
the DELETE FROM query string created in the variable $query, which is then passed to the
mysql_query function to issue it to MySQL. mysql_query returns either TRUE or FALSE, and
FALSE causes an error message to be displayed explaining what went wrong.

Displaying the Form

Next is the part of the code that displays the little form at the top of Figure 19 above. The echo
<<<_END heredoc structure, which outputs everything between the _END tags.

Querying the Database

A query is sent to MySQL asking to see all the records in the classics table. After that, $rows is
set to a value representing the number of rows in the table and a for loop is entered to display the
contents of each row. Note also that instead of using the <br /> tags for line feeds, we have
chosen to use a <pre> tag to line up the display of each record in a pleasing manner.

After the display of each record, there is a second form that also posts to sqltest.php (the program
itself) but that contains two hidden fields: delete and isbn. The delete field is set to "yes" and the
isbn to the value held in $row[4], which is the ISBN for the record. Then a submit button with
the name DELETE RECORD is displayed and the form is closed.

64 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Running the Program

Once you have typed in the program (and corrected any typing errors), try entering the following
data into the various input fields to add a new record for the book

Moby

Dick to the database:

Herman Melville

Moby Dick

Fiction

1851

9780199535729

When you have submitted this data using the ADD RECORD button, scroll down to the bottom
of the web page to see the new addition. It should look like Figure below.

65 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

Fig. 20: The result of adding Moby Dick to the database

Now let’s look at how deleting a record works by creating a dummy record. Try entering just the
number 1 in each of the five fields and clicking on the ADD RECORD button. If you now scroll
down, you’ll see a new record consisting just of 1s. Obviously this record isn’t useful in this
table, so now click on the DELETE RECORD button and scroll down again to confirm that the
record has been deleted.

PHP INTEGRATED DEVELOPMENT ENVIRONMENT (IDE) AND FRAME WORKS

As good as dedicated program editors (such as notepad++, CodeWriter e.t.c.) can be for
programming productivity, their utility pales into insignificance when compared to Integrated
Developing Environments (IDEs), which offer many additional features such as in-editor
debugging and program testing, as well as function descriptions and much more. When
developing with an IDE, you can set breakpoints and then run all (or portions) of your code,

66 | CSC209: Introduction To Web Programming (PHP)


Department of Computer Science, FUGUS

which will stop at the breakpoints and provide you with information about the program’s current
state.

As an aid to learning the PHP programming, the examples in this whole lectures can be entered
into an IDE and run there and then, without the need to call up your web browser.

There are several IDEs available for different platforms, most of which are commercial, but there
are some free ones too. Choosing an IDE can be a very personal thing, so if you intend to use
one, we advise you to download a couple or more and try them out first—they all either have
trial versions or are free to use, so it won’t cost you anything.

The best IDEs for PHP Programming comprise of Eclipse, PHPStorm, Zend Studio, Sublime
Text, Nusphere, NetBeans, PHP Designer, PHPED and Cloud 9, to name some.

Eclipse

Initially released on 7th Nov 2001, Eclipse has become widely famous due to its flexibility. It is
a cross-platform tool which supports OS like Windows, Linux, and Mac. It is an ideal choice for
large-scale projects.
Features of Eclipse:-

 Automatic Error Reporting.

 Support for Git Flow.

 Multi-Platform Support with Lots of Plugins.

 Support for GUI as well as Non-GUI based applications.

 Provides seamless integration of tools.

NetBeans

Initially Released in 1996 and written in JAVA, NetBeans is one of the best tools for developers.
One of the best things about NetBeans is that it allows the concept of modular development.
Although written in JAVA, it does support other languages like PHP, C/C++, and HTML5.

Features of NetBeans Include:-


67 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

 Lightweight and much Faster than others.

 Supports PHP Frameworks like WordPress CMS, CakePHP, Zend, etc.

 Automatic generation for getter and setter. Smart Code Compilation.

 Support for Embedded Applications.

PHPStorm

Developed by JetBrains and written in JAVA, PHPStorm is one of the best IDE for building a
website using PHP. PHPStorm was initially released in 2009 and in the last 8 years, it has
become a popular choice of developers around the globe. Actually, PHPStorm is an enterprise
IDE which has a license cost, but for students and teachers, it is free of cost.

Features of PHP Storm are:-

 Rich Code Editor with Syntax Highlighting.

 Supports PHP Frameworks like Drupal, Laravel, WordPress etc.

 Live-Editing for all Front-End Technologies. Extremely Fast, Smooth and Lightweight.

 Support for Integration with Version Control Systems.

NuSpher

NuSphere is a US-based software company which specialized in making programming tools for
web development & PhpED is the PHP editor developed by that company for PHP based
applications. Initially released on 21st July 2001, PhpED supports both local and remote projects.

Features of NuSphere are:-

 Dynamic Syntax Highlighting.

 Code Insights for PHP.

 Support for CMS like WordPress and Joomla.

 Support for Docker and Git Flow.


68 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

 Facility of hiding and displaying certain portions of the file.

Zend Studio

It is an IDE developed by the Zend technologies and the stable release was launched on 31st
May 2016. It is an intelligent user-interface which provides you with all the current features for
successful PHP development.

Features of Zend Studio:-

 Facility of Seamless Integration with Zend Server.

 Faster Validation.

 Support for CMS like WordPress and Joomla.

 Support for Indexing and Searching PHP Code.

Sublime Text

Developed by Skinner & Bond on 18th Jan 2008, Sublime Text is a cross-platform editor with
Python API. Sublime Text is regarded as one of the most powerful tools for markup and coding.
Phpmysql development tools

Features of Sublime Text:-

 Excellent Command Palette.

 Facility of Opening File with Few Keystrokes.

 Facility of Simultaneous Editing.

 Compatibility with many language grammars.

 Quick Navigation to Files & Symbols.

PHPDesigner

PHP Designer is one of the best IDE for PHP development, especially for someone who has just
started to learn the trends of PHP. The latest version of PHP Designer, PHPDesigner 8 is fast and
69 | CSC209: Introduction To Web Programming (PHP)
Department of Computer Science, FUGUS

powerful IDE which helps you in all the phases of the development lifecycle. This tool is like an
all in one website editor which saves your time and money. software to design php websites

Features of PHP Designer:-

 Intelligent Syntax Highlighting.

 Support for PHP 5 and above.

 Support for Object-Oriented Programming.

 Real-time Syntax Checking.

 Powerful Code Beautifier.

70 | CSC209: Introduction To Web Programming (PHP)

You might also like