E Commerce Lab Manual
E Commerce Lab Manual
for
CSE 326 (E-Commerce and Web Programming
Lab)
Credit: 1, Contact hour: 2 Hours Per week
Page 1 of 57
Varendra University
Department of Computer Science and Engineering
CSE 326
E-Commerce and Web Programming Laboratory
Student ID
Student Name
Section
Page 2 of 57
INDEX
SL Page
II COURSE SYLLABUS 5
Page 3 of 57
INSTRUCTIONS FOR LABORATORY
Do’s
Don’ts
Page 4 of 57
Varendra University
COURSE SYLLABUS
1 Faculty Faculty of Science & Engineering
2 Department Department of CSE
3 Program B.Sc. in Computer Science and Engineering
4 Name of Course E-Commerce and Web Programming Lab
5 Course Code CSE 326
6 Trimester and Year Spring ,2021
7 Pre-requisites CSE 313
8 Status Core Course
9 Credit Hours 2
10 Section A
11 Class Hours Not Defined
12 Class Location Not Defined
13 Name (s) of Md. Toufikul Islam
Academic staff /
Instructor(s)
14 Contact toufikul.cse@gmail.com
15 Office 532, Jahangir Sharoni, Talaimari, Rajshahi-6204
1. Lab Sheet
2. Text Book (PDF)
19 Equipment & Aids
3. XAMPP Software
4. Notepad++/Sublime Text Editor
Page 5 of 57
This course is designed to provide the student with foundational
programming knowledge and skills for application development on the
Internet. The student will learn about the Web as a development platform
20 Course Description through the use of popular representative languages (such as PHP). The
student will learn to plan, design, construct, and integrate basic server-side
components of modern web applications including databases and scripts.
The course is designed to provide the background of the following topics:
1. Technical review of the Internet and web applications
2. Overview of static and dynamic web pages
3. Overview of server-side and client-side programming
4. Server-side scripting with inline code using procedural
21 Course Objectives programming techniques
5. Programming web forms that connect with web-enabled
databases and perform basic CRUD operations
6. Programming web forms that connect with web-enabled
databases and perform basic CRUD operations
Page 6 of 57
Letter Marks Grade Letter Marks Grade Point
Grade % Point Grade %
A+ 80-100 4.00 C+ (Plus) 50-54 2.50
25 Grading Policy (Plus) 75-79
A 3.75 C (Plain) 45-49 2.25
A-
(Plain) 70-74 3.50 D (Plain) 40-44 2.00
B+
(Minus) 65-69 3.25 F (Fail) <40 0.00
B
(Plus) 60-64 3.00
B-
(Plain) 55-59 2.75
(Minus)
1. Lab Reports
Report on previous Experiment must be submitted before the beginning of
new experiment. A bonus may be obtained if a student submits a neat, clean
and complete lab report.
2. Examination
There will be a lab exam at the end of the semester that will be closed book.
4. Counseling
Students are expected to follow the counseling hours posted. In case of
Additional Course emergency/unavoidable situations, students can e-mail me to make an
26
Policies
appointment. Students are regularly advised to check the piazza course page
for updates/materials.
In case of absence in the mid/final exam for medical grounds, the student
must also get his/her application forwarded by the head of the department
before a make-up exam can be taken.
Page 7 of 57
Lab (1): HTML Basic, Headings,Paragraph,Text Formatting and Quotations
HTML Basics:
All HTML documents must start with a document type declaration: <!DOCTYPE
html>.
The HTML document itself begins with <html> and ends with </html>.
The visible part of the HTML document is between <body> and </body>.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
<html>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>
<html>
<body>
<p>Welcome to Web Lab.</p>
<p>Eight Semester 2019.</p>
</body>
</html>
Page 8 of 57
[Task3]. HTML <pre> Element
The HTML <pre> element defines preformatted text. The text inside a <pre> element is
displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks:
<html>
<body>
<p>The pre tag preserves both spaces and line breaks:</p>
<pre>
My Bonnie lies over the ocean.
My Bonnie lies over the sea.
My Bonnie lies over the ocean.
</pre>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>This is<br>a paragraph<br>with line breaks</p>
</body>
</html>
<html>
<body>
<h1>HTML</h1>
<p>HTML is a language for describing web pages.</p>
<hr>
<h1>CSS</h1>
<p>CSS defines ow to display HTML elements.</p>
</body>
</html>
Page 9 of 57
Formatting elements were designed to display special types of text:
<html>
<body>
<p>This text is normal.</p>
<p><b>This text is bold.</b></p>
<p><i>This text is italic</i></p>
<p><em>This text is emphasized</em></p>
<p>This is a <u>parragraph</u>.</p>
<p>HTML <small>Small</small> Formatting</p>
<p>HTML <mark>Marked</mark> Formatting</p>
<p>My favorite color is <del>blue</del> red.</p>
<p>My favorite <ins>color</ins> is red.</p>
<p>This is <sub>subscripted</sub> text.</p>
<p>This is <sup>superscripted</sup> text.</p>
<p> <b><i>This text is bold and italic</i></b></p>
</body>
<html>
Page 10 of 57
Non-breaking Space
A common character entity used in HTML is the non-breaking space: or  
A non-breaking space is a space that will not break into a new line. Two words separated by a
non- breaking space will stick together (not break into a new line).
Examples:
<p> 10 km/h </p>
If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to
your text, you can use the character entity.
<html>
<body>
<p>WWF's goal is to: <q>Build a future where people live in harmony with
nature.</q></p>
<body>
<html>
The HTML <blockquote> element defines a section that is quoted from another source.
Browsers usually indent <blockquote> elements.
<html>
<body>
<p>Browsers usually indent blockquote elements.</p>
<blockquote cite="http://www.worldwildlife.org/who/index.html">
For 50 years, WWF has been protecting the future of nature.
The world's leading conservation organization,
WWF works in 100 countries and is supported by
1.2 million members in the United States and
close to 5 million globally.
</blockquote>
</body>
</html>
Page 11 of 57
The HTML <address> element defines contact information (author/owner) of a document or
an article. The <address> element is usually displayed in italic. Most browsers will add a line
break before and after the element.
<html>
<body>
<p>The HTML address element defines contact information of a document or article.</p>
<address>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland<br>
USA
</address>
</body>
</html>
Page 12 of 57
Lab (2): HTML Lists and Images
In HTML, images (Gif,JPG, PNG) are defined with the <img> tag.The <img> tag is empty, it
contains attributes only, and does not have a closing tag. The src attribute specifies the URL
of the image:
<img src="url" alt="some_text" width="width" height="height">
[Task1]. Display images from web site
<html>
<body>
<img src="http://www.w3schools.com/images/w3schools_green.jpg">
</body>
</html>
[Task2]. Display images from the same folder of the web page
<html>
<body>
<img src="html.gif">
</body>
</html>
<html>
<body>
<imgsrc="html5.gif" alt="HTML5 Icon" width="128" height="128">
</body>
</html>
Page 13 of 57
Adding Lists to a Web Page
There are three basic types of HTML lists: ordered list, unordered list and definition list.
[Task5]. The ordered list in HTML
The ordered list which is created by the ol Element that begins with the <ol> tag and ends
with a closing </ol> tag. The attributes required: type attribute and the start attribute.
<html>
<body>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
</body>
</html
Page 14 of 57
Lowercase Roman Numbers:
<oltype="i">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
HTML <ol> start Attribute: define the start value of the list.
<html>
<body>
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="I" start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
</body>
</html>
<html>
<body>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</body>
</html>
In unordered list, Type Attribute can take one of the next values:
Page 15 of 57
Disc: Circle:
<ultype="disc"> <ul type="circle">
<li>Coffee</li> <li>Coffee</li>
<li>Tea</li> <li>Tea</li>
<li>Milk</li> <li>Milk</li>
</ul> </ul>
Square: None:
<ultype="none">
<ul type="square">
<li>Coffee</li>
<li>Coffee</li>
<li>Tea</li>
<li>Tea</li>
<li>Milk</li>
<li>Milk</li>
</ul>
</ul>
<html>
<body>
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
</body>
</html>
HTML Links
HTML links are hyperlinks. You can click on a link and jump to another document. A link
does not have to be text. It can be an image or any other HTML element.
In HTML, links are defined with the <a> tag:
<a href="url">link text</a>
<html>
<body>
<p><a href="http://www.w3schools.com/html/">Visit our HTML tutorial</a></p>
</body>
</html>
The target attribute specifies where to open the linked document. The target attribute can have
one of the following values:
This example will open the linked document in a new browser window/tab:
Page 17 of 57
Going from one Location into another within the Same Web Page
<html>
<body>
<p><a href="#C4">Jump to Chapter 4</a></p>
<h2>Chapter 1</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 2</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 3</h2>
<p>This chapter explains ba bla bla</p>
<h2 id="C4">Chapter 4</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 5</h2>
<p>This chapter explains ba bla bla</p>
</body>
</html>
Image as Link
<html>
<body>
<p>This is an email link:<a href="mailto:asmakhtoom@yahoo.com?Subject=Hello
again">SendMail</a>
</p>
</body>
</html>
A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).
The <div> element is a block-level element.
Page 18 of 57
<html>
<body>
<div>Hello</div>
<div>World</div>
<p>The DIV element is a block element, and will start on a new line.</p>
</body>
</html>
Inline element
An inline element does not start on a new line and only takes up as much width as necessary.
The <span> element is an inline element.
<html>
<body>
<span>Hello</span>
<span>World</span>
<p>The SPAN element is an inline element, and will not start on a new line.</p>
</body>
</html>
Page 19 of 57
Lab (4) : HTML Tables
An HTML table is defined with the <table> tag. Each table row is defined with the <tr> tag.
A table header is defined with the <th> tag. By default, table headings are bold and centered.
A table data/cell is defined with the <td> tag.
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Note: The <td> elements are the data containers of the table.
They can contain all sorts of HTML elements; text, images, lists, other tables, etc.
An HTML Table with a Border Attribute
If you do not specify a border for the table, it will be displayed without borders.
A border can be added using the border attribute:
Page 20 of 57
[Task1]. Double Border Table, Coloring and width
<html>
<head>
<style>
table, th, td {
border: solid;
border-width: 3px; border-color : red;}
th{color:green;}
td{color:blue;}
</style>
</head>
<body>
……… write the code of your table here.
</body>
</html>
<head>
<style>
table, th, td {
border: solid ;
border-collapse: collapse; //single line border
border-width: 3px;
border-color : red;}
th { color : green;}
td { color : blue;}
</style>
</head>
Or try this
<table border="3" bordercolor="red" bgcolor="green" cellspacing="5" cellpadding="3">
Page 21 of 57
[Task4]. Table caption and cell coloring using bgcolor
The <caption> tag defines a table caption. The <caption> tag must be inserted
immediately after the <table> tag. Note: You can specify only one caption per
table.
bgcolor attribute allow you to give a color to the cell or to the row.
<tr bgcolor=”blue”>
<th bgcolor=”red” >
<table>
<caption>Student Marks</caption>
<tr>
<th bgcolor=”red” >Name</th>
<th bgcolor=”red” >Mark</th>
</tr>
<tr>
<td>Ali</td>
<td>30</td>
</tr>
</table>
<table style="width:100%">
<tr>
<th>Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>555 77 854</td>
</tr>
<tr>
<td>555 77 855</td>
</tr>
</table>
Page 22 of 57
Example2: colspan attribute
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>555 77 854</td>
<td>555 77 855</td>
</tr>
</table>
Page 23 of 57
Lab (5) : HTML Forms
The HTML <form> element defines a form that is used to collect user input. An HTML
form contains form elements. Form elements are different types of input elements, like text
fields, checkboxes, radio buttons, submit buttons, and more.
<html>
<body>
<form action="/action_page.php"> First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called
"/action_page.php".</p>
</body>
</html>
Form Attributes
Attribute Usage
Action Attribute The action attribute defines the action to be performed when the
form is submitted
Specifies the HTTP method (GET or POST) to be used when
Method Attribute
submitting the form data.
Each input field must have a name attribute to be submitted. If the
Name Attribute
name attribute is omitted, the data of that input field will not be
sent at all.
enctype Attribute Specifies how the form-data should be encoded when submitting it
to the server. can be used only if method="post".
1. Action attribute
Normally, the form data is sent to a web page on the server when the user clicks on the submit
button. In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the form data:
<form action="/action_page.php">
If the action attribute is omitted, the action is set to the current page.
Page 24 of 57
2. Method Attribute
The method attribute specifies the HTTP method (GET or POST) to be used when submitting
the form data:
<form action="/action_page.php" method="get">
when GET is used, the submitted form data will be visible in the page address field:
/action_page.php?firstname=Mickey&lastname=Mouse
or:
<form action="/action_page.php" method="post">
GET must NOT be used when sending sensitive information! GET is best suited for short,
non-sensitive, amounts of data, because it has size limitations too.
Always use POST if the form data contains sensitive or personal information. The POST
method does not display the submitted form data in the page address field. POST has no size
limitations, and can be used to send large amounts of data.
3. Enctype method
Value Description
application/x-www-form- Default. All characters are encoded before sent (spaces are
urlencoded converted to "+" symbols, and special characters are
converted to ASCII HEX values)
multipart/form-data No characters are encoded. This value is required when you
are using forms that have a file upload control
The <input> element is the most important form element. The <input> element can be
displayed in several ways, depending on the type attribute.
Type Description
text Defines a one-line text input field
radio Defines a radio button (selecting one of many choices)
submit Defines a submit button (for submitting the form)
checkbox Defines a checkbox (selecting many choices)
password Defines a password field (characters are masked)
Button Defines a clickable button
Page 25 of 57
reset Defines a reset button (resets all form values to default values)
image Defines an image as the submit button
file Defines a file-select field and a "Browse..." button (for file uploads)
hidden Defines a hidden input field
<form>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</form>
<form>
User name:<br>
<input type="text" name="username"><br>
User password:<br>
<input type="password" name="psw">
</form>
Page 26 of 57
Input Type: radio
Input Restrictions
Here is a list of some common input restrictions (some are new in HTML5):
Attribute Description
disabled Specifies that an input field should be disabled
max Specifies the maximum value for an input field
maxlength Specifies the maximum number of character for an input field
min Specifies the minimum value for an input field
pattern Specifies a regular expression to check the input value against
readonly Specifies that an input field is read only (cannot be changed)
required Specifies that an input field is required (must be filled out)
size Specifies the width (in characters) of an input field
step Specifies the legal number intervals for an input field
value Specifies the default value for an input field
Page 27 of 57
Input Type: date
The <input type="date"> is used for input fields that should contain a date.
Depending on browser support, a date picker can show up in the input field.
<form>
Birthday:
<input type="date" name="bday">
</form>
The <input type="file"> defines a file select field and a “Browse” button for file upload.
<form action="/action_page.php">
Select a file: <input type="file" name="img">
<input type="submit">
</form>
The <textarea> Element
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
Page 29 of 57
Grouping Form Data with <fieldset>
The <fieldset> element groups related data in a form.
The <legend> element defines a caption for the <fieldset> element.
<form action="action_page.php">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
Page 30 of 57
Lab (6) : CSS and Bootstrap
The most used css properties used in a web page are as follows:
1) Color
2) Background
3) Border
4) Margin
5) Padding
6) Font
7) Links
8) Lists
9) Tables
10) Display
11) Position
12) Float
13) Align
14) Navigation Bar
15) Dropdowns
Bootstrap
Bootstrap is an open source toolkit for developing with HTML, CSS, and JS. Quickly
prototype your ideas or build your entire app with responsive grid system, extensive prebuilt
components, and powerful plugins built on jQuery.
Page 31 of 57
Lab (7) : PHP Basics
PHP is a server- side language which means that PHP script will run on the web server and
after execution the result will be sent to the browser as xhtml.
PHP Syntax:
<?php ………….?>
Each line code must end with ;
The file saved with .php extension.
Case-Sensitivity in PHP
Comments in PHP
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can
be used in expressions. echo can take multiple parameters (although such usage is rare) while
print can take one argument. echo is marginally faster than print.
1. print statement:
print (string); is used to print a single string and can contain html tags, the ( ) are
optional. Always return 1.
Page 32 of 57
[Task1]. Write the next code and determine what the output is?
2. echo statement:
echo (str1,str2,str3,…..)
Is used to output one or more string and return nothing. Can
contain html tags.
If it used to print single string the ( ) are optional.
If it used to print more than one string don’t use ( ).
[Task3]. Write the next code and determine what the output is?
<?php
echo ("<hr>");
echo ("<p><b>V University</b></p>");
echo "hello<br/>";
echo "One",”Two”,”Three”;
?>
Page 33 of 57
Variables in PHP
2. Declaring Variables.
A variable starts with the $ sign, followed by the name of the variable. When you assign a text
value to a variable, put quotes around the value.
[Task4]. Write the next code and determine what the output is?
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
$z= true;
$w=null;
echo $txt;
echo "<br>";
echo $x;
echo "<br>"
echo "$x"; // it will not be used as string ,it is ……
echo "<br>";
echo $y;
echo "<br>";
echo $z;
echo "<br>";
echo $w;
?>
Page 34 of 57
3. Constants Declaration.
Constants are like variables except that once they are defined they cannot be changed or
undefined.
A valid constant name starts with a letter or underscore (no $ sign before the constant name)
to create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
<?php Output
// case-sensitive constant name
define("GREETING", "Welcome to VU!");
echo GREETING;
echo "GREETING"; // not as variable it will print the string
?>
<?php Output
// case-insensitive constant name
define("GREETING","Welcome to VU!", true);
echo greeting;
?>
Page 35 of 57
Concatenation in PHP
Functions in PHP
functions Syntax
function functionName() {
code to be executed;
}
<?php Output
function familyName($fname) {
echo "$fname Nsour.<br>";
}
familyName("Ahmad"); familyName("Abdullah");
familyName("Leen"); familyName("Tamara");
familyName("Noor");
?>
Page 36 of 57
Example3. Function with parameters
<?php
function familyName($fname, $year) {
echo "$fname Al-Abadi. Born in $year <br>";
}
familyName("Ayman", "1975");
familyName("Jumana", "1978");
familyName("Fadi", "1983");
?>
Output
<?php Output
function countNum($n) {
echo "$n . <br>";
}
for($i=1; $i<=10 ; $i++) countNum($i);
?>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); //if there is no default it will cause error. setHeight(135);
setHeight(80);
?>
Output
Page 37 of 57
Example6. PHP Functions - Returning values
<?php Output
function sum($x,$y)
$z = $x + $y; return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?
var_dump() function
The PHP var_dump() function returns the data type and value:
Output
<?php
$x =5985;
var_dump($x);
?>
Arrays in PHP
1. Indexed Arrays
Arrays with a numeric index .There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
1. $cars = array("Volvo", "BMW", "Toyota");
or
2. the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example1.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2]. ".";
?>
Output
Page 38 of 57
The count Function
<?php
$cars =array("Volvo","BMW","Toyota");
echocount($cars);
?>
To loop through and print all the values of an indexed array, you could use for loop.
Example3.
<?php Output
$cars =array("Volvo","BMW","Toyota");
$arrlength = count($cars);
2. Associative Arrays
Associative arrays are arrays that use named keys that you assign to them. There are two ways
to create an associative array:
1. $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
Page 39 of 57
2. $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script; key can be number or string
The value can be of any type.
Example. $color=array(1=>”Red”,”b”=>”blue”,”g”=>”green”);
Example1.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Output
Example2.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";
}
?>
Output
Page 40 of 57
Lab (8) :Form Handling in PHP
Form Handling
Example1.
Part1. Create this web page.
form.html
<html>
<head>
<title>Php contact form</title>
</head>
<body>
<form name="contact" method="post" action="one.php">
Name:<input type="text" size=25 name="uname" /><br/>
Email:<input type="text" size=25 name="email" /><br/>
Phone:<input type="text" size=25 name="phone" /><br/>
Message:<textarea name="message" rows="5" cols="35"></textarea><br/>
<input type="submit" value="Send" name="send"/>
</form>
</body>
</html>
Page 41 of 57
Part2. Create php file called “one.php” in www root to hold the data sent by submit button.
To display the submitted data you could simply echo all the variables.
<?php
$name= $_POST['uname'];
echo "PHP file received the Name". " ". $name;
?>
<br>
Your email address is: <?php echo $_POST["email"]; ?>
Example 2:
Modify the one.php file as follows:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
$name= $_POST['uname'];
else
$name= $_GET['uname'];
echo "PHP file received the Name". " ". $name;
?>
Example 3:
Modify the one.php file as follows:
<?php
$name=$_REQUEST['uname'];
echo $name;
?>
Form Validation
Create the next form first in a "test_form.php" file.
Page 42 of 57
Example1:
<html>
<body>
<?php
$nameErr = "";
$passErr = "" ;
$genderErr = "" ;
$name = "";
$pass = "";
$gender= "" ;
if ($_SERVER["REQUEST_METHOD"] == "POST")
{ if (empty($_POST["name"]))
$nameErr = "Name is required";
else
$name= $_POST['name'];
if (empty($_POST["pass"]))
$passErr = "password is required";
else
{
$p = $_POST['pass'];
if(strlen($p)>8)
$pass = $p;
else
$passErr ="Password must be greater than 8"; }
if (empty($_POST["gender"]))
$genderErr = "Gender is required";
else
$gender = $_POST["gender"];}
?>
Page 43 of 57
Gender:
<input type="radio" name="gender" <?php if (isset($gender)
&& $gender=="female") echo "checked";?> value="female"
/>Female
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="male") echo "checked";?> value="male" />Male
<font color="red">* <?php echo $genderErr;?> </font>
<br>
<input type="submit" name="submit" value="Send" />
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name."<br/>";
echo $pass."<br/>";
echo $gender;?>
</body>
</html>
File Upload
1. Create The HTML Form
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$imageFileType holds the file extension of the file
Page 44 of 57
Note:You will need to create a new directory called "uploads" in the directory where
"upload.php" file resides. The uploaded files will be saved there.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
Page 45 of 57
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Page 46 of 57
Lab (9) : PHP Sessions
Example1
In the example below, we will create a simple page-views counter. The isset() function
checks if the "views" variable has already been set. If "views" has been set, we can increment
our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:
view.php
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']= $_SESSION['views']+1;
else
$_SESSION['views']= 1;
echo "Views=". $_SESSION['views'];
?>
<html>
<body>Hello there</body>
</html>
The first time you run this script on a freshly opened browser the if statement will fail because
no session variable views would have been stored yet. However, if you refreshed the page the
if statement would be true and the counter would increment by one. Each time you reran this
script you would see an increase in views by one.
Example2:
First, create the following PHP File:
mypage.php
<?php
// this starts the session
session_start();
// this sets variables in the session
$_SESSION['color']='red';
// this sets variables in the session
$_SESSION['color']='red';
print "Done";
?>
Page 47 of 57
Now we are going to make a second page. We again will start with session_start() (we need
this on every page) - and we will access the session information we set on our first page.
Notice we aren't passing any variable; they are all stored in the session.
mypage2.php
<?php
session_start();
echo "Our color value is ".$_SESSION['color'];
echo " Our size value is ".$_SESSION['size'];
echo " Our shape value is ".$_SESSION['shape']; ?>
You can also store an array within the session array. Go back to our mypage.php file
and edit it slightly to do this:
<?php
session_start();
// makes an array
$colors=array('red', 'yellow', 'blue');
// adds it to our session
$_SESSION['color']=$colors;
$_SESSION['size']='small';
$_SESSION['shape']='round';
print "Done"; ?>
<?php
// you have to open the session to be able to modify or remove it
session_start();
// to change a variable, just overwrite it
$_SESSION['size']='large';
//you can remove a single variable in the session
unset($_SESSION['shape']);
// or this would remove all the variables in the session, but not the session //itself
session_unset();
// this would destroy the session variables
session_destroy(); ?>
Note: By default, a session lasts until the user closes the browse
Page 48 of 57
Lab (10) :Databases with SQL and PHP
Database Creation
Create database called Persons.
Create Table called contacts like this:
<html>
<head><title>Persons: Main Page </title></head>
<body>
<h1>Persons Information Application </h1>
<p> Welcome to my first Web Application </p>
<p> Next is the main menu of this Application
<ul>
<li><a href="./index.html">Home page </a></li>
<li><a href="./show_all.php">Show all contacts </a></li>
</ul>
</p>
</body>
</html>
<html>
<head><title>Persons: Show All Contacts</title></head>
<body>
<h1>Persons Application: All my contacts </h1>
<p>Next is a alist of all my contacts </p>
<?php
$con=mysqli_connect("localhost","root","","Persons");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
Page 49 of 57
else{
echo "Connected successfully"; }
$result = mysqli_query($con,"SELECT * FROM contacts");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
<br /><hr />
<p> Go back to <a href="./index.html">Home page </a></p>
</body>
</html>
<html>
<head><title>Persons: Show All Contacts</title></head>
<body><h1>Persons Application: All my contacts </h1>
<p>Next is a alist of all my contacts </p>
<?php
$con=mysqli_connect("localhost","root","","Persons");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
else{
echo "Connected successfully"; }
$result = mysqli_query($con,"SELECT * FROM contacts");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>PhoneNumber</th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['PhoneNumber'] . "</td>";
echo "</tr>";
Page 50 of 57
}
echo "</table>";
mysqli_close($con); ?>
<br /><hr />
<p> Go back to <a href="./index.html">Home page </a></li></p>
</body>
</html>
Example:
We will create an HTML form that can be used to add new records to the "Persons" table.
<html>
<body>
<form name="new_form" method="post" action="insert.php" >
Firstname: <input type="text" name="firstname" /> Lastname: <input type="text"
name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
<?php
$con=mysqli_connect("localhost","root","","Persons");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$firstname = $_POST['firstname'];
$lastname =$_POST['lastname'];
$age = $_POST['age'];
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$firstname',
'$lastname', $age)";
if (!mysqli_query($con, $sql))
die('Error: ' . mysqli_error($con));
echo "1 record added";
mysqli_close($con);
?>
Page 51 of 57
Lab (11) : PHP and MySql CRUD
1. Create database using PHP code.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error; }
$conn->close();
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Page 52 of 57
// sql to create table
$sql = "CREATE TABLE Students (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL,
email VARCHAR(50), reg_date TIMESTAMP )";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Students (firstname, lastname, email) VALUES ('John', 'Doe',
'john@example.com')";
$conn->close();
?>
Page 53 of 57
4. Insert Multiple Records into MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Students (firstname, lastname, email) VALUES ('John', 'Doe',
'john@example.com');";
$sql .= "INSERT INTO Students (firstname, lastname, email) VALUES ('Mary', 'Moe',
'mary@example.com');";
$sql .= "INSERT INTO Students (firstname, lastname, email) VALUES ('Julie', 'Dooley',
'julie@example.com')";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
Page 54 of 57
die("Connection failed: " . $conn->connect_error); }
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
Page 55 of 57
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id=$_GET["id"];
// sql to delete a record
$sql = "DELETE FROM Students WHERE id='$id' ";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id=$_GET["id"];
Page 56 of 57
Lab (12) : FINAL LAB EXAMINATION
Task 1: Quiz
Task 2: Two Lab Problem Solving. (Include GUI)
Task 3: Viva Voce
Task 4: Project Demonstration
Page 57 of 57