0% found this document useful (0 votes)
12 views84 pages

Internet Programming II (Lab) Programing Two in PHP

The Internet Programming II Lab Manual is designed to provide hands-on experience in web development, focusing on client- and server-side technologies. It includes practical exercises on building dynamic web applications, database integration, and web security measures. The course aims to equip students with the skills needed to design, develop, and deploy modern web applications through a combination of lectures and lab sessions.

Uploaded by

shumawakjira26
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views84 pages

Internet Programming II (Lab) Programing Two in PHP

The Internet Programming II Lab Manual is designed to provide hands-on experience in web development, focusing on client- and server-side technologies. It includes practical exercises on building dynamic web applications, database integration, and web security measures. The course aims to equip students with the skills needed to design, develop, and deploy modern web applications through a combination of lectures and lab sessions.

Uploaded by

shumawakjira26
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ETHIOPIAN POLICE UNIVERSITY

COLLEGE OF CRIME INVESTIGATION AND FORENSIC SCIENCE


DEPARTMENT OF INFORMATION TECHNOLOGY AND CYBER
SECURITY

INTERNET PROGRAMMING II LAB MANUAL

COURSE CODE: ITec3093

Prepared by: Mrs. Meti Bekele Tufa (MSc)

Contact: meti22bekele@[Link]

October, 2024
Sendafa, Ethiopia
Module Description

The Internet Programming II Lab Manual is designed to provide hands-on experience that complements
the theoretical components of the Internet Programming II course. This lab manual guides students
through practical exercises and real-world projects focused on client- and server-side web
development. Students will engage in activities that include building dynamic web applications,
working with databases, and implementing web security measures. The labs emphasize problem-
solving, debugging, and refining code to produce efficient and scalable web solutions.

i
Course Introduction
Internet Programming II is an intermediate-level course that builds on foundational web
development concepts, focusing on the creation of dynamic, interactive, and data-driven web
applications. In this course, students will learn how to bridge client-side and server-side technologies
to develop full-featured web applications that communicate with databases and handle asynchronous
data exchanges.

Additionally, students will be introduced to key web security concepts to ensure the applications they
build are functional and secure.

Internet Programming II emphasizes practical, hands-on learning through a combination of lectures


and lab exercises, helping students apply theory to real-world scenarios. By the end of the course,
students will have the skills to design, develop, and deploy modern web applications capable of
handling complex data interactions and user-driven functionality

ii
Laboratory Objectives

The laboratory component of Internet Programming II is designed to reinforce the concepts taught
in lectures through hands-on practice. The primary objectives of the lab sessions are to:

1. Develop Dynamic Web Applications: Enable students to implement server-side scripting and
logic to build dynamic, data-driven web applications.

2. Integrate with Databases: Provide experience in connecting web applications to relational


databases and performing CRUD operations (Create, Read, Update, Delete).

3. Enhance Client-Side Interactivity: Strengthen students' ability to use advanced JavaScript


techniques and DOM manipulation to create interactive and user-friendly web interfaces.

4. Apply Web Security Practices: Familiarize students with common security vulnerabilities and
help them implement security measures, such as data validation, user authentication, and
session management.

5. Use Version Control: Promote the use of Git for managing code changes, collaborating on
projects, and maintaining organized development workflows.

6. Debug and Optimize Web Applications: Equip students with the skills to troubleshoot, debug,
and improve the performance of their web applications.

iii
Table of Contents

Session 1: General Laboratory Instruction/Introduction ........................................................................1


Session 2: Create a Simple HTML & PHP Page ..................................................................................12
Objective: at the end of this laboratory session, you will be able to: ...................................................12
Session 3: PHP Comments, Variables and Strings ...............................................................................16
Session 4: PHP Expressions, Operators, control structures ..................................................................22
Session 5: PHP Arrays ..........................................................................................................................28
Session 6: PHP Functions .....................................................................................................................33
Session 7: Interaction between Client-Side and Server-Side scripts (HTML FORM Manipulation with
PHP) .....................................................................................................................................................39
Session 8: FORM validation with PHP ................................................................................................42
Session 9: File system in PHP ..............................................................................................................49
Session 10: Manipulating MySQL Database with PHP -Part I ............................................................57
Session 11: Manipulating MySQL Database with PHP -Part II ...........................................................62
Session 12: Designing Online Databases with phpMyAdmin ..............................................................70
Session 13: Cookies and Sessions in PHP ............................................................................................75
REFERENCES .....................................................................................................................................79

iv
Session 1: General Laboratory Instruction/Introduction

Objective: at the end of this laboratory session, you will be able to:

Successful participation in lab exercises by familiarizing them with the


development environment, tools, procedures, and best practices essential for
building dynamic web applications.

What you should know


Before starting this lab, it is important that you have a basic understanding and experience in the
following:

HTML - Know the syntax and especially HTML Forms.


Basic programming knowledge - this isn't required, but if you have any traditional
programming experience it will make learning PHP a great deal easier.
So, in the first lab, you should know and refresh yourself on how to:

1. Execute (X)HTML Program.


2. Execute CSS Program.
3. Execute JavaScript Program.
4. Execute PHP Program.
5. Installation Instruction
✓ Introducing Web server
✓ How to download and install the WAMP Server
1. Steps to execute (X)HTML Program.
A. Create a folder by your name in any directory
B. Open any text editor (for example, notepad, notepad++, Visual Studio Code) type the
program, and save the file with the .html extension in your folder.
C. Then open with one of the web browsers (for example the Internet Explorer
/Mozilla/chrome web browser) and type the URL as
Directory_name:\folder_name\[Link] Example: E:\cs\[Link]
1
D. Finally, the output will be displayed in the browser.

2. Steps to execute the CSS Program


A. Create a folder by your name in any directory
B. Open Notepad++ or another editor type the CSS program and save the file with the .css
extension for the CSS program in your folder. (if it is external CSS and like to the html
page)
C. Then open the Internet Explorer /Mozilla web browser and type the URL as
directoryname:\foldername\[Link] Ex: E:\cse\[Link]
D. Finally, the output will be displayed.
3. Steps to execute the JavaScript Program
The browser is responsible for running JavaScript. Thus, the output from JavaScript is going to
be more responsive as the data does not need to travel to or from the server. A web browser runs
JavaScript when a web page is downloaded or in response to an event.
JavaScript code can be placed either in an HTML file or an external file. So how do you decide
where to place your code? If your JavaScript code is small and cannot be used in any other web
page, then, you should consider placing your code directly in the HTML document that uses it.
If, on the other hand, your JavaScript is long and/or used by many HTML documents, then, you
should create a separate JavaScript file.
Because you can insert JavaScript code inside an HTML file, it needs to be distinguished from
the rest of the text or code on the page. To separate your JavaScript commands from HTML
commands or regular text on the page, insert your JavaScript code inside the opening

<script> and closing </script> tag.

For example,

<script language="JavaScript">
JavaScript commands
</script>

Because there are different client-side languages, we need to indicate to the browser which
language we are using in our scripts. To indicate the scripting language, we added the language
attribute to the <script> tag. Since we are using JavaScript, we set the language tag to JavaScript.

2
If you omit the language tag from your <script> tag, the browser will assume that your code is
written in JavaScript.
If you place your scripting code outside of the HTML page, you still use the <script> tag but then
just add the src attribute. The value of src attribute tells the browser where your JavaScript code
is located. For instance,

<script language="JavaScript" src="JavaScript/[Link]"> </script>

The code fragment above indicates that we are using JavaScript language and the JavaScript
commands are located in a folder called JavaScript and a file called [Link]. A ".js" file
extension indicates a JavaScript file.
4. Steps to execute PHP Program.
A. Type the program in notepad++ and save it with .php extension in the C:\wamp\www folder.
B. Next type the supported html & save it with .html extension in the same folder.
C. Start server (go to start->programs->Wamp server->start wamp server).
D. Open the browser & type the URL as [Link] then it will display the welcome web page
then Open Browser and type the URL as [Link]
Example: [Link]

E. Finally, the output will be displayed.

NB: If you have PHP inserted into your HTML and want the web browser to interpret it correctly, then
you must save the file with a .php extension, instead of the standard .html extension. So be sure to
check that you are saving your files correctly. Instead of [Link], it should be [Link] if there is
PHP code in the file.

If you are writing PHP scripts and plan on distributing them, it is recommended that you use the
standard form (which includes the ? php) rather than the shorthand form. This will ensure that your
scripts will work, even when running on other servers with different settings.

5. Installation Instructions

The Web pages that students create in Advanced Internet Programming / Internet Programming II
(Server-side programming) contain PHP code that must be processed by a Web server. It isn’t possible
to open PHP files directly using a Web browser alone as was done in Internet Programming I /
Introduction to Internet Programming (Client-Side Programming). PHP Web pages need to be
3
processed by a Web server first before they are viewed in a Web browser. Therefore, the first thing that
needs to be done is install a personal Web server on your computer.

❖ Windows Computers:

The personal Web server that will be used in this class for Windows computers is named WampServer.
WampServer is a free to use open-source project that installs and configures Apache, MySQL, and
PHP on a Windows computer. With WampServer you don’t need to install the individual software
components separately. WampServer will quickly and easily install and configure a complete personal
Web server. The WAMP (Windows, Apache, MySQL, and PHP) is very easy to install and to use, just
download, extract and start. SQLitemanager, The Phpmyadmin comes along with WAMP server which
gives a very good user interface to manage MySQL.

If you are using a Windows computer follow the steps in this document beginning on next page.

✓ WAMP is an acronym for Apache, MySQL, and PHP on Windows.


✓ LAMP is an acronym for Apache, MySQL, and PHP on Linux.
✓ MAMP is an acronym for Apache, MySQL, and PHP on Macintosh.
✓ XAMPP is an acronym for Apache, MySQL, PHP, and PERL on all
platforms.
Apache, PHP, and MySQL

Apache is a free open-source Web server. Apache has been the most popular web server on the
Internet since April 1996. According to a recent Netcraft survey, 62% of all Web sites on the
Internet are using Apache. This makes Apache more widely used than all other Web servers
combined. Microsoft’s Web server named Microsoft IIS has less than a third of the market share.
PHP is a free open-source scripting language designed for producing dynamic, database-driven
web pages. PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is installed on
more than 20 million websites and 1 million web servers.
MySQL is a free open-source relational database management system (RDBMS). MySQL has
more than 11 million installations.

Downloading, Installing, and Testing WampServer

4
1. Open a Web browser and go to the WampServer download page at
[Link] you can download and install WampServer.
This will give you a server on your PC (Windows users), somewhere you can test your scripts.
In this example, the Mozilla Firefox Web browser is being used.

2. Click on the DOWNLOAD tab to download the appropriate WampServer software version to
your computer. Choose the top left button to install WAMPSERVER (32 BITS & PHP 5.4)
2.4. Even if you have a 64-bit computer the 32-bit version will work fine for this class. We’re
choosing this version for the smaller installation size and because we don’t need to utilize 64-
bit functionality.

3. Choose the Save File option and then click the Save File button and double click the setup file
to install and follow the wizard.

5
If the installation went well, you should have a new icon in the bottom right, where the clock
is:

Click the icon to see the menu above.


From here, you can stop the server, exit it, view help files, and see the configuration pages.
Click on localhost, though, and you'll see this page appear: (Localhost just refers to the server
running on your computer. Another way to refer to your server is by using the IP address
[Link].)

To test if PHP was installed properly enter the address [Link] into the
Web browser. If you see the following Web page then PHP was installed correctly.

6
To test if MySQL was installed properly enter the address [Link] into
the Web browser. If you see the following Web page then MySQL was installed correctly.

7
If you saw the above page, then congratulations! That’s it. The WampServer personal Web server is
now successfully installed. Your PHP server is up and running and you can start scripting the PHP
page.

Saving your PHP files


Whenever you create a new PHP page, you need to save it in your WWW directory. You can see where
this is by clicking its item on the menu:

8
When you click on www directory, you should see an explorer window appear. (You'll probably have
only two files, index and testmysql.)

This www folder for Wampserver is usually at this location on your hard drive: c:/wamp/www/
Bear this in mind when you click File > Save As to save your PHP scripts.

Launching your PHP scripts


Suppose you have created a php script called [Link]. To launch this script, you need to add the script
name after localhost in your browser. So instead of this:

[Link]

9
You would type this:

[Link]

You don't type the name of the Wamp folder, however. This would be wrong, for example:

c:/wamp/www/[Link]

As too would this:

[Link]

Your server knows where the www folder is, so you don't have to type it out: just add the script name
to localhost. Likewise, if you create a folder under www then you'd just type this:

[Link]

Create a [Link] file as follows.

<html> <head>

<title> Hello world </title>

</head>

<body text=white bgcolor=blue>

<?php

Print "Hello, World!";

?>

<?php

$x="Hi there, ";

$x=3;
$x=4.5;
echo "Hello, World!,
$x ";
?>

</body> </html>

10
Output

Now open the browser and type [Link] or you could type it in [Link]
and browse through the projects and select [Link]

Hello, World! Hello, World!, 4.5

11
Session 2: Create a Simple HTML & PHP Page

Objective: at the end of this laboratory session, you will be able to:

To embed PHP scripts on HTML

To declare and initialize PHP variable

to start and finish a PHP block of code

To include a file in a PHP code

Example 1: The following program will display Hello World on the browser (PHP scripts embedded
in HTML).

<!DOCTYPE html>

<html>

<head>

<title>My First PHP Page</title>

</head>

<body>

<?php // PHP delimiters- opening marker

echo "Hello World";

?> // PHP delimiters- closing marker

</body>

</html>

Output:

12
Hello World

Example 2: Declaration and initialization of variable in PHP

<!DOCTYPE html>

<! -- [Link] -->

<! -- Simple PHP program. -->

<html>

<?php

$name = "Abebe"; // declaration and initialization

?><! -- end PHP script -->

<head>

<meta charset = "utf-8">

<title>Simple PHP document</title>

</head>

<body>

<!-- print variable name’s value -->

<h1>
<?php
print(“Welcome to PHP, $name!" );
?>

</h1>

</body></html>

Output:

13
Welcome to PHP, Abebe!

Example 3: Ways to start and finish a PHP block of code.

<!DOCTYPE html>
<html>
<head>
<title>Simple PHP Example</title>
</head>

<body>

<?php
echo"<p><h1>Output</h1>";
echo "<h2>Output</h2>";
echo "<h3>Output</h3></p>";
?>

<script language="PHP">
echo "\n<b>More PHP Output</b>\n";
echo "New line in source but not rendered";
echo "<br/>";
echo "New line rendered but not in source";
</script>

</body></html>
Exercise: What is the output of example 3?

Example 4: How to include a file into a PHP code

14
[Link]

<!DOCTYPE html>

<html> <head>

<title>Third PHP Example</title>

</head>

<body>

<?php echo"<p><h2>Initial script</h2>


include("[Link]");
echo"<h2>Back to initial script</h2>”;
include("[Link]");
echo"<h2>Back again to script</h2></p>”;
include("[Link]");
echo "<h2>Finally back to script</h2></p>";
?>

</body>

</html>

[Link]

<?php

echo "<p><h3><b>Included script</b></h3>"; ?>


[Link]

<h3><i>Included HTML</i></h3>

[Link]

echo "<h3><b>Another included script</b></h3>";


Exercise: Discuss how example 4 works and why [Link] is wrong?

15
Session 3: PHP Comments, Variables and Strings

Objective: at the end of this laboratory session, you will be able to:

Understanding and applying single-line and multi-line comments to document


code.

Defining and using variables to store and manipulate different types of data.

Working with strings in PHP, including concatenation, interpolation, and


various string functions for manipulating text.

Gaining the ability to use variables and strings in real-world web applications.

Example 1: The following program will help you to know about comments, variables, and strings.

<!DOCTYPE html>

<html> <head>

<title>Session 3 PHP Example</title>

</head>

<body>

<?php

/* PHP Comments can be in the style of C, C++/Java, or Perl

This multiline comment is in the C style */

// The C++ / Java style is also fine

# And the Perl style works as well (in case you are interested)

16
// Note that with double quotes the variables are interpolated

// into the string but with single quotes the variable names are

// put into the strings. If double quotes are used, we can

// prevent interpolation by putting a backslash before the

// variable name, as shown.

// Also note something about the \n in the first two lines below:

// With double-quotes, the \n produces a newline character


// as we are used to seeing with C++ or Java
// With single-quote, the \n produces the characters \ and n

//

// However, in NEITHER case, does a new line show up on the web

// page, since newlines are ignored by the html parser -- we need a

// <br/> to get a newline on the web page.


echo "\$x is $x and is type ", gettype($x), "<br/>\n";
$x = 50;
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
echo '$x is $x and is type ', gettype($x), '<br/>\n';
$x = $x * 100000000000000000000000000000;
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
$x = 10;
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
$x += 1.350;
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
echo var_dump($x), "<br />\n";
$x = "hello " . $x;
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
echo var_dump($x), "<br />\n";

17
echo "Here are the first three characters: <br/>";
echo "$x[0] $x[1] $x[2] <br />";
$y = $x;

$x = $y == "hello 11";
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
$x = $y == "hello 11.35";
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
$x = 1234;
echo var_dump($x) . "<br/>\n";
if (is_int($x))
echo "I am an int<br/>\n";

else

echo "I am NOT an int<br/>\n";

if (is_string($x))

echo "I am a string<br/>\n";

else

echo "I am NOT a string<br/>\n";


if (is_numeric($x))

echo "I am numeric<br/>\n";

else

echo "I am NOT numeric<br/>\n";

$x = "wacky1234";
echo var_dump($x), "<br/>\n";
if (is_int($x))

echo "I am an int<br/>\n";

18
else

echo "I am NOT an int<br/>\n";

if (is_string($x))

echo "I am a string<br/>\n";

else

echo "I am NOT a string<br/>\n";

if (is_numeric($x))

echo "I am numeric<br/>\n";

else

echo "I am NOT numeric<br/>\n";

?>

</body> </html>

Exercise: What do you learn from the above example?

Example 2: echoing variables and text strings

<?php
$my_string = "Hello Bob. My name is: ";
$newline = "<br />";
echo $my_string."Bobettta".$newline;
echo "Hi, I'm Bob. Who are you? ".$my_string.$newline;
echo "Hi, I'm Bob. Who are you? ".$my_string."Bobetta";
//echo “$my_string”;
//echo ‘$my_string’;
?>

Output:
19
Hello Bob. My name is: Bobetta
Hi, I'm Bob. Who are you? Hello Bob. My name is:
Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta
Exercise: try to display the values of the variable that are enclosed within double quotes (“ “) and
single quotes(‘ ‘). For example, see the output of the following from the above example.
echo “$my_string”;
echo ‘$my_string’;
What difference do you observe?

Example 3: PHP predefined variables

<!DOCTYPE html> <html> <head>


<title>PHP Example</title>
</head> <body>
<?php
# Here are a few PHP predefined variables
echo $_SERVER["HTTP_HOST"], "<br/>";
echo $_SERVER["SERVER_SOFTWARE"], "<br/>";
echo $_SERVER["SCRIPT_FILENAME"], "<br/>";
echo $_POST, "<br/>";
# The output from the loop below shows all of the $_SERVER
# values for this execution. We will discuss how the loop
# works shortly (after discussing arrays). Note that if we
# Substitute POST for SERVER, the output will be empty, since
# In this script there are no POST parameters. When we process
# forms, POST will not be empty and we will extract values from it

echo "Values in the \$_SERVER Variable: <br/>";


foreach ($_SERVER as $key => $val) {
echo "$key has value $val <br/>";

20
}
# The phpinfo() function is very useful, showing the configuration
# information about the server.
// phpinfo();
?>

</body> </html>

21
Session 4: PHP Expressions, Operators, control structures

Objective: at the end of this laboratory session, you will be able to:
Understanding and using various operators (arithmetic, comparison, logical, etc.) to
perform calculations and comparisons in PHP.
Writing and evaluating expressions to manipulate data and perform operations.
Implementing control structures (if, else, elseif, switch) to make decisions based on
conditions.
Using loops (for, while, do-while, foreach) to repeat actions and iterate over data sets.
Applying these concepts to create efficient, dynamic web applications that respond to
user interactions or inputs.

Expressions and Arithmetic Operators Example:

<?php

$addition = 2 + 4;

$subtraction = 6 - 2;

$multiplication = 5 * 3;

$division = 15 / 3;
$modulus = 5 % 2;
echo "Perform addition: 2 + 4 = ".$addition."<br />";
echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />";
echo "Perform multiplication: 5 * 3 = ".$multiplication."<br />"; echo
"Perform division: 15 / 3 = ".$division."<br />";
echo "Perform modulus: 5 % 2 = " . $modulus . ". Modulus is the
remainder after the division operation has been performed.
In this case, it was 5 / 2, which has a remainder of 1.";
?>

22
Output:

Perform addition: 2 + 4 = 6

Perform subtraction: 6 - 2 = 4

Perform multiplication: 5 * 3 = 15

Perform division: 15 / 3 = 5

Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been
performed. In this case, it was 5 / 2, which has a remainder of 1.

String Operators Example:

<?php

$a_string = "Hello";

$another_string = " Billy";

$new_string = $a_string . $another_string;


echo $new_string . "!";
?>

Output:

Hello Billy!

Pre/Post-Increment & Pre/Post-Decrement Example:

<?php
$x = 4;
echo "The value of x with post-plusplus = " . $x++;
echo "<br /> The value of x after the post-plusplus is " . $x;
$x = 4;
echo "<br />The value of x with with pre-plusplus = " . ++$x;
echo "<br /> The value of x after the pre-plusplus is " . $x;
?>
23
Output:

The value of x with post-plusplus = 4

The value of x after the post-plusplus is = 5

The value of x with with pre-plusplus = 5

The value of x after the pre-plusplus is = 5

Example: Demonstration of expressions and control structures

<!DOCTYPE html>

<html>

<head>

<title>Twelve PHP Example</title>

</head>

<body>

<?php

// Demonstration of expressions and control structures in PHP

$x = 15;

$y = 6;
$z = 5;
echo ($x/$y), " ", (int)($x/$y), ($x/$z), "<br/><br/>\n";

$x = 150; $x2 = "150";

$y = 160; $y2 = "160";

$z = 80; $z2 = "80";

$a = "aardvark";

if ($x == $x2) print "[int] $x == [string] $x2 <br/>\n"; // yes


if ($x === $x2) print "[int] $x === [string] $x2 <br/>\n"; // no

24
if ($x !== $x2) print "[int] $x !== [string] $x2 <br/>\n"; // yes
if ($x < $y) print "[int] $x < [int] $y <br/>\n"; // yes
if ($x < $y2) print "[int] $x < [string] $y2 <br/>\n"; // yes (casting)
if ($x < $z) print "[int] $x < [int] $z <br/>\n"; // no (numeric)
if (strcmp($x, $z) < 0) print "$x lt $z <br/>\n"; // yes (alpha)
if ((string)$x < (string)$z) print "$x lt $z <br/>\n"; // no (why???)
else
print "$x ge $z <br/>\n";
if ($x < $a) print "$x < $a <br/>\n"; // no (why???)
else print "$x >= $a <br/>\n";
if ((string)$x < $a) print "$x lt $a <br/>\n"; // yes (why???)

echo "<br/>";

$x1 = "wacky"; // normal string

$x2 = "10"; // string representing a number

$x3 = "0"; // string representing 0

$x4 = "00"; // string double 0

$y = 0; // 0 integer

$z = (2 != 2); // false boolean

if ($x1 == $y) // non-numeric string == 0

print "[string] $x1 == [int] $y -- WACKY! <br/>\n";

if ($x2 != $y) // numeric string == number value

print "[string] $x2 != [int] $y -- WACKY! <br/>\n";

if ($x3 == $y) // numeric string == number value

25
{

print "[string] $x3 == [int] $y -- WACKY! <br/>\n";

if ($x1 != $z) // non-numeric string == true

print "[string] $x1 != [boolean] $z -- WACKY! <br/>\n";

if ($x2 != $z) // non-zero string == true

print "[string] $x2 != [boolean] $z -- WACKY! <br/>\n";

if ($x3 == $z) // zero string == false

print "[string] $x3 == [boolean] $z -- WACKY! <br/>\n";

if ($x4 != $z) // 00 string == true

print "[string] $x4 != [boolean] $z -- WACKY! <br/>\n";

?>

<h2><strong> <?php
for ($i = 1; $i <= 10; $i++)

echo $i;

if ($i < 10) echo ", ";

26
}

echo "<br/>\n";

// Same loop as above but now using the alternative

// block syntax. Once you get used to this, you may

// prefer it to the old C-style blocks


for ($i = 1; $i <= 10; $i++):
echo $i;
if ($i < 10)
echo ", ";

endfor;

echo "<br/>\n";

?>

</strong></h2>

</body>

</html>

Exercises

1. Write a PHP program that uses a while loop to print the phrase “Hello World” ten times.

2. Write a PHP program that uses a for loop to print the phrase “Hello World” ten times.

3. Write a PHP code that calculates and displays the summation of the first 10 even numbers.

4. Write a PHP code that calculates and displays the net salary, pension, and tax of an Ethiopian
police university Employee.

27
Session 5: PHP Arrays

Objective: at the end of this laboratory session, you will be able to:

Understanding how to create and use different types of arrays (indexed, associative,
and multidimensional arrays).
Accessing, modifying, and manipulating array elements.
Utilizing array functions to perform operations such as sorting, merging, and
searching within arrays.
Implementing arrays to manage and organize data dynamically in web applications

Example 1: Numeric and Associative Array

<html>
<body>
<?php
//numeric array
$friend[0] = "Abebe";
$friend[1] = "Yonas ";
$friend[2] = "Tigist";
$friend[3] = "Sara";
//associative array
$age["Abebe"] = 45;
$age["Yonas"] = 32;
$age["Tigist"] = 26;
$age["Sara"] = 15;

28
print "My friends names are " . $friend[0] . ", " . $friend[1] . ", " . $friend[2] . ", and " .
$friend[3];
Print "<p>";
print "Sara is " . $age["Sara"] . " years old";
echo"<hr/>\n"; print_r($friend);
echo"<hr/>\n"; print_r($age);
echo "<hr/>\n";
foreach ($friend as $key => $val)
{
echo "$key is an index of $val <br/>";
}
echo "<hr/>\n";

foreach ($age as $key => $val)

{
echo "$key is $val years old <br/>";

echo "<hr/>\n";

//two-dimensional arrays

<?php

$marks = array( "Mohammad" => array("physics" => 35, "maths" => 30,"chemistry" => 39),
"Qadir" => array("physics" => 30,"maths" => 32,"chemistry" => 29),

"Zara" => array("physics" => 31,"maths" => 22,"chemistry" => 39));

/*Accessing multi-dimensional array values


*/ echo "Marks for Mohammad in physics: " ;
echo $marks['Mohammad']['physics'] . "<br />";
echo "Marks for Qadir in maths: ";
echo $marks['Qadir']['maths'] . "<br />";
echo "Marks for Zara in chemistry: " ;

29
echo $marks['Zara']['chemistry'] . "<br />";
//One predefined way to show an array with arbitrary nesting
// is the print_r method as shown below.
echo"<hr/>\n";
print_r($marks);
?>

</body>

</html>

Example 2: Associative array

<?php

//$myArray is a ToDo-List of things that need to be done

//in different locations (home, work, shopping mall)

//On the line below, create your associative array:

$myArray = array ('at home' => array ('laundry', 'dishes'),

'shopping' => array ('milk', 'bread’, ‘pasta'),

'at work'=>array ('teaching’, ‘research'));

// On the line below, output one of the values to the page:

echo $myArray ['shopping'][2].'<br />';

// On the line below, loop through the array and output

// *all* of the values to the page:

foreach ($myArray as $place => $task) {

foreach ($task as $thingToDo){

echo $thingToDo.'<br />';

30
/* The first foreach-command is addressing every part in

$myArray as $place (key) and $task (value).

The $task itself is an array, so the second foreach command

(which is inside the first) addresses each item inside each

array as $thingToDo(value) of each $task(key).

So in the second foreach-command, the value of the first

foreach-command becomes a key.*/

?>

Example 3: Accessing multi-dimensional array values using foreach statement and list () construct

<?php

$marks = array( "Mohammad" => array("physics" => 35, "maths" => 30,"chemistry" => 39),
"Qadir" => array("physics" => 30,"maths" => 32,"chemistry" => 29),

"Zara" => array("physics" => 31,"maths" => 22,"chemistry" => 39));


/*Accessing multi-dimensional array values using
foreach statement,list() construct */
// method1

foreach ($marks as $stud => $course) {


foreach ($course as $res){
while (list($key, $value) = each ($course)) {

echo " $stud has got $value in $key. <br />";

31
//method2

for eacforeach ($marks as $stud => $course){


foreachforeach ($course as $key => $value) {
echo "$stud: $key ($value)<br>";

// check whether the current item is an array!


if(is_array($value)){
echo "$key is sub-array:<br />";
foreach($value as $subKey => $subValue)
echo "$subKey: $subValue<br />";
}

?>

32
Session 6: PHP Functions

Objective: at the end of this laboratory session, you will be able to:

Understanding the syntax and structure of defining and calling functions in PHP.
Differentiating between built-in and user-defined functions.
Passing arguments to functions and returning values to the calling code.
Utilizing variable scope and understanding local vs. global variables.

Applying functions to break down complex problems into manageable, logical parts,
fostering better organization in web application development.

Example 1: Defining and calling a PHP Function with parameter and no parameter.

<html>
<head>
<title>Writing PHP Function</title> </head>
<body>
<?php //Defining a PHP Function
function writeMessage()
{
echo "You are really a nice person, Have a nice time!<br/>";
}
/* Calling a PHP Function */
writeMessage(); //Writing PHP Function with Parameters
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum <br/>";
}
addFunction(10, 20);
?>
</body>
</html>

33
Output:

You are really a nice person, Have a nice time!


Sum of the two numbers is : 30

Example 2: Use of default parameters in functions

<?php
//Use of default parameters in functions function
makecoffee($type = "cappuccino")
{
return "Making a cup of $type.<br/>";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");

//Incorrect usage of default function arguments


function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); // won't work as expected

//Correct usage of default function arguments


function makeyogurt($flavour, $type = "acidophilus")
{
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt("raspberry"); // works as expected
?>

34
Example 3: Passing function parameters by value and reference

<?php
//Passing function parameters by value
function add_some_extra($string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, '; add_some_extra($str);

echo "$str<br/>"; // outputs 'This is a string,'

//Passing function parameters by reference

function add_some_extra1(&$string)

$string .= 'and something extra';

$str1 = 'This is a string, ';

add_some_extra1($str1);

echo "$str1.<br/>"; // outputs 'This is a string, and something extra.'

?>

Output:

This is a string,
This is a string, and something extra.

Example 4: scope of a variables: Local, Global, and Static.

35
<html>
<head>
<title>The scope of a variable</title>
</head>
<body>
<?php
//Local scope
function update_counter1 ( ) {
$counter1=$counter1+2;// shows error
echo "counter1 is now $counter1 <br/>";
}
$counter1 = 10;
update_counter1( );
echo "counter1 is $counter1 <br/>";//10

//Global scope
function update_counter2 ( ) {
global $counter2;
$counter2++;
}
$counter2 = 10;

36
update_counter2( );
echo "Global counter2 is $counter2 <br/>"; //11

//A static variable retains its value between calls //to a


function but is visible only within that function. function
update_counter3 ( ) {
static $counter3 = 0;
$counter3++;
echo "Static counter3 is now $counter3 <br/>";
}
$counter3 = 10;
update_counter3( );
update_counter3( );
echo "Global counter3 is $counter3 <br/>";
//Static counter3 is now 1
//Static counter3 is now 2
//Global counter3 is 10
?>
Output:

counter1 is now 2
counter1 is 10
Global counter2 is 11
Static counter3 is now 1
Static counter3 is now 2

Global counter3 is 10

Exercise

Using the PHP function, write a program that calculates the sum of three numbers:

1. The case of no parameter to the function

37
2. The case of three parameters to the function
3. The case of default parameter to the function

38
Session 7: Interaction between Client-Side and Server-Side scripts (HTML FORM
Manipulation with PHP)
Objective: at the end of this laboratory session, you will be able to:

Understanding the structure and elements of HTML forms, including input types,
labels, and form attributes.
Learning how to handle form submissions in PHP, including retrieving and processing
user input using the $_POST and $_GET superglobals.
Implementing data validation techniques to ensure the integrity and security of user
inputs.
Exploring how to provide user feedback and error messages based on form validation
results.
Developing practical applications that utilize form data to create personalized user
experiences, such as registration forms, contact forms, and search functionalities.

Enhancing skills in integrating PHP with HTML to create seamless user interfaces
that effectively capture and process data.

HTML Code:

[Link]

<html><body>

<h4>Tizag Art Supply Order Form</h4>

<form action="[Link]" method="post">

<select name="item">

<option>Paint</option>

<option>Brushes</option>

<option>Erasers</option>

</select>

Quantity: <input name="quantity" type="text" />

39
<input type="submit" />
</form> </body></html>
PHP Code:

[Link]

<html><body>

<?php

$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from Tizag Art Supplies!";
?> </body></html>
If you selected the item brushes and specified a quantity of 6, then the following would be displayed on
"[Link]":

You ordered 6 brushes.

Thank you for ordering from Tizag Art Supplies!

[Link]

<html> <head>

<title>hello user</title>

</head>

<body>

<form action="[Link]" method="post">

Name: <input type="text" name="username" />

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

</form>

</body> </html>

40
[Link]

[Link]

<?php

$content = $_POST['username']; echo


"Hello !" . $content . ".<br />"; echo
"You have visited the Server Page"
?>

Exercises

1. How to execute the above examples?

2. Where shall we begin to execute? Is it from HTML or PHP?

3. Accept two numbers from the HTML form and display their summation,
subtraction, product and division on the browser using PHP.

4. Develop and demonstrate using PHP script that displays your full information
(Name, date of birth, Department, Address, etc) that was accepted from the
HTML form.

41
Session 8: FORM validation with PHP

Objective: at the end of this laboratory session, you will be able to:

Understanding the various types of validation techniques, including client-side and


server-side validation.
Learning how to validate different input types (text, email, numbers, etc.) using PHP
functions and regular expressions.
Implementing comprehensive validation rules to check for required fields, data
formats, and length constraints.

Develop strategies to handle validation errors and provide meaningful feedback to


users to improve the overall usability of forms.

42
PHP Code segment

[Link]

<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$websiteError ="";
// On submitting form below function will execute.
if(isset($_POST['submit'])){
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailError = "Invalid email format";
}}

43
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check address syntax is valid or not(this regular expression also allows dashes in the URL)
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-
z09+&@#\/%=~_|]/i",$website)) {
$websiteError = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderError = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> //php code ends here

44
HTML Code segment

<!DOCTYPE html>
<html>
<head>
<title>Form Validation with PHP - Demo Preview</title>
<meta content="noindex, nofollow" name="robots">
<link href="[Link]" rel="stylesheet">
</head>
<body>
<div class="maindiv">
<div class="form_div">
<div class="title">
<h2>Form Validation with PHP.</h2>
</div>
<form action="[Link]" method="post">
<h2>Form</h2>
<span class="error">* required field.</span>
Name:
<input class="input" name="name" type="text" value=""> <span
class="error">* <?php echo $nameError;?></span>
E-mail:
<input class="input" name="email" type="text" value=""> <span
class="error">* <?php echo $emailError;?></span>
Gender:
<input class="radio" name="gender" type="radio" value="female">Female
<input class="radio" name="gender" type="radio" value="male">Male
<span class="error">*<?php echo $genderError;?></span>
Website:
<input class="input" name="website" type="text" value="">
<span class="error"><?php echo $websiteError;?></span>
Comment:

45
<textarea cols="40" name="comment" rows="5">
</textarea>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
</div>
</body>
</html>

CSS File

[Link]
(Remember this from your previous course: Internet Programming I)
@import "[Link]
/* Above line is to import Google font style */
.maindiv{
margin:0auto;
width:980px;
height:500px;
background:#fff; padding-
top:20px; font-size:14px
}
.title{
width:500px; height:70px;
text-shadow:2px 2px 2px #cfcfcf; font-
size:16px; text-align:center;
font-family:'Droid Serif',serif
}
.form_div{
width:70%;
float:left

46
}
form{
width:440px;
border:1px dashed #ccc;
padding:10px 30px 40px;
background-color:#f0f8ff; font-
family:'Droid Serif',serif
}
form h2{
text-align:center;
text-shadow:2px 2px 2px #cfcfcf
}
textarea{
width:250px;
height:60px;
border-radius:1px;
box-shadow:0 0 1px 2px #123456;
margin-top:10px;
padding:5px;
border:none
}
.input{
width:250px;
height:15px;
border-radius:1px;
box-shadow:0 0 1px 2px #123456;
margin-top:10px;
padding:5px; border:none;
margin-bottom:20px
}
.submit{

47
color:#fff;
border-radius:3px;
background:#1F8DD6;
padding:5px;
margin-top:40px; border:none;
width:100px;
height:30px;
box-shadow:0 0 1px 2px #123456;
font-size:16px
}
.error{
color:red }
.radio{
width:15px; height:15px;
border-radius:1px;
margin-top:10px;
padding:5px; border:none;
margin-bottom:20px
}
.formget{
float:right;
margin-top:85px
}

Exercises

1. Is the above expression enough to validate name, email, gender, website and comment? If not,
please validate them to the maximum level?

2. Using PHP script validates data/input submitted from html form of having inputs (phone
number, age, and address).
48
Session 9: File system in PHP

Objective: at the end of this laboratory session, you will be able to:

Understanding the PHP file system functions and their applications for managing files
and directories.
Learning how to perform essential file operations, including creating, opening,
reading, writing, and closing files.
Implementing techniques for uploading and downloading files securely in web
applications.
Exploring methods for handling file permissions and ensuring proper security
measures are in place when accessing or modifying files.

Gaining familiarity with file handling error management to enhance application


reliability and user experience.

include() and require() functions

49
Exercise: Discuss the differences of include, include_once, require, require_once from the above
example.

File Paths and Directory Script Navigation

<?php

// these first 5 examples use relative referenced paths (relative to where script is)

$my_file = "[Link]"; // Connect to file in same folder

$my_file = "myFolder/[Link]"; // File in a folder within the current folder

$my_file = "myFolder/anotherFolder/[Link]"; // Connect to file in a folder within a folder

$my_file = "../[Link]"; // Connect to file in the parent directory (jump up one level)

$my_file = "../../[Link]"; // File 2 parent folders up (jump up two levels)

$my_file = "[Link] // This example is referencing


the file by full URL

?>

Creating Files

<?php

// you can create any extension type file(html, php, xml, etc...)

$file_x = "my_file.txt";
$createFile=touch($file_x);
if (file_exists($file_x)) {
echo "The file has been created";
} else {
echo "The file has not been created";
}

?>

50
The file has been created
Deleting files

<?php

// you can delete any extension type file(html, php, jpg, gif, flv, swf, etc...)

$file_x = "my_file.txt";
if (file_exists($file_x)) {
unlink($file_x); // delete it here only if it exists
echo "The file has been deleted";
} else {
echo "The file was not found and could not be deleted";
}
?>

The file has been deleted

Opening, Writing, Appending, Closing, and Reading Files in PHP

modes for reading and writing files

51
<?php

// Here we define the file path and name

$target_file = "my_file.txt";

// Here we define the string data that is to be placed into the file

$target_file_data = "This is the string data or code I want to place in the newly created
file.";

// Here we are creating a file(since it does not yet exist) and adding data to it

$handle = fopen($target_file, "w");


fwrite($handle, $target_file_data); // write it
fclose($handle);
// Here we are opening and appending to the file

$handle = fopen($target_file, "a");

// Here we define the string data that is to be appended to the data already in file

$target_file_data = "Here is more data I want to append to the file.";


fwrite($handle, $target_file_data); // write it
fclose($handle);
// Here we display the file contents by including it
include($target_file);
?>

This is the string data or code I want to place in the newly created file.
Here is more data I want to append to the file.

52
In the example above we created a file, wrote to it, closed it, appended
data to it, then displayed its contents.
Reading a file

<html> <head>

<title>Reading a file using PHP</title>

</head> <body>

<?php

$filename = “my_file.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in the opening file"
); exit();
}

$filesize = filesize( $filename );


$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size :$filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>

</body> </html>

Writing a file

53
<?php

$filename = "my_file.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{ echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>

<html>

<head>

<title>Writing a file using PHP</title>

</head>

<body> <?php
if (file_exists($filename))

$filesize = filesize( $filename );

$msg = "File created with name $filename </br> ";

$msg .= "containing $filesize bytes";

echo ($msg );
}
else
{ echo ("File $filename does not exit" );

?>

</body></html>

54
Uploading Files

file_uploader.html

<html> <head>

<title>File Uploading Form</title>

</head>

<body><h3>File Upload:</h3>

Select a file to upload: <br />

<form action="/php/file_uploader.php" method="post"

enctype="multipart/form-data">

<input type="file" name="file" size="50" /> <br />

<input type="submit" value="Upload File" />


</form></body></html>
file_uploader.php

<?php
if( $_FILES['file']['name'] != "" )
{ copy( $_FILES['file']['name'], "/var/www/html" ) or
die( "Could not copy file!");
}
else
{ die("No file specified!");

?>

<html> <head> <title>Uploading Complete</title>

</head> <body>

<h2>Uploaded File Info:</h2>

55
<ul>

<li>Sent file: <?php echo $_FILES['file']['name']; ?>

<li>File size: <?php echo $_FILES['file']['size']; ?> bytes

<li>File type: <?php echo $_FILES['file']['type']; ?>

</ul>

</body></html>

When you will upload a file using upload form and upload script, it will display following result:

Uploaded File Info:

Sent file: [Link]

File size: 2003 bytes

File type: image/jpg

Exercises:

1. Using PHP scripts create, delete, read, write, append, upload, and download a file.

2. Move and copy the file form its original place to another using PHP

3. Retrieve the file information from the global PHP variable called $_FILES.

56
Session 10: Manipulating MySQL Database with PHP -Part I

Objective: at the end of this laboratory session, you will be able to:

Implementing CRUD operations to manipulate data within a MySQL database,


including executing SQL queries and handling results.
Understanding how to manage database structures, including creating and modifying
tables, and managing relationships between different data entities.
Developing practical applications that utilize MySQL databases for data-driven
features, such as user authentication, content management systems, and e-commerce
functionalities.

Gaining experience in error handling and debugging database interactions to ensure


the robustness and reliability of applications

Connect to a MySQL Server and Create a MySQL Database

NB: if you don't know the username, servername, and password, make these parameters empty.

<html><head>

<title> Connect to a MySQL server and Create MySQL Database</title>


</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'CREATE DATABASE TUTORIALS';

57
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create database: ' . mysql_error());
}
echo "Database TUTORIALS created successfully\n";
mysql_close($conn);
?>
</body></html>

Deleting MySQL database

<html><head>
<title>Deleting MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'DROP DATABASE TUTORIALS';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete database: ' . mysql_error());

58
}
echo "Database TUTORIALS deleted
successfully\n";
mysql_close($conn);
?>
</body></html>

Selecting MySQL Database Using PHP Script

<html><head>
<title>Selecting MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'TUTORIALS' );
mysql_close($conn);
?>
</body> </html>

Creating Tables Using PHP Script

59
<html><head>
<title>Creating MySQL Tables</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "CREATE TABLE tutorials_tbl( ". "tutorial_id INT NOT NULL
AUTO_INCREMENT, ". "tutorial_title VARCHAR(100) NOT NULL, ".
"tutorial_author VARCHAR(40) NOT NULL, ". "submission_date DATE, ".
"PRIMARY KEY ( tutorial_id )); ";

mysql_select_db( 'TUTORIALS' );
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully\n";
mysql_close($conn);
?>
</body></html>

Dropping Tables Using PHP Script

60
<html>
<head><title>Dropping MySQL Tables</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
If(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "DROP TABLE tutorials_tbl";
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete table: ' . mysql_error());
}
echo "Table deleted successfully\n";
mysql_close($conn);
?>
</body></html>

61
Session 11: Manipulating MySQL Database with PHP -Part II

Inserting data into MySQL table Using PHP Script


Example 1: The HTML form and PHP script on one file using $_PHP_SELF

<html><head> <title>Add New Record in MySQL Database</title> </head>


<body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error()); }
$tutorial_title = $_POST['tutorial_title'];
$tutorial_author = $_POST['tutorial_author'];
$submission_date = $_POST['submission_date'];
$sql = "INSERT INTO tutorials_tbl ". "(tutorial_title,tutorial_author, submission_date)
". "VALUES ".
"('$tutorial_title','$tutorial_author','$submission_date')";
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
} else

62
{?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="600" border="0" cellspacing="1" cellpadding="2">
<tr><td width="250">Tutorial Title</td><td>
<input name="tutorial_title" type="text" id="tutorial_title"></td>
</tr><tr><td width="250">Tutorial Author</td><td>
<input name="tutorial_author" type="text" id="tutorial_author"></td>
</tr><tr><td width="250">Submission Date [ yyyy-mm-dd ] </td><td>
<input name="submission_date" type="text" id="submission_date"></td></tr>
<tr><td width="250"> </td><td> </td></tr><tr><td width="250"> </td><td>
<input name="add" type="submit" id="add" value="Add Tutorial"></td>
</tr></table></form>
<?Php
}
?> </body></html>

Example 2: The HTML form and PHP scripts are on separate files.

[Link]
<html>
<body>
<form action="[Link]" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>

63
</html>
[Link]

<?php
$con=mysqli_connect(““, ““ , ““ , "my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

Fetching Data Using PHP Script


Example 1: Fetching Data Using mysql_fetch_array() function

//display all the records from tutorials_tbl table.


<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

64
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM
tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title: {$row['tutorial_title']} <br> ".
"Author: {$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

Example 2: Display all the records using mysql_fetch_assoc() function

//display all the records from tutorial_tbl table using mysql_fetch_assoc() function.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
If(! $conn )

65
{ die('Could not connect: ' . mysql_error());}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM
tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval=mysql_query($sql,$conn);
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_assoc($retval))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title: {$row['tutorial_title']}
<br> ". "Author: {$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "-------------------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

Example 3: Display all the records using the MYSQL_NUM argument.

//display all the records from tutorials_tbl table using MYSQL_NUM argument.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error()); }
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date
FROM tutorials_tbl';

66
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{ echo "Tutorial ID :{$row[0]} <br> ". "Title: {$row[1]} <br> ". "Author:
{$row[2]} <br> ". "Submission Date : {$row[3]} <br> ". "-------<br>";} echo
"Fetched data successfully\n";
mysql_close($conn);
?>

NB: All the above three examples will produce the same result.

Example 4: Return all the records from the tutorials_tbl table for which the author's name is Abebe
using the MYSQL_NUM argument.

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date
FROM tutorials_tbl WHERE tutorial_author=" Abebe "'; mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title: {$row['tutorial_title']} <br>
". "Author: {$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "--------------<br>";}

67
echo "Fetched data successfully\n";
mysql_close($conn);
?>

Updating Data Using PHP Script

// update tutorial_title field for a record having tutorial_id as 3.


<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
$sql = 'UPDATE tutorials_tbl SET tutorial_title="Learning JAVA" WHERE tutorial_id=3';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not update data: ' . mysql_error());}
echo "Updated data successfully\n";
mysql_close($conn);
?>

68
Deleting Data Using PHP Script:

//delete a record into tutorial_tbl whose tutorial_id is 3.


<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
$sql = 'DELETE FROM tutorials_tbl WHERE tutorial_id=3';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not delete data: ' . mysql_error());}
echo "Deleted data successfully\n";
mysql_close($conn);
?>

69
Session 12: Designing Online Databases with phpMyAdmin

Run WAMP and phpMyAdmin

1. Run WAMP (do not forget to turn off Skype or go offline).


2. Click on the WAMP icon on the left side of the start menu (circled red) and then on appeared
menu press on phpMyAdmin (circled yellow).

phpMyAdmin will be opened in your browser. Write anything as a username (remember it)
and leave the password textbox blank and press Go.

After that you will see screen that shown below.

70
4. Creating tables in your default database.

Select your default database (it is circled with red color on the left side of the screen below).
¾Inside the textbox named “Create Table” type the name of the new table (it is circled with
black color on the figure below).
Inside the next textbox to the right, type the number of fields in the new table (again, it is
circled with black color on the figure below).
Press the Go button (as shown on the most right side of the figure below).

71
Enter the names of the fields that you would like to create in your table (they are circled in red
color on a figure below).

You need to specify data for -Type, -Length Values -Null or not Null (to set Null click on
the checkbox).
It is good to have a habit of creating one more column for some unique information (such as
ID which can be used later for connecting tables, circled blue)
Then press Save.

5. Modifying the entries of a table in your database:

5.1. Insert data in a table:

To insert into a table, select a table (like BillPay, Customer, etc. on the left side of the figure
given below)

72
Click Insert menu item (circled with red color on the figure above).
Insert data in the Value textboxes (circled with green color on the figure above).
Press the Go button (circled with black color on the figure above).

5.2. Update:

To update the entry of a table, select the table (in red color below).
Click the Browse menu item (circled in blue color on the figure above).
Click on the Pencil sign (circled with black color on a figure below) for the entry you want to
be updated.
The textbox will appear with existing data in that field.
Update (change, modify) the data in the field and click on Go button.

73
5.3. Delete:

Select the entry you want to delete from the table, and then click the delete icon in front of it
(circled with blue color in the figure above).

6. Modifying a table:

To delete a table from the database, select the database (circled with red color on the figure
below).
Select a specific table you want to be deleted (circled with black color below).
And select Drop (circled with black color below).

74
Session 13: Cookies and Sessions in PHP

Example 1: Simple demonstration of cookies and sessions in PHP

<?php

session_start();
if (isset($_SESSION["count"])) $s =
(int) $_SESSION["count"];
if (isset($_COOKIE["cookie1"])) $c1
= $_COOKIE["cookie1"];
if (isset($_COOKIE["cookie2"])) $c2
= $_COOKIE["cookie2"];
if ((!isset($s)) && (!(isset($c1)))):
setcookie("cookie1","You have visited the site 1 previous time",time()+600);

$output = "You have not visited the site before";


elseif ((!(isset($s))) && (!(isset($c2)))):
setcookie("cookie2","You have visited the site > 1 previous times",time()+600);

$output = $c1; elseif


(!(isset($s))): $output =
$c2; else:
$output = "";
endif;
if (!(isset($s))) $s
= 1;
else
$s++;

$_SESSION["count"] = $s;

?>

<!DOCTYPE html>

<html>

75
<head>

<title> PHP cookies and sessions Example </title>

</head>

<body>

<h3>
<?php
echo "Welcome to the PHP cookies and sessions Example <br/>";
if ($output):

echo "$output<br/>";
endif;
echo "You have visited $s pages in the current session"; ?>
</body>

</html>

Example 2: Write a PHP program to store current date-time in a COOKIE and display the “Last visited
on‟ date-time on the web page upon reopening of the same page.

<html >

<head>

<title>Cookies</title>

</head>

<body>

<form action="[Link]" method="post">

<p>

The last visited time was <input type="submit" name="Display Now"/>

</p>

76
</form>

</body>

</html>

//[Link] (PHP File)

<?php

$inTwoMonths=60*60*24*60+time();
setcookie('lastVisit',date("G:i-m/d/y"),$inTwoMonths);
if(isset($_COOKIE['lastVisit']))
{

$visit=$_COOKIE['lastVisit'];
echo "Your last visit was - ".$visit;
}
else echo "You've got some stale cookies!";
?>

Output:

You've got some stale cookies!

Your last visit was - 12:37 - 12/24/14

Example 3: Write a PHP program to store page views count in SESSION, to increment the count on
each refresh, and to show the count on web page.

Method 1

<?php
session_start();
session_register("count");
77
if (!isset($_SESSION)) {
$_SESSION["count"] = 0;
echo "<p>Counter initialized</p>\n"; }
else { $_SESSION["count"]++; }
echo "<p>The counter is now <b>$_SESSION[count]</b></p>".
"<p>reload this page to increment</p>";

?>

Method 2

<html >

<head> <title>SESSION PROGRAM </title> </head>

<body>

<form action="[Link]" method="post">

<p> To see page views count in session <input type="submit" name="Click Here"/>

</p>

</form> </body>

</html>

<?php

//------------------------[Link](PHP File)-----------------------------
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;

else

$_SESSION['views']=1;
echo "This page has been viewed ".$_SESSION['views']." times.";
?>

78
REFERENCES

1. Programming PHP. 3rd ed. Kevin Tatroe, Peter MacIntyre, and Rasmus Lerdorf, 2013.

2. Harvey M. Deitel. 5th ed. Internet and World Wide Web: How to Program.

3. PHP5 and MySQL Bible by Tim Converse and Joyce Park with Clark Morgan

4. PHP Cookbook, 2nd Edition By David Sklar, Adam Trachtenberg

5. PHP AND MYSQL FOR DYNAMIC WEBSITES by Larry Ullman

6. Programming the World Wide Web, various editions, by Robert W. Sebesta

7. PHP and MySQL Web Development, by Luke Welling and Laura Thomson (Developer's Library)

8. The Web Wizard's Guide to PHP by David A. Lash (AW)

9. [Link]

79

You might also like