We Blab Manual
We Blab Manual
net/publication/320556418
CITATIONS READS
0 5,019
1 author:
Asma'a Khtoom
Al-Balqa' Applied University
7 PUBLICATIONS 27 CITATIONS
SEE PROFILE
Some of the authors of this publication are also working on these related projects:
All content following this page was uploaded by Asma'a Khtoom on 22 October 2017.
Web Applications
Development Lab
[Lab Manual]
Installing WAMPServer
By doing so, you install the following software: Apache : 2.4.4 MySQL :
5.6.12 PHP : 5.4.16 PHPMyAdmin : 4.0.4 SqlBuddy : 1.3.3 XDebug : 2.2.3
If the “W” icon is red or yellow, then this means that the software is not
properly configured. Red icon indicates that all services are put offline. Yellow
icon indicates that some services are offline. Green icon means that all
services are online.
To turn those services on or off, click on the “W” icon once. You should see
the next pop up menu.
Using this window, you should be able to start all services, stop all services or
restart all services. Or you can put the server on the offline mode.
You may need to disable the IIS webserver on your machine. To do so:
1. Go to “Control Panel”
We will be using this text editor for coding in PHP and html.
Download and install the latest version of Notepad++ into your local machine.
Viewing the WWW root and Showing files extensions under Windows
The WWW root is the folder where you will be saving your
html and php project files. The path to this folder is
C:\wamp\www, use your Windows Explorer to view the
contents of this folder.
Later in this lab, you will be creating html and php file for
your lab tasks. Those must carry the extensions “.html” and
“.php”.
HTML Basics
1. All HTML documents must start with a document type declaration: <!DOCTYPE html>.
2. The HTML document itself begins with <html> and ends with </html>.
3. The visible part of the HTML document is between <body> and </body>.
Try This
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
1. Use the Windows Notepad++ to type the following html code and save it in a file named
“testing_html.html”.
2. Store this file under the following path into your machine: C:\wamp\www\lab1
3. To edit the file using Notepad++, right click on the file icon and choose “Edit with Notepad++”.
<html>
<body>
</body> </html>
c. You show be able to see the “lab1” folder under “Your Project” in the default localhost page.
<h1> defines the most important heading. <h6> defines the least important heading, try this code:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
The <br> tag is an empty tag, which means that it has no end tag.
Use <br> if you want a line break (a new line) without starting a new paragraph, try next code:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
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:
<!DOCTYPE html>
<html>
<body>
<pre>
</pre>
</body>
</html>
HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
Try this:
<html>
<body>
<p>This is a <u>parragraph</u>.</p>
</body>
</html>
Some characters are reserved in HTML. If you use the less than (<) or greater than (>) signs in your text,
the browser might mix them with tags. Character entities are used to display reserved characters in
HTML.
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:
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.
Cout<<i;
Use the <hr> tag to draw horizontal line. Try the next code:
<!DOCTYPE html>
<html>
<body>
<h1>HTML</h1>
<hr>
<h1>CSS</h1>
2. Creating Lists
Ordered Lists
Unordered Lists
Definition Lists
Nesting Lists
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:
Tasks:
<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>
<img src="/images/html.gif">
</body>
</html>
The alt attribute provides an alternate text for an image, if the user for some reason cannot view it.
You can use the width and height attributes to specify the width and height of an image in pixels.
<html>
<body>
</body>
</html>
There are three basic types of HTML lists: ordered list, unordered list and definition list.
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>
Type Description
type="1" The list items will be numbered with numbers (default)
type="A" The list items will be numbered with uppercase letters
type="a" The list items will be numbered with lowercase letters
type="I" The list items will be numbered with uppercase roman numbers
type="i" The list items will be numbered with lowercase roman numbers
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Uppercase Letters:
<ol type="A">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Lowercase Letters:
<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="I">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ol type="i">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<html><body>
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
</body> </html>
The unordered list which is created by the ul Element that begins with the <ul> tag and
ends with </ul>. The attributes required: just the type attribute.
<html><body>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</body></html>
Disc:
<ul type="disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Circle:
<ul type="circle">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Square:
<ul type="square">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
None:
<ul type="none">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
The definition list: The list of terms and their meanings is called a definition list. This list is
created by the dl Element that starts with the <dl> and ends with </dl>. Inside this element
two elements are used. The <dt> element which goes in front of each term to be defined and a
<dd> element that is used in front of each definition.
<html> <body>
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl> </body></html>
Assignments:
1. Write the required code to create the following output: 2. Observe the output of the following piece of code:
<html>
<body>
<h3>Vegetables</h3>
<ul>
<li>Cucumbers</li>
<li>Carrots:
<ul>
<li>Orange Carrot</li>
<li>White Carrot</li>
</ul>
</li>
<li>Spinach</li> </ul>
</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.
The link text is the visible part, clicking on the link text will send you to the specified address.
Try this:
<html>
<body>
</body>
</html>
This example will open the linked document in a new browser window/tab:
Try this
<a href="http://www.bau.edu.jo/" target="_blank">Visit BAU!</a>
Going from one Location into another within the Same Web Page
<html> <body>
<h2>Chapter 1</h2>
<h2>Chapter 2</h2>
<h2>Chapter 3</h2>
Instructor: Asma’a Khtoom. 2
<p>This chapter explains ba bla bla</p>
<h2>Chapter 5</h2>
<h2>Chapter 6</h2>
</body>
</html>
Image as Link
Try this
<a href=" http://www.bau.edu.jo/">
</a>
Image Maps
Value Description
<html>
<body>
<map name="planetmap">
</map>
</body></html>
<html><body>
</p></body></html>
News page: include nested lists (orderd and unordered list) about any news.
Q2. Write the code to view the next page. Each link open location as follow:
Pictures: open your computer picture folder.
Social: open html page contain three ordered list with three images about social media sites.
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>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Asma</td>
<td>Mohammad</td>
<td>33</td>
</tr>
<tr>
<td>Ahmad</td>
<td>Naji</td>
<td>46</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.
<html>
<head>
<style>
border-width: 3px;
border-color : red;}
th { color : green;}
td { color : blue;}
</style>
</head>
<body>
</body>
</html>
Ex. <head>
border: solid ;
border-width: 3px;
border-color : red;}
th { color : green;}
Cell padding specifies the space between the cell content and its borders.
The cellspacing attribute specifies the space, in pixels, between cells.
……
</table>
Or try this
bgcolor attribute allow you to give a color to the cell or to the row.
<tr bgcolor=”blue”>
<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 >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td align="left">$100</td>
</tr>
<tr>
<td>February</td>
<td align="center">$80</td>
</tr> </table>
6. valign Attribute
The valign attribute specifies the vertical alignment of the content in a cell.
Try this
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td valign="bottom">January</td>
<td valign="bottom">$100</td>
</tr>
</table>
rowspan: This attribute specifies the number of rows a cell should merged.
colspan: This attribute specifies the number of columns a cell should merged.
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
<td rowspan="2">$50</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
<table>
<tr>
<td colspan="2">Sum: $180</td>
</tr>
</table>
1. A table that has a cell with an image and text in its content.
1. iframe Attributes
Task. Create 3 html files : mm.html , bb.html and cc.html , write the next code in each one:
1. mm.html
3. cc.html
<h1> Hello with iframes</h1>
Homework:
<html>
<body>
<tr>
</tr>
<tr>
<td rowspan="3">M<br>o<br>n<br>d<br>a<br>y</td>
<td valign="top"><b>Breakfast</b></td>
</tr>
<tr>
<td valign="top"><b>Lunch</b></td>
<td>Tuna sandwich<br>Apple</td>
</tr>
<td valign="top"><b>Dinner</b></td>
</tr>
</table>
</body>
</html>
Table1.
2.
Table2.
<html> <body>
<?php
echo "hello";
?>
</body></html>
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>
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.
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.
2. Method Attribute
The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data:
when GET is used, the submitted form data will be visible in the page address
field:
/action_page.php?firstname=Mickey&lastname=Mouse
or:
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.
Value Description
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
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
Try this.
<input type="radio"> defines a radio button. Radio buttons let a user select ONE of a
limited number of choices.
Try this.
<form>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
The output:
</body>
</html>
<input type="submit"> defines a button for submitting the form data to a form-
handler.
The form-handler is typically a server page with a script for processing input data.
Try this.
<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>
File
<html><body>
<form action="/action_page.php">
Select a file: <input type="file" name="img">
</body></html>
6. hidden
<html>
<body>
<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
<input type="hidden" name="country" value="Norway">
<input type="submit" value="Submit">
</form>
</body>
</html
7. image submit
<html>
<body>
<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="image" src="img_submit.gif" alt="Submit" width="48"
height="48">
</form>
</body>
</html>
8. Password
<html><body>
<form action="/action_page.php">
</form>
</body></html>
9. Reset button
<form action="/action_page.php">
</form>
10. Buttons
<form>
</form>
textarea Element
<html>
<body>
<form action="/action_page.php">
<textarea name="message" rows="10" cols="30">The cat
was playing in the garden.</textarea>
<br>
<input type="submit">
</form>
</body>
</html>
<form action="/action_page.php">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br><br>
<input type="submit">
</form>
Try this.
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 ………….?>
Case-Sensitivity in PHP
Comments in PHP
1. print statement:
int print(string);
Is used to print a single string and can contain html tags, the ( ) are optional.
Always return 1.
Task1. Write the next code and determine what the output is?
<?php
print "<hr>";
print "<p><b>BAU University</b></p>";
print "hello";
print "Welcome";
?>
2. echo statements:
void echo(st1,st2,st3,……….);
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 ( ).
<?php
echo ("<hr>");
echo ("<p><b>BAU University</b></p>");
echo "hello<br/>";
echo "One",”Two”,”Three”;
?>
Variables in PHP
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
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 $y;
echo "<br>";
echo $z;
echo "<br>";
echo $w;
?>
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
<?php Output
// case-sensitive constant name
define("GREETING", "Welcome to BAU!");
echo GREETING;
Echo "GREETING"; // not as variable it will print the string
?>
<?php Output
// case-insensitive constant name
define("GREETING", "Welcome to BAU!", true);
echo greeting;
?>
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
Concatenation in PHP
Functions in PHP
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");
?>
<?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);
?>
The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:
var_dump() function
The PHP var_dump() function returns the data type and value:
Output
<?php
$x = 5985;
var_dump($x);
?>
1. Local scope
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
2. Global scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
Example1:
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
Output
Method1. The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example2:
Output
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; //?>
Method2. PHP also stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable. This array is also accessible from within functions
and can be used to update global variables directly.
Example3:
<?php Output
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; //
?>
3. Static scope
<?php Output
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
4. Parameter scope
The parameter is local to function.
Example:
Output
<?php
function mm($value) {
$value=$value*10;
return $value;}
mm(2);
echo value;// error
?>
Arrays in PHP
1. Indexed Arrays
Arrays with a numeric index .There are two ways to create indexed arrays:
1. The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or
Example1.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2]
. ".";
?>
Output
Example2.
Output
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
To loop through and print all the values of an indexed array, you could use for loop.
Example3.
Output
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
foreach($age as $x) {
echo $x; echo "<br>";}?>
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:
or:
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
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
To loop through and print all the values of an associative array, you could use a
foreach loop.
Example2.
<?php Output
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>
Syntax
empty(var_name)
Return value
FALSE if var_name has a non-empty and non-zero value.
<?php
$ivar1=0;
$istr1='Learning empty';
if (empty($ivar1))
{
echo '$ivar1'." is empty or 0. <br />";
}
else
{
echo '$ivar1'." is not empty or 0. <br />";
String Functions
The strip_tags() function strips a string from HTML, XML, and PHP
tags. all tags will be removed.
<?php
echo strip_tags("Hello <b>world!</b>");
?>
<?php
echo strip_tags("Hello <b><i>world!</i></b>","<b>");
?>
Output:
<?php
echo stripslashes("Who\'s Peter Griffin?");
?>
Output:
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
Output:
<?php
echo strpos("I love php, I love php too!","php");
?>
Output:
<?php
print_r(str_split("Hello"));// print_r(string): Return an
array containing the keys:
?>
Output:
<?php
print_r(str_split("Hello",3));
?>
Output:
<?php
echo str_replace("world","Peter","Hello world!");
?>
<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
Output:
<html>
<body>
<?php
$arr= array("blue","red","green","yellow");
print_r(str_ireplace("RED","pink",$arr,$i)); //Case-
insensitive
echo "<br>" . "Replacements:$i";
?>
</body>
</html>
Output:
Example1. Convert the predefined characters "<" (less than) and ">" (greater
than) to HTML entities:
<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>
Output:
<!DOCTYPE html>
<html>
<body>
This is some <b>bold</b> text.
</body>
</html>
Form Handling
Example1.
Part1. Create this web page.
c.html
<html><head>
</head> <body>
</body></html>
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>
Output:
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; ?>
<?php
$name=$_REQUEST['uname'];
Task1: Write a code to check if the user enter the name or not. If the name entered print
it, if not ask the user to enter it.
Task2. Design a form to enter the user name and age, then when you submit the form
the output like the next one appeared in anew page.
Welcome Asma’a!
Name: *
Password: *
Submit
You’re Input:
<html>
<body>
<?php
$nameErr = "";
$passErr = "" ;
$name = "";
$pass = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{ if (empty($_POST["name"]))
else
$name= $_POST['name'];
if (empty($_POST["pass"]))
else
{ $p = $_POST['pass'];
if(strlen($p)>8)
$pass = $p;
else
<form method="post"
</form>
<?php
echo $name."<br/>";
echo $pass;?>
</body>
</html>
Example2
Validate that the name and password must only contain letters and whitespace.
Create a function that will do all the checking for us (which is much more convenient
than writing the same code over and over again).
<html><body>
<?php
$nameErr = "";
$passErr = "";
$name = "";
$pass = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{ if (empty($_POST["name"]))
else
if (empty($_POST["pass"]))
else
{ $p = myTest($_POST['pass']);
if(strlen($p)>8)
$pass = $p;
else
{ $data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data; } ?>
<form method="post"
action="<?php echo($_SERVER["PHP_SELF"];?>">
</form>
<?php
echo $name."<br/>";
echo $pass;?>
</body> </html>
<html> <body>
<?php
$nameErr = "";
$genderErr = "" ;
$name = "";
$gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
if (empty($_POST["name"]))
else
if (empty($_POST["gender"]))
else
$gender = myTest($_POST["gender"]);
}
function myTest($data)
{ $data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
<form method="post"
Gender:
</form>
<?php
echo $name."<br/>";
echo $gender;?>
</body>
</html>
Q1. Design and implement a php application that accepts two integer numbers from the
current user through. Those represent the number of rows and the number of columns in a
table. The php code should return back a web page that displays the table with the number
of rows and columns requested.
PHP Sessions
Objectives:
Example
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:
vv.php
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']= $_SESSION['views']+1;
else
$_SESSION['views']= 1;
?>
<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.
mypage.php
<?php
session_start();
$_SESSION['color']='red';
$_SESSION['size']='small';
$_SESSION['shape']='round';
print "Done";
?>
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();
<?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
session_start();
//echo a single entry from the array
echo $_SESSION['color'][2]; ?>
--------------------------------------------------------------------------------------------------------
Notes:
<?php
// you have to open the session to be able to modify or remove
it
session_start();
Creating a Database
Objectives:
Database Creation
use myinfo;
phone2 varchar(15),
insert into personal values(1, 'Ben' , 'Storm' , 'Mexico', '0796324432', "", "");
insert into personal values( 3, 'Kim', 'Stone', 'Milan', '0796324477', "", "");
insert into personal values(4, 'Tom', 'Steven', 'Milan', '0796324444', "", "");
1 10308 1996-09-18
2 10309 1996-09-19
4 10310 1996-09-20
5. Displaying Databases
The SHOW DATABASE statement displays all databases in the MySQL Database Server.
SHOW DATABASES;
Example:
create table St (ID int not null, Name varchar(20) not null, Age int not null,
UNIQUE (ID));
If we only want to delete the data inside the table, and not the table itself, then we need to
use the TRUNCATE TABLE statement:
Objectives:
Database Creation
<html>
<body>
<ul>
</li>
</ul></p>
</body>
</html>
<html>
<?php
$con=mysqli_connect("localhost","root","","Persons");
// Check connection
if (mysqli_connect_errno()) {
else{
while($row = mysqli_fetch_array($result)) {
mysqli_close($con);
?>
</body>
</html>
<html>
<?php
$con=mysqli_connect("localhost","root","","Persons");
else{
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>PhoneNumber</th>
</tr>";
while($row = mysqli_fetch_array($result))
echo "<tr>";
echo "</tr>"; }
echo "</table>";
mysqli_close($con); ?>
</body></html>
Example:
We will create an HTML form that can be used to add new records to the "Persons"
table.
<html>
<body>
insert.php File:
<?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'];
if (!mysqli_query($con, $sql))
die('Error: ' . mysqli_error($con));
mysqli_close($con);
?>
<?php
$con=mysqli_connect("example.com","rick","abc123","mydb");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
else
{$result = mysqli_query($con,"SELECT * FROM Persons");
<tr><th>Firstname</th><th>Lastname</th></tr>";
while($row = mysqli_fetch_array($result))
{ echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>"; }
echo "</table>";}
mysqli_close($con);
?>
// 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();
?>
<?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);
}
$conn->close();
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. "
" . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a
variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into
an associative array that we can loop through.
The while() loop loops through the result set and outputs the data from the id, firstname and
lastname columns.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>