You are on page 1of 15

Basic PHP System: View/Edit/Delete/Add Records

It's a basic system that allows you to:


-- view existing records
-- edit existing records
-- delete existing records
-- add new records

DATABASE:
-- You'll need to create a database (I named mine 'records' but it can be changed) using PHPMyAdmin

--
-- Table structure for table `students`
--
CREATE TABLE `students` (
‘id` int(11) NOT NULL auto_increment,
‘student_number’ int(10) NOT NULL,
‘firstname’ varchar(32) NOT NULL,
‘lastname’ varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `students`
--

INSERT INTO `students` VALUES(1, 'Bob', 'Baker');


INSERT INTO `students ` VALUES(2, 'Tim', 'Thomas');
INSERT INTO `students ` VALUES(3, 'Rachel', 'Roberts');
INSERT INTO `students ` VALUES(4, 'Sam', 'Smith');
How to Create a Database and tables using PHPMyAdmin

1. Click phpMyAdmin

2. PHPMyAdmin will display. Click Databases


3. Type the name of the database
Database name: Records

4. Type the table name and number of columns, click Go.


Table name: students
No. of columns: 4
5. Enter the data type of each column

How to see the structure of your tables

1. Click the Structure tab

1.
How to insert a record
1. Click the insert tab. Type the values for your table

CODES:
CONNECT_DB.PHP

<?php
/*
CONNECT_DB.PHP
Allows PHP to connect to your database
*/

// Database Variables (edit with your own server information)


$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'records';

// Connect to Database
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());

?>

VIEW.PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>

<?php
/*
VIEW.PHP
Displays all data from 'students' table
*/

// connect to the database


include('connect_db.php');

// get results from database


$result = mysql_query("SELECT * FROM students")
or die(mysql_error());

// display data in table


echo "<p><b>View All</b> | <a href='view_paginated.php?page=1'>View Paginated</a></p>";

echo "<table border='1' cellpadding='10'>";


echo "<tr> <th>ID</th> <th>Student Number</th> <th>First Name</th> <th>Last Name</th>
<th>Operation</th> <th></th></tr>";

// loop through results of database query, displaying them in the table


while($row = mysql_fetch_array( $result )) {

// echo out the contents of each row into a table


echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['student_number'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td><a href="edit_record.php?id=' . $row['id'] . '">Edit</a></td>';
echo '<td><a href="delete_record.php?id=' . $row['id'] . '">Delete</a></td>';
echo "</tr>";
}

// close table>
echo "</table>";
?>
<p><a href="new_record.php">Add a new record</a></p>

</body>
</html>
NEW_RECORD.PHP
<?php
/*
NEW_RECORD.PHP
Allows user to create a new entry in the database
*/

// creates the new record form


// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($student_number,$first, $last, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>

<form action="" method="post">


<div>
<strong>Student Number: *</strong> <input type="text" name="student_number" value="<?php echo
$student_number; ?>" /><br/>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $first; ?>"
/><br/>
<strong>Last Name: *</strong> <input type="text" name="lastname" value="<?php echo $last; ?>"
/><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}

// connect to the database


include('connect_db.php');

// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$student_number = mysql_real_escape_string(htmlspecialchars($_POST['student_number']));
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));

// check to make sure both fields are entered


if ($firstname == '' || $lastname == '' ||$student_number=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';

// if either field is blank, display the form again


renderForm($student_number,$firstname, $lastname, $error);
}
else
{
// save the data to the database
mysql_query("INSERT students SET student_number='$student_number', firstname='$firstname',
lastname='$lastname'")
or die(mysql_error());

// once saved, redirect back to the view page


header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','');
}
?>
EDIT_RECORD.PHP
<?php
/*
EDIT_RECORD.PHP
Allows user to edit specific entry in database
*/

// creates the edit record form


// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id,$student_number, $firstname, $lastname, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>

<form action="" method="post">


<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Student Number: *</strong> <input type="text" name="student_number" value="<?php echo
$student_number; ?>"/><br/>
<strong>First Name: *</strong> <input type="text" name="firstname" value="<?php echo $firstname; ?>"/><br/>
<strong>Last Name: *</strong> <input type="text" name="lastname" value="<?php echo $lastname; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}

// connect to the database


include('connect_db.php');

// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$student_number = mysql_real_escape_string(htmlspecialchars($_POST['student_number']));
$firstname = mysql_real_escape_string(htmlspecialchars($_POST['firstname']));
$lastname = mysql_real_escape_string(htmlspecialchars($_POST['lastname']));

// check that firstname/lastname fields are both filled in


if ($firstname == '' || $lastname == '' || $student_number=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';

//error, display form


renderForm($id,$student_number, $firstname, $lastname, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE students SET student_number='$student_number',firstname='$firstname',
lastname='$lastname' WHERE id='$id'")
or die(mysql_error());

// once saved, redirect back to the view page


header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{

// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM students WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);

// check that the 'id' matches up with a row in the databse


if($row)
{

// get data from db


$student_number = $row['student_number'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];

// show form
renderForm($id,$student_number, $firstname, $lastname, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
DELETE_RECORD.PHP
<?php
/*
DELETE_RECORD.PHP
Deletes a specific entry from the 'students' table
*/

// connect to the database


include('connect_db.php');

// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get id value
$id = $_GET['id'];

// delete the entry


$result = mysql_query("DELETE FROM students WHERE id=$id")
or die(mysql_error());

// redirect back to the view page


header("Location: view.php");
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
header("Location: view.php");
}

?>
VIEW_PAGINATED.PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
</head>
<body>

<?php
/*
VIEW-PAGINATED.PHP
Displays all data from 'STUDENTS' table
This is a modified version of view.php that includes pagination
*/

// connect to the database


include('connect_db.php');

// number of results to show per page


$per_page = 3;

// figure out the total pages in the database


$result = mysql_query("SELECT * FROM students");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);

// check if the 'page' variable is set in the URL (ex: view_paginated.php?page=1)


if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];

// make sure the $show_page value is valid


if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}

// display pagination

echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";


for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view_paginated.php?page=$i'>$i</a> ";
}
echo "</p>";

// display data in table


echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Student Number</th><th>First Name</th> <th>Last Name</th> <th></th>
<th></th></tr>";

// loop through results of database query, displaying them in the table


for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }

// echo out the contents of each row into a table


echo "<tr>";
echo '<td>' . mysql_result($result, $i, 'id') . '</td>';
echo '<td>' . mysql_result($result, $i, 'student_number') . '</td>';
echo '<td>' . mysql_result($result, $i, 'firstname') . '</td>';
echo '<td>' . mysql_result($result, $i, 'lastname') . '</td>';
echo '<td><a href="edit.php?id=' . mysql_result($result, $i, 'id') . '">Edit</a></td>';
echo '<td><a href="delete.php?id=' . mysql_result($result, $i, 'id') . '">Delete</a></td>';
echo "</tr>";
}
// close table>
echo "</table>";

// pagination

?>
<p><a href="new_record.php">Add a new record</a></p>

</body>
</html>

You might also like