You are on page 1of 11

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

Basics of PHP - 4
1. Updating existing record in MySQL database
Basically, you will need to do the following things.

(1) Show the data from database and let user choose a record to update
(2) Let user modify existing data
This requires setting default values to HTML form
(3) Update the data in database using SQL UPDATE command
1.1 Database structure and update operation
If the database consists of non-relational (independent) flat tables only, then updating can be
done by simply deleting old data and inserting new data into the table.
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

Minnie Mouse 2

1987-09-23

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

NAFED, Jakarta, 2

1. Delete record

02-2341-9573

2. Insert updated record

However, if the database has relational tables, updating means Modifying data while
keeping the internal position of record in the table. So it cannot be done by simply deleting &
adding, especially when the table has primary key.
Suppose we do update of the following simple (but related) tables
participants2 table
pt_id
1
2
3
4
5

province table

participant_name
Mickey Mouse
Minnie Mouse
Donald Duck
Buffy Doggy
Dumbo Elephant

pv_id
1
2
3
4
5

province_name
Jakarta
Surabaya
Medan
Makassar
Bali

Updating Donald Duck record in participants2 table is rather easier

province_id
2
1
3
1
5

You can delete the record, and add new record with updated information

But updating Medan record in province table cannot be done by delete & add,
because doing so will change the id of Medan to other value. You should rather use
SQL UPDATE command to update the record.

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

1.2 Interface for adding or updating table that has the link to other table
If the table has a field that is actually a key number to another table (like participants2
table), then that field should be a drop-down list of selectable values like shown below.

Province field should be a dropdown list that has been generated


from province table

In order to display this kind of drop-down list, it is a good idea to write general-purpose
function to produce the list.

PHP script for update page

host, user, password of MySQL


name of database and table
field to be the internal value and item
currently selected item

show_table_droplist

General-purpose function

Output from the function

<select name="province_id">
<option value=1>Jakarta</option>
<option value=2>Surabaya</option>
<option
value=3
selected>Medan</option>
<option value=4>Makassar</option>
... </select>

Selected item = $_POST[province_id]

The value you get from the posting

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

show_table_droplist.php
1 <?php
2 function show_table_droplist (
3 $host_name, $user_name, $password, $database_name,
4 $table_name, $id_name, $field_name, $selected_id)
5{
6 /* Connect to MySQL database */
7 $link = mysql_connect($host_name, $user_name, $password) or die;
8 mysql_select_db($database_name) or die;
9
10 /* Execute SQL command */
11 $sql = "SELECT `$id_name`, `$field_name` FROM `$table_name`";
12 $result = mysql_query($sql);
13
14 /* Display drop-down list items */
15 while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
16 echo "<option value='$line[$id_name]'";
17
if ($line[$id_name] == $selected_id) echo " selected";
18
echo ">";
19 echo htmlspecialchars($line[$field_name]);
20 echo "</option>\n";
21 }
22
23 /* Closing procedures */
24 mysql_free_result($result);
25 mysql_close($link);
26 }
27 ?>
test_droplist.php Test page for the function
1 <html><body>
2 <p>Province:
You can add blank item if needed
3 <select name="province_id">
4 <option></option>
Name of host, user, password,
5 <?php
and database of MySQL
6 require_once("show_table_droplist.php");
7 show_table_droplist("localhost","yoichi","","test",
8 "province", "pv_id", "province_name", 3);
9 ?>
Name of table to show as drop-down list,
10 </select>
Field name of the table to be used as value,
11 </body></html>
Field name of the table to be used as each list item
Selected item number in drop-down list

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

1.3 Overall general-purpose database manipulation pages


Here are the sample of general-purpose, overall database manipulation pages.
You can use these pages by changing database name and / or SQL commands.
rdb_main.php

rdb_browse.php

Start page

Browse record

Browse record

Browse all
Search

Add new record

Delete

rdb_delete.php

Delete
Confirmation
Yes

No

Update

Add new

Update

Add
/ Update
Name:
Province:

add/update
rdb_add_update.php
rdb_main.php
1
2
3
4
5

<HTML><BODY>
<H1>Relational Database Main Page</H1>
<p><a href="rdb_browse.php">Browse Record</a></p>
<p><a href="rdb_add_update.php">Add New Record</a></p>
</BODY></HTML>

rdb_browse.php
1 <?php
2 /* Initialize variables */
3 $submit = ""; // Which submit button was clicked by user
4 $search = ""; // Search string
5 $offset = 0;
// Starting position of record to show
6 $num_rows = 10;
// Number of records to show at a time
7 $max_row = 0; // Maximum row that has been displayed before

Show_MySQL_table2.php
show_table_droplist.php

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

8 $selected = ""; // Selected record for update or deletion


9 if (isset($_POST["submit"]) && $_POST["submit"] != "OK" &&
$_POST["submit"] != "NO") {
10
$submit = $_POST["submit"];
11
$search = $_POST["search"];
12
$offset = $_POST["offset"];
13
$num_rows = $_POST["num_rows"];
14
$max_row = $_POST["max_row"];
15
if (isset($_POST["selected"])) $selected = $_POST["selected"];
16 }
17
18 /* Redirect to update or delete page */
19 if ($selected != "") {
20
if ($submit == "Update Marked Record")
21
$location = "rdb_add_update.php";
22
elseif ($submit == "Delete Marked Record")
23
$location = "rdb_delete.php";
24
if (isset($location)) {
25
header("Location: " . $location . "?id=$selected");
26
exit;
27
}
28 }
29
30 /* Modify varable deoending on the submit type */
31 if ($submit == "Show All Records") $search = "";
32 if ($submit == "Search Record") $offset = 0;
33 if ($submit == "Next Page") $offset = $max_row;
34 if ($submit == "Previous Page") {
35
$offset = $offset - $num_rows;
36
if ($offset < 0) $offset = 0;
37 }
38 ?>
39
40 <html><body>
41
<!-- These are for self-learning information -->
42
<p><small><b>Debug information for Developer</b><br>
43
$_POST['submit'] = <?php echo $submit; ?><br>
44
$_POST['search'] = <?php echo $search; ?><br>
45
$_POST['offset'] = <?php echo $offset; ?><br>
46
$_POST['num_rows'] = <?php echo $num_rows; ?><br>
47
$_POST['selected'] = <?php echo $selected; ?><br>
48
</small></p>
49 <H1>Browse Relational Database</H1>
50

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

51 <!-- Display search capability -->


52 <FORM method="POST">
53 <INPUT type="submit" name="submit" value="Show All Records"> or
54 <INPUT type="text" name="search" value="<?php echo $search; ?>">
&nbsp;
55 <INPUT type="submit" name="submit" value="Search Record">
56
57 <HR>
58
59 <?php
60 /* Display data table */
61 require_once("show_MySQL_table2.php");
62 $sql = "SELECT pt_id, participant_name, province_name FROM
participants2, province WHERE province_id = pv_id";
63 if ($search != "") $sql .= " AND participant_name LIKE '%$search%'";
64 $sql .= " ORDER BY pt_id";
65 $num_found = show_MySQL_table2("localhost", "yoichi", "", "test",
$sql, $offset, $num_rows, "pt_id");
66
67 /* Display number of data and current range */
68 $min_row = $offset + 1;
69 $max_row = $offset + $num_rows;
70 if ($max_row > $num_found) $max_row = $num_found;
71 echo "<p><b>$num_found</b> records found / Showing record No.
<b>$min_row - $max_row</b></p>\n";
72 ?>
73
74 <!-- Display selection for number of records in a screen -->
75 <p>Show
76 <select name="num_rows">
77 <?php
78 for ($i=10;$i<=100;$i+=10) {
79
echo "<option ";
80
if ($i == $num_rows) echo " selected";
81
echo ">$i</option>";
82 }
83 ?>
84 </select>
85 records at a time
86
87 <!-- Display previous / next page button -->
88 <?php if ($offset > 1) echo "<INPUT type='submit' name='submit'
value='Previous Page'>"; ?>&nbsp;
89 <?php if ($offset + $num_rows - 1 < $num_found) echo "<INPUT
type='submit' name='submit' value='Next Page'>"; ?>

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

90
91 <!-- Hidden field to hold current variables -->
92 <INPUT type="hidden" name="offset" value="<?php echo $offset; ?>">
93 <INPUT type="hidden" name="max_row" value="<?php echo $max_row; ?>">
94
95 <HR>
96
97 <!-- Display button for update or delete -->
98 <p><b>Operation</b>: Mark a record, then</p>
99 <INPUT type="submit" name="submit" value="Update Marked Record">
&nbsp;
100 <INPUT type="submit" name="submit" value="Delete Marked Record">
101 </FORM>
102 <a href="rdb_main.php">Return to Main Menu</a>
103 </body></html>
rdb_add_update.php
1 <?php
2 require_once("show_MySQL_table2.php");
3
4 /* Initialize all variables */
5 $is_update = isset($_GET["id"]); // TRUE if it is update screen
6 $pt_nm = "";
// Participant name
7 $pv_id = 0;
// Province id
8 $error = "";
// Error message
9 $success = ""; // Success message
10 if ($is_update) {
11
$title = "Update Record";
12
$button_caption = "Update";
13 } else {
14
$title = "Add New Record";
15
$button_caption = "Add";
16 }
17
18 /* Get current record datas */
19 if (isset($_POST["submit"])) {
20
$pt_nm = $_POST["name"];
21
$pv_id = $_POST["province_id"];
22 } elseif ($is_update) {
23
$link = mysql_connect("localhost", "yoichi", "") or die;
24
mysql_select_db("test") or die;
25
$result = mysql_query("SELECT * FROM participants2 WHERE pt_id ="
. $_GET["id"]);
26
if (mysql_num_rows($result) == 0) die;

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

27
$line = mysql_fetch_array($result, MYSQL_ASSOC);
28
$pt_nm = $line["participant_name"];
29
$pv_id = $line["province_id"];
30
mysql_free_result($result);
mysql_close($link);
31 }
32
33 /* Perform SQL command */
34 if (isset($_POST["submit"])) {
35
/* Check values */
36
if ($pt_nm == "") $error .= "Please enter the name of participant";
37
if ($pv_id == "") $error .= "Please choose province";
38
/* If there's no error, then perform SQL command */
39
if ($error == "") {
40
if ($is_update) {
41
$sql = "UPDATE participants2 SET
participant_name='$pt_nm',
province_id=$pv_id WHERE pt_id=" . $_GET["id"];
42
$success = "The record has been updated.";
43
} else {
44
$sql = "INSERT INTO participants2 VALUES ('', '$pt_nm',
$pv_id)";
45
$success = "A new record has been added.";
46
$pt_nm = ""; $pv_id = 0;
// Clear all field!
47
}
48
show_MySQL_table2("localhost", "yoichi", "", "test", $sql, "",
"", "");
49
}
50 }
51 ?>
52 <html><body>
53 <H1><?php echo $title; ?></H1>
54 <FORM method='POST'>
55 <p>Participant Name:
56 <INPUT type='text' name='name' size=30 maxlength=50
value="<?php echo $pt_nm; ?>"></p>
57 <p>Province:
58 <select name="province_id">
59 <?php
60 if (!$is_update) echo "<option></option>";
61 require_once("show_table_droplist.php");
62 show_table_droplist("localhost","yoichi","","test","province",
"pv_id", "province_name", $pv_id);
63 ?>
64 </select></p>
65 <input type="submit" name="submit" value="<?php echo $button_caption
?>">&nbsp;
8

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

66 <?php if (!$is_update && !isset($_POST["submit"])) echo '<input


type="reset" name="submit" value="Clear">'; ?>
67 <HR>
68 <p><font color='red'><?php echo $error; ?></font></p>
69 <?php
70 if ($success != "") echo "<p>$success</p>";
71 if ($is_update) echo '<a href="rdb_browse.php">Return to Data
Browser</a>';
72 if (!$is_update) echo '<a href="rdb_main.php">Return to Main
Menu</a>';
73 ?>
74 </FORM>
75 </body></html>
rdb_delete.php
76 <?php
77 /* Redirect to data browser page */
78 if (!isset($_GET["id"]) || isset($_POST["submit"]) &&
$_POST["submit"] == "NO") {
79
header("Location: rdb_browse.php");
// Redirect to browser page
80
exit;
81 }
82 ?>
83
84 <html><body>
85 <H1>Delete confirmation</H1>
86 <?php
87 require_once("show_MySQL_table2.php");
88 if (isset($_POST["submit"]) && $_POST["submit"] == "YES") {
89
/* Perform deletion */
90
$sql = "DELETE FROM participants2 WHERE pt_id = " . $_POST['id'];
91
show_MySQL_table2("localhost", "yoichi", "", "test", $sql, -1, 0,
"");
92 ?>
93
<p><font color="red">One record has been deleted.</font></p>
94
<a href="rdb_browse.php">Return to Data Browser</a>
95 <?php
96 } else {
97
/* Show record to be deleted once again */
98
$sql = "SELECT pt_id, participant_name, province_name FROM
participants2, province WHERE province_id = pv_id AND pt_id = " .
$_GET['id'];
99
$num_found = show_MySQL_table2("localhost", "yoichi", "", "test",
$sql, -1, 0, "");
100
if ($num_found == 0) {echo ("No record found"); die;}
101 ?>
9

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

<!-- Show confirmation message and YES/NO button -->


<p><font color="red">Are you sure to delete this record?</font></p>
<FORM method="POST">
<INPUT type="hidden" name="id" value="<?php echo ($_GET["id"]);
?>">&nbsp;
106
<INPUT type="submit" name="submit" value="YES">&nbsp;
107
<INPUT type="submit" name="submit" value="NO">
108
</FORM>
109 <?php
110 }
111 ?>
112 </body></html>
102
103
104
105

show_MySQL_table2.php
1 <?php
2 function show_MySQL_table2 (
3 $host_name, $user_name, $password, $database_name,
4 $sql, $offset, $num_rows, $id_field)
5{
6 /* Connect to MySQL database */
7 $link = mysql_connect($host_name, $user_name, $password) or die;
8 mysql_select_db($database_name) or die;
9
10 /* Execute SQL command */
11 $result = mysql_query($sql);
12 if (!$result) {
13 echo "<B>(Error in SQL)</B> " . mysql_error();
14 die;
15 }
16
17 /* If the SQL command is not SELECT, then stop function here */
18 if (strtoupper(substr($sql,0,6)) != "SELECT") {
19
mysql_close($link);
// Closing connection
20
return;
21 }
22
23 /* Get number of records found */
24 $num_found = mysql_num_rows($result);
25
26 if ($num_found == 0 ) {
27
mysql_close($link);
// Closing connection
28
return 0;
29 }
30

10

ADMTC-UCSC-University of Colombo

Basics of PHP - 4

31 /* Output results as HTML table */


32 echo "<table border>\n";
33 /* Output field names as table header */
34 echo "<tr>\n";
35 if ($id_field != "") echo "<th bgColor='red'>mark</th>";
36 for ($field=0; $field<mysql_num_fields($result); $field++) {
37 echo "<th>" . mysql_field_name($result, $field) . "</th>\n";
38 }
39 echo "</tr>\n";
40
41 /* Output all records */
42 for ($row = 0; $row < mysql_num_rows($result); $row++) {
43
$line = mysql_fetch_array($result, MYSQL_ASSOC);
44
if ($offset <0 || $row >= $offset && $row < $offset + $num_rows) {
45
echo "<tr>\n";
46
if ($id_field != "") echo "<td align='center'><input type='radio'
name='selected' value='". $line[$id_field] . "'></td>";
47
foreach ($line as $cell) {
48
if (is_numeric($cell)) {
49
echo "<td align='right'>";
50
echo number_format($cell);
51
echo "</td>\n";
52
} else {
53
echo "<td>$cell</td>\n";
54
}
55
}
56
echo "</tr>\n";
57
}
58 }
59 echo "</table>\n";
60
61 /* Closing procedures */
62 mysql_free_result($result);
// Free result
63 mysql_close($link);
// Closing connection
64 return $num_found;
65 }
66 ?>

11

You might also like