You are on page 1of 12

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

Basics of PHP - 3
1. Adding new record to MySQL database
Basically, you will need to do the following things.

(1) Get new values from the user using HTML form.
(2) Validate new data (This is the most important part)
(3) Add new record to database using SQL INSERT command
(Example)
Suppose we have the following table of participants.
No.
1
2
3
4
5

Name
Mickey Mouse
Minnie Mouse
Donald Duck
Buffy Doggy
Dumbo Elephant

Sex
M
F
M
M
M

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

Address
3535, Wall street, CA
NAFED, Jakarta
RETPC, Surabaya
JICA, Tokyo
MOE, Somewhere

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

1.1 Modify show_MySQL_table function


In order to correctly handle INSERT command or other SQL commands than SELECT,
our general-purpose function show_MySQL_table must be modified as follows.
show_MySQL_table.php
...
/* Execute SQL command */
$result = mysql_query($sql);
if (!$result) {
echo "<B>(Error in SQL)</B> " . mysql_error();
die;
}
/* If SQL command is not SELECT, then exit function here */
if (strtoupper(substr($sql,0,6)) != "SELECT") {
mysql_close($link);
Exit from function
return;
}
/* Output results as HTML table */
echo "<table border>n";
...

Add these lines

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

1.2 HTML Form for the data entry


IMPORTANT: Basic data validation can be done easily by HTML form itself (without PHP).

Date should be entered by predefined combo-box rather than


text box, because we can force
user to enter only the valid
number for year, month and day

Telephone number should also


be entered like this way, so that
we can validate the value easily
add_record.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

<HTML><BODY>
<H1>Add new record to participants database</H1>
<FORM method="POST">
<p>Name:<INPUT type="text" name="name" size="50" maxlength="50"></p>
<p>Sex:
<INPUT type="radio" name="sex" value="M">Male
<INPUT type="radio" name="sex" value="F">Female
</p>
<p>Birthday:
size and maxlength should be used to limit
Year
the maximum size of the data. These values must
match with the definition of each field in database
<select name="year">
"<option></option>"
<?php
for ($y = 1900; $y <= date("Y"); $y++) {
echo "<option>$y</option>n";
}
?>
</select>
Month
<select name="month">
"<option></option>"
<?php
for ($m = 1; $m <= 12; $m++) {
echo "<option>$m</option>n";
}
?>
</select>
2

PHP code to automatically add


items to combo-box (year from
1900 up to this year)
PHP code to automatically
add items to combo-box
(month from 1 to 12)

ADMTC-UCSC-University of Colombo

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

Basics of PHP - 3

Day
<select name="day">
"<option></option>"
<?php
for ($d = 1; $d <= 31; $d++) {
echo "<option>$d</option>n";
}
?>

PHP code to automatically


add items to combo-box
(day from 1 to 31)

</select>
</p>
<p>Address:<INPUT type="text" name="address" size="100" maxlength="100"></p>
<p>Telephone:
<INPUT type="text" name="tel1" size="4" maxlength="4"><INPUT type="text" name="tel2" size="4" maxlength="4"><INPUT type="text" name="tel3" size="4" maxlength="4">
</p>
<p><INPUT type="submit" name="submit" value="Add Record"></p>
<p><INPUT type="reset" name="reset" value="Clear"></p>
</FORM>
<HR>

1.3 PHP initialization


add_record.php (continued)
50
51
52
53
54
55
56
57

<?php
function invalid($error_message) {
echo "<p><font color='red'>$error_message</font></p>";
echo "</BODY></HTML>";
die;
Same as previous practice
}
require_once("show_MySQL_table.php");

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

IMPORTANT: This code is needed for the first


visit to the page. Without this code, it will
display error (because no data has been sent)

1.4 Validation of entered data


add_record.php (continued)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

/* If it is the initial screen, then stop here */


if (!isset($_POST["submit"])) invalid("");
/* Check whether all values are posted or not */
$error = "";
isset must be used
if ($_POST["name"] == "") $error .= "Enter Name<BR>";
for option button or
checkbox because
if (!isset($_POST["sex"])) $error .= "Enter Sex<BR>";
key value will not be
if ($_POST["year"] == ""
exist if user does not
$_POST["month"] == ""
select the option or
$_POST["day"] == "") $error .= "Enter Birthday<BR>";
checkbox
if ($_POST["address"] == "") $error .= "Enter Address<BR>";
if ($_POST["tel1"] == ""
means OR in PHP. For AND, use &&
$_POST["tel2"] == ""
$_POST["tel3"] == "") $error .= "Enter Telephone<BR>";
if ($error != "") invalid($error);
Check valid date by function
/* Check Birthday */
if (!checkdate($_POST["month"],$_POST["day"],$_POST["year"]))
invalid("Invalid birthday");
/* Check Telephone */
Check if all data is numeric
if (!is_numeric($_POST["tel1"])
!is_numeric($_POST["tel2"])
!is_numeric($_POST["tel3"])) invalid("Telephone is not number");

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

1.5 Addition of new data to MySQL database


add_record.php (The end of page)
84
85
86
87
88
89
90
91
92
93
94
95
96
97

/* Finally, we can add record */


$sql = "INSERT INTO participants VALUES " .
sprintf('("","%s","%s","%s-%s-%s","%s","%s-%s-%s")',
$_POST["name"],
$_POST["sex"],
$_POST["year"], $_POST["month"], $_POST["day"],
$_POST["address"],
$_POST["tel1"], $_POST["tel2"], $_POST["tel3"]);

sprintf is a very
useful function that
returns a string that
combines the values of
one or more variables
using specified format

echo "<p>", htmlspecialchars($sql), "</p>";


show_MySQL_table("localhost","yoichi","","test",$sql);
echo "<p><b>New record has been successfully added</b></p>";
?>
</BODY></HTML>

1.6 Improvement consideration


Though this code works well, we should consider many necessary improvements when you
will develop real Web site. Followings are some of the important improvements.

Prevent duplication of data If the database should not have duplicated data, you
should first search for the same data in database so that there will be no same data in
the database.
In order to implement this function, some additional modification is needed for our
general-purpose function show_MySQL_table ( see 2.2)

Better retry interface for error When user made even tiny mistake, all input data will
be disappeared and must be entered from the beginning. The form should be able to
display the user-entered data as the initial value in each form element.
Below is the example of inserting initial value for input-text box.

<p>Name:<INPUT type="text" name="name" size="50" maxlength="50"


value="<?php echo htmlspecialchars($_POST['name']) ?>"></p>

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

2. Deleting a record from MySQL database


Basically, you will need to do the following things.
(1) Show the data from database and let user choose a record to delete
(2) Ask the user for confirmation of the deletion
(3) Delete the data from database using SQL DELETE command
(Example) We use the same example as 1.
2.1 Interface design for the record deletion
The interface design for record deletion is very critical. We can think of many possible
interfaces, but we should be very careful to choose the best interface based on the userfriendliness as well as the easiness of development.

Interface design for the deletion 1

Advantage: Very easy to develop. You can use almost the same code as record
addition in practice 1, only changing the SQL command from INSERT ~ to
DELETE ~.
Disadvantage: There is no display of existing record to be deleted. It is very
difficult to use. User must enter exactly the same data to delete.

Interface design for the deletion 2

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

Advantage: Easy to use because user can see the list of existing records. It is also
convenient if the user needs to delete multiple records at once.

Disadvantage: Not so easy to write PHP code to perform this function. It is also
necessary to implement multiple page display if number of records are very large.
Interface design for the deletion 3

1. First, user searches the record to delete

2. Then, user deletes the data that found

Advantage: Rather easy to develop. The same interface can be used for Search
page. It is also useful for the database with large number of records. Multiple
records deletion is also possible depending on the search result.

Disadvantage: Two-step operation is needed. It is not so easy to use if the user


wants to delete only 1 record but there are so many similar records (Getting
search result with only 1 match might be difficult)

In this practice, we adopt design 3.

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

2.2 Modify show_MySQL_table function


We need the information of number of records found by SELECT command, so our
general-purpose function show_MySQL_table must be modified as follows.
show_MySQL_table.php
...
/* If the SQL command is not SELECT, then stop function here */
if (strtoupper(substr($sql,0,6)) != "SELECT") {
mysql_close($link); // Closing connection
return;
}

Add these lines

/* Get number of records found */


$num_found = mysql_num_rows($result);
echo "<p>($num_found records found)</p>n";

Get number of records

if ($num_found != 0) {

Output number of
records on screen

/* Output results as HTML table */


echo "<table border>n";

Output the table only if one


or more records found

...
Add this line
(Closing brace for
if statement)

echo "</table>n";
}
/* Closing procedures */
mysql_free_result($result);
// Free result
mysql_close($link); // Closing connection
return $num_found;
}
?>

Add this line


(Return number of
records found)

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

2.3 HTML Form for data search


HTML form is almost the same as practice 1. You only change the message text as follows.
delete_record.php
1
2
3
4

<HTML><BODY>
<H1>Search &amp; Delete record from participants database</H1>
<H3>Enter one or more fields to search</H3>
<FORM method="POST">
...
45 <p><INPUT type="submit" name="submit" value="Search Record"></p>
46 <p><INPUT type="reset" name="reset" value="Clear"></p>
47 </FORM>
2.4 PHP initialization
It is almost the same as practice 1 except that we should change the name of function
invalid.
delete_record.php (continued)

It is better to change the name of function


invalid to stop because we use this
function not only for error, but also for
normal termination

48 <?php
49 function stop($error_message) {
...
56 require_once("show_MySQL_table.php");
2.5 Overall submit validation

First of all, we check if the page has been shown for the first time (without posting of any
data), or user chose NO for the confirmation of deletion. In both case, we stop the PHP code
here.
58 /* If it is the initial screen or user has clicked "NO" button */
59 if (!isset($_POST["submit"]) $_POST["submit"]=="NO") stop("");
60
IMPORTANT: In this example, all 3 submit buttons on the page (Search Record, YES, and
NO) have the same name attribute as submit (i.e. name=submit).
Therefore, the posted value from the form $_POST["submit"] can also take 3 different
values (Search Record, YES, or NO) depending on which button the user
clicked.

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

2.6 Deletion of data if user confirmed it


Next, we will check if the user has clicked YES button for confirmation of deletion. If that
case, we will actually delete the record.
61 /* If user has clicked "YES" button */
62 if ($_POST["submit"] == "YES") {
63
$sql="DELETE FROM participants WHERE".stripslashes($_POST["where"]);
64
show_MySQL_table("localhost", "yoichi", "", "test", $sql);
65
stop("Specified record has been deleted.");
Execution stops here
66 }
IMPORTANT: This code will not be executed at all when the user visited the page for the first
time, or when the user searches for the record. It will be executed only when the
user clicked YES button.
stripslashes function removes unnecessary backslashes () in posted string (which Web
browser adds automatically)
$_POST["where"] is the WHERE phrase for SQL command to be used for the deletion. This
value will be created only after the user searches any record ( see 2.7~2.8).
2.7 Creating WHERE phrase for the search
Now, we prepare WHERE phrase that will be used for SELECT command for the search as
well as DELETE command later. The secret here is that we must use the same WHERE phrase
for both SELECT and DELETE command, so that the user can delete exactly the same record it
finds.
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

/* Assign short variables to each field for easy coding */


$nm = $_POST["name"];
if (isset($_POST["sex"])) $sx = $_POST["sex"]; else $sx = "";
$bd = $_POST["year"]."-".$_POST["month"]."-".$_POST["day"];
$ad = $_POST["address"];
$tl = $_POST["tel1"]."-".$_POST["tel2"]."-".$_POST["tel3"];
/* Create WHERE phrase for the search and delete */
$where = "";
if ($nm != "") $where .= " name LIKE '%$nm%'";
if ($sx != "") $where .= " AND sex='$sx'";
if ($bd != "--") $where .= " AND birthday='$bd'";
if ($ad != "") $where .= " AND address LIKE '%$ad%'";
if ($tl != "--") $where .= " AND telephone LIKE '%$tl%'";
if (substr($where,1,3) == "AND") $where = substr($where, 4);
/* If there was no data entered, then we reject the request */
if ($where == "") stop("You must enter at least one field to search.");

10

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

2.8 Perform search and display confirmation buttons for deletion


Finally, we perform record search by using SQL SELECT command. And if there is any
records found, we display confirmation buttons (YES and NO) so that the user can confirm the
deletion.
87 /* Perform search for the specified records */
88 $sql = "SELECT * FROM participants WHERE" . $where;
89 $num_found = show_MySQL_table("localhost","yoichi","","test",$sql);
90
91 /* Show delete confirmation button if record found */
92 if ($num_found > 0) {
93
echo "<FORM method='POST'>";
94
echo '<INPUT type="hidden" name="where" value="' .
95
htmlspecialchars($where) . '"';
96
echo "<p><font color='red'>";
97
echo "Are you sure to delete $num_found record?&nbsp;";
98
echo "<INPUT type='submit' name='submit' value='YES'>&nbsp;";
99
echo "<INPUT type='submit' name='submit' value='NO'>";
100
echo "</font></p>";
101
echo "</FORM>";
102}
103?>
104</BODY></HTML>

11

ADMTC-UCSC-University of Colombo

Basics of PHP - 3

IMPORTANT: Confirmation buttons (YES and NO) are located in another HTML form. You
can include multiple forms within one page, so that you can post different
information by different forms.
In line 94~95, we use single quotation (') instead of double quotation (") to enclose echo
statement. This is because the variable $where already contains single quotation,
and that we must make all the strings valid in terms of quotation usage. In other
words, any enclosing symbols in PHP must be used as pair with no conflict with
others.
(Example)

$where

1st-level (')
3rd-level (")

3rd-level (")

echo '<INPUT type="hidden" value="name LIKE '%kogure%'">'

2nd-level (<~>)

4th-level (')

Alternate notation (indentation)


echo
'
<
INPUT type =
"
hidden
1st-level (')

"
value =

2nd-level (<~>)

"
name LIKE
'

3rd-level (")
$where

%kogure%

4th-level (')

'
"
>
'

<INPUT type="hidden"> is a text box that will not appear on the screen. You can use this
hidden text box to store information that should be posted again to Web server. In
this case, we store the WHERE phrase that we will use for record deletion.

12

You might also like