You are on page 1of 11

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

Basics of PHP - 2
1. HTML forms
The user can submit information using a standard HTML form. It is just a standard HTML
feature, neither PHP nor JavaScript.
1.1 <FORM> tag
The HTML form must begin with <FORM> and must end with </FORM>
<FORM>
...
</FORM>
You can specify the following attributes to <form> tag
Optional attributes
method="POST" / method="GET"
This determines the method of transmission of form data to the Web server.
The default method is GET, and all the form values will be sent as the
parameter of URL.
action="destination_URL"
This determines the destination URL that the form will be submitted. This URL
must be a page that uses server-side technology such as PHP, ASP or CGI.
If omitted, the same page as form page (itself) will be the destination.
1.2 HTML form items
Almost all standard user interface elements can be creates by <INPUT> tag.
The value of any kind of element will be always sent to Web server in the same key=value
format.
You can get each value of these elements by using $_GET["key"] or $_POST["key"]
array depending on the method specified in <FORM> tag as follows
(1) Single-line text box
<input type="text" name="key">
Optional attributes
value="value" If you specify value, it will be the initial text displayed.
type="password"

If you specify password for type, then characters will not


be shown directly in the text box. Good for password field.

type="hidden" If you specify hidden for type, then the text box will not be
displayed on screen. You can use this type of text box to store
any value temporarily in HTML page, then send back again to
the Web server. This is commonly used for PHP page that
1

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

needs to store variables within generated page.


size=n

Specify width of text box in number of characters. Note that this does
not limit the number of characters user will enter. For that
purpose, use maxlength=n instead.

maxlength=n Specify maximum number of characters allowed to enter from user.


This is useful for user-ID or password input.
(2) Multi-line text box
<textarea rows="n" cols="m" name="key">
...
Multi-line content comes here
...
</textarea>
Any text between <textarea> and </textarea> will be treated as data to be shown in multiline text box.
(3) Buttons
<input type="button" name="key" value="value">
<input type="submit" name="key" value="value">
<input type="reset" name="key" value="value">
All these 3 tag will show buttons on screen. value determines the caption displayed on the
button.

type="button" will create normal button with NO function assigned. You must write
JavaScript or other script to assign the behavior manually.

type="submit" will create submit button for the form. Clicking on this button will
send all the information entered in the form

type="reset" will create reset button for the form. Clicking on this button will clear all
the fields in the form

(4) List box and Combo box


<select size="n" name="key">
<option>item1</option>
<option>item2</option>
<option>item3</option>
...
</select>
This group of tags will create a List-box or Combo-box. size="n" determines the number of
rows displayed on the screen. If n = 1, then it will be a Combo-Box. If n > 1, then it will be a
List-box.
Every item in the List-box or Combo-box will be specified by <option> ~ </option> pair of
tags. And the text inside this tag will be sent to Web server as value.

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

Optional attributes
value="value" If you specify value, it will be the value to be sent instead of item.
selected

If you specify selected for one of <option> tags, then that item will be
initially selected. Only 1 <option> tag is allowed to be selected.

(5) Option button


<input type="radio" name="key" value="value_1">
<input type="radio" name="key" value="value_2">
...
<input type="radio" name="key" value="value_n">
This tag will create 1 option button. And usually you must create 2 or more option buttons to
be practical. All <input> tags for a set of option buttons must have the same name, and
each option button must have different value. So that the form will send appropreate
key=value pair to the Web server.
If you want to create multiple sets of option buttons, then you must use different name for
different set of option buttons.
Optional attributes
checked

If you specify checked for one of option buttons, then that option
button will be initially selected. Only 1 option button is allowed to be
selected within a set of option buttons.

(6) Check box


<input type="checkbox" name="key" value="value">
This tag will create 1 check box. Since check boxes are always independent, you can insert
only 1 check box, or multiple check boxes with totally independent settings.
Optional attributes
checked

If you specify checked, then the check box will be initially checked.

2. Viewing MySQL database


2.1 Simple display of all records
Common PHP code to display all records in MySQL table is as follows.
Note: This code can be used for any MySQL table. You should modify only , , and .
<HTML><BODY>
<?php
/* Connect to MySQL database */
$link = mysql_connect("host_name", "user_name", "password") or die;
mysql_select_db("database_name") or die;

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

/* Execute SQL command */


$sql = "SELECT * FROM table_name";

Ending semi-colon ; is not


needed for SQL command string

$result = mysql_query($sql) or die;


/* Output results as HTML table */
echo "<table border>n";
/* Output field names as table header */
echo "<tr>n";
for ($field=0; $field < mysql_num_fields($result); $field++) {
echo "<th>" . mysql_field_name($result, $field) . "</th>n";
}
echo "</tr>n";
/* Output all records */
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>n";
foreach ($line as $cell) {
echo "<td>$cell</td>n";
}
echo "</tr>n";
}
echo "</table>n";
/* Closing procedures */
mysql_free_result($result);

// Free result

mysql_close($link);

// Closing connection

?>
</BODY></HTML>
(Required modification for real use)

host_name Name or IP address of MySQL server. You should use localhost if


MySQL server is in the same PC as Web server.
user_name MySQL user name. CAUTION: This is not the login name of the server.
password MySQL password. CAUTION: This is not the login password of the server.

database_name MySQL database name to use


table_name MySQL table name to use. You can also use any other SQL
commands here.
Practice Try database_name = test and table_name = sales
(Output of the practice should be like shown next page)
4

ADMTC-UCSC-University of Colombo

No
.

Basics of PHP - 2

Date

Branch

Item

Category

Unit
Price

Unit
Profit

2002-07-01
2002-07-01
2002-07-02
2002-07-03
2002-07-04

Jakarta
Medan
Surabaya
Jakarta
Makassar

Trousers
Suites
Mesh Bag
Suites
Trousers

Clothes
Clothes
Accessory
Clothes
Clothes

78000
345000
29800
345000
78000

22000
147000
16800
147000
22000

148

2002-09-30

1
2
3
4
5

Jakarta

T-Shirt

Clothes

39800

Qty
12
4
10
8
34

10800

45

Sales

Profit

936000
1380000
298000
2760000
2652000

264000
588000
168000
1176000
748000

1791000

486000

2.2 Adjust the display of cell


You notice that numeric values in practice output is left-justified, which is not appropriate.
There is also no commas , in numbers that it is difficult to read.
We will try to change the cell format in general way (so that this code can be used for any
table)
...
/* Output all records */
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>n";
foreach ($line as $cell) {
if (is_numeric($cell)) {
echo "<td align='right'>";
echo number_format($cell);

Add these lines instead of


echo "<td>$cell</td> n";

echo "</td>n";
} else {
echo "<td>$cell</td>n";
}
}
echo "</tr>n";
}
echo "</table>n";
...
Now the output will be like this.
No
.

Date

Branch

Item

Category

Unit
Price

Unit
Profit

1
2
3
4
5

2002-07-01
2002-07-01
2002-07-02
2002-07-03
2002-07-04

Jakarta
Medan
Surabaya
Jakarta
Makassar

Trousers
Suites
Mesh Bag
Suites
Trousers

Clothes
Clothes
Accessory
Clothes
Clothes

78,000
345,000
29,800
345,000
78,000

22,000
147,000
16,800
147,000
22,000

148

2002-09-30

39,800

Jakarta

T-Shirt

Clothes

Qty

Sales

Profit

12
4
10
8
34

936,000
1,380,000
298,000
2,760,000
2,652,000

264,000
588,000
168,000
1,176,000
748,000

10,800

45

1,791,000

486,000

2.3 Even better way to generalize table display


The code in 2.1 is so general that you can pack these codes into a user-defined
function. If you do that, you then can simply call that function to display any kind of table in any
way (including search result or joining of multiple tables!)

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

Here is the way to create user-defined function to output table records as HTML table.
<HTML><BODY>

Delete this line

<?php

Name of the function

function show_MySQL_table
($host_name,
$user_name,

Parameters for the function


the user will specify when
they call this function

$password,
$database_name,
$sql)

Opening brace of the function

{
/* Connect to MySQL database */

$link = mysql_connect($host_name, $user_name, $password) or die;


mysql_select_db($database_name) or die;
Delete this line

/* Execute SQL command */


$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);

Display error message for SQL

if (!$result) {
echo "<B>(Error in SQL)</B> " . mysql_error();
die;
}
...

Same code as 2.1~2.2

mysql_close($link);
}

// Closing connection

Closing brace of the function

?>

Delete this line

</BODY></HTML>
When
you
finished
modification,
show_MySQL_table.php.

then

you

should

save

the

file

as

Now, you can use this user-defined function as follows.


Create new file, then enter the following code.
<HTML>
The filename that you have
<BODY>
saved
your function definition
<?php
require_once("show_MySQL_table.php");
$sql = "SELECT * FROM sales";
show_MySQL_table("localhost","yoichi","","test",$sql);
?>
</BODY>
Just specify parameters
</HTML>
Save

the

new

file

as

new

name
6

with

.php

extension.

Upload

both

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

show_MySQL_table.php and this new file to Web server, then try browsing this new file.
2.4 Display of table that has relation to other tables
Suppose we normalized (optimized) structure of table for previous practice as follows.

Item, Category, Unit Price and Unit Profit fields can be separated as Item
table, then just use Item No. in main table as a pointer to Item table

Branch field and Category field can also be separated

Remove Sales and Profit field because they can be calculated from other
values

Optimized table structure (4 tables with relation)


branch table

sales2 table
No
.

Date

Branch
No.

Item
No.

Qty

Branch
No.

Branch

2002-07-01
2002-07-01
2002-07-02
2002-07-03
2002-07-04

1
3
2
1
4

2
3
6
3
2

12
4
10
8
34

1
2
3
4

Jakarta
Surabaya
Medan
Makassar

148

2002-09-30

45

1
2
3
4
5

Item
No.
1
2
3
4
5
6
7

item table
Item

Category
No.

T-Shirt
Trousers
Suites
Necktie
Ear Ring
Mesh Bag
Button

1
1
1
2
2
2
2

Unit
Price

Cost

Unit
Profit

39,800
78,000
345,000
54,000
19,800
29,800
7,000

29,000
56,000
198,000
47,000
11,000
13,000
5,000

10,800
22,000
147,000
7,000
8,800
16,800
2,000

category
table

Category
No.
1
2

Category

Clothes
Accessory

Now, how can we display the same output as 2.2 ?

Well, you can do it by just giving appropriate SQL command to the same function

First, lets JOIN 2 tables into 1, sales2 and branch


1.
2.
3.
4.

SELECT `No.`, Date, Branch, `Item No.`, qty


FROM sales2, branch
WHERE sales2.`Branch No.` = branch.`Branch No.`
ORDER BY `No.`
1.
2.
3.
4.

Specify all fields that you want to display.


Use back-quote ` (not single quote, but a back quote!!) to surround field
name that has space or symbol.
~
!
@
#
Specify two tables that you want to join.
`
1
2
3
Specify the link between two tables
Tab
Q
W
E
Specify sorting order
7

Caps Lock

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

(The output will look like this)


No
.
1
2
3
4
5

Date

Branch

Item
No.

Qty

2002-07-01
2002-07-01
2002-07-02
2002-07-03
2002-07-04

Jakarta
Medan
Surabaya
Jakarta
Makassar

2
3
6
3
2

12
4
10
8
34

45

148

2002-09-30

Jakarta

Then, the complete SQL command to produce exactly the same output with 2.2 will
be as follows
SELECT `No.`, Date, Branch, Item, Category,
`Unit Price`, Qty,
`Unit Price` * Qty as Sales,
`Unit Profit` * Qty as Profit
FROM sales2, branch, item, category
WHERE (sales2.`Item No.` = item.`Item No.`)
AND (sales2.`Branch No.`= branch.`Branch No.`)
AND (item.`Category No.`= category.`Category No.`)
ORDER BY `No.`

Calculate values
for output and
give them name

2.5 Perform statistical analysis of data


Basically, you can also do statistical analysis of data using the SELECT command.
Example 1: Total sales of each branch
SELECT Branch, SUM(`Unit Price` * Qty) as `Total Sales`
FROM sales2, branch, item
WHERE (sales2.`Item No.` = item.`Item No.`)
AND (sales2.`Branch No.`= branch.`Branch No.`)
GROUP BY Branch
(The output will look like this)
Branch
Jakarta
Makassar
Medan
Surabaya

Total Sales
82,183,200
59,208,000
41,242,200
83,692,400

Example 2: Average number of items sold in a day


SELECT item, AVG(Qty) as `Average Qty`
FROM sales2, item
WHERE (sales2.`Item No.` = item.`Item No.`)
GROUP BY item

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

(The output will look like this)


item

Average Qty

Button
Ear Ring
Mesh Bag
Necktie
Suites
T-Shirt
Trousers

13
62
19
47
7
58
23

2.6 Searching through database


Basically, searching through database is the same as showing database by SQL command
using WHERE phrase.
Much more critical part is the validation of data sent from user.
Suppose we have the following table of participants.
Name
Mickey Mouse
Minnie Mouse
Donald Duck
Buffy Doggy
Dumbo Elephant

Sex

Birthday

M
F
M
M
M

1961-07-01
1987-09-23
1989-11-25
2002-07-03
2002-07-04

Address

Telephone

3535, Wall street, CA


NAFED, Jakarta
RETPC, Surabaya
JICA, Tokyo
MOE, Somewhere

02-1234-0987
02-2341-9573
02-0492-9713
03-6731-1231
04-4827-3719

<HTML><BODY>
<H1>Search in participants database</H1>
<FORM method="POST">
<p>Name:<INPUT type="text" name="name"></p>
<p>Sex: <INPUT type="radio" name="sex" value="M">Male
<INPUT type="radio" name="sex" value="F">Female</p>
<p><INPUT type="submit" name="submit" value="OK"></p>
<p><INPUT type="reset" name="reset" value="Clear"></p>
</FORM>
<HR>
<?php
Function to report error
function invalid($error_message) {
echo "<p><font color='red'>$error_message</font></p>";
echo "</BODY></HTML>";
die;
}
require_once("show_MySQL_table.inc");
if (isset($_POST["submit"])) {
$sql = "SELECT * FROM participants WHERE";
$option = "";
if (isset($_POST["name"])) {

Form

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

$name = $_POST["name"];
if (strlen($name) > 50) invalid("Name is too long");
if ($name != "") $option .= " Name LIKE '%$name%'";
}
if (isset($_POST["sex"])) {
if ($option != "") $option .= " AND";
$option .= " Sex = '".$_POST["sex"]."'";
}
if ($option != "") {
$sql .= $option;
echo "<p>", htmlspecialchars($sql), "</p>";
show_MySQL_table("localhost","yoichi","","test",$sql);
}
}
?>
</BODY></HTML>
Useful data validation functions
isset($var)

Return TRUE if the specified variable has been set (exists)

echo isset($var);
$var = "Hello!";
echo isset($var);
is_numeric($var)

// This will show nothing (FALSE)


// Now this will show 1 (TRUE)

Return TRUE if the specified variable contains numeric value

$var = "Hello!";
echo is_numeric($var); // This will show nothing
$var = "1234";
echo is_numeric($var); // Now this will show 1 (TRUE)
checkdate($month,$day,$year)
echo checkdate(2,31,2003);
echo checkdate(2,28,2003);

Return TRUE if the specified combination of Year,


Month, Day is valid; & check leap years.
// This will show nothing (FALSE)
// Now this will show 1 (TRUE)

strlen($var) Return number of characters contained in specified string variable


$var = "Hello!";
echo strlen($var);

// This will show 6 (Hello! has 6 characters)

10

ADMTC-UCSC-University of Colombo

Basics of PHP - 2

Useful data conversion functions


htmlspecialchars($var) Convert any special characters for HTML contained in
specified string to a safe notation of HTML display
$var = "<I> LOVE YOU </I>";
echo $var;
// This will show LOVE YOU in Italic
echo htmlspecialchars($var); // This will show <I> LOVE YOU </I>
strip_tags($var)

Strip all HTML and PHP tags from the specified string. Useful
for message board system to prevent abuse.

$var = "<a href='bad.html'>Click here</a>";


echo $var;
// This will show Click here with a link
echo strip_tags($var);
// This will show Click here in normal text
substr($var,$start,$length)

Return part of specified string, starting from


specified position and for the specified length.
CAUTION: $start must be counted from 0, not 1

$var = "I am just a human.";


echo $var;
echo substr($var,5,4);

// This will show whole text


// This will show just only

11

You might also like