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

(Anyone with PHP knowledge is welcome to comment on the code. If there are issues I haven't noticed, please let me know. Do realize that it is intended for beginners, so I didn't want to do anything too advanced that might lead to confusion. Yes, I realize I could use OOP, or could separate some of these out into methods, etc. etc.)

OK... Here's some code for you to play with. It's a basic system that allows you to:
-- view existing records
-- edit existing records
-- delete existing records
-- add new records

Online demo:
http://www.falkencreative.com/forum/records/view.php

Basically, just imagine that you are in charge of a sports team, and you want to keep a list of all your player's contact information. The code I've created could be a starting point for that (it only includes fields for their first name/last name, but could obviously could be expanded to use more fields).

This is just a basic starting point for projects that require view/edit/delete functionality. I know it may seem a lot to understand at first, but read all the comments in the code -- I try to explain what I am doing step by step. I'm also happy to help with any questions (please post questions in a new topic.)

How to create a system that allows a user to add/edit/remove data in a database seems to be a commonly asked topic, so I may adapt this into an actual tutorial at some point in the future.

DATABASE:
-- You'll need to create a database (I named mine 'records' but it can be changed) using PHPMyAdmin
-- Save the included sql file on your desktop as a .txt file
-- Once you've created the database, make sure the database is selected, then click the "import" tab
-- Select the .txt file on your desktop, and import it into your database. PHPMyAdmin will create all of the necessary tables/import some test data for you to play with

SQL file:

--
-- Table structure for table `players`
--

CREATE TABLE `players` (
  `id` tinyint(4) NOT NULL auto_increment,
  `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 `players`
--

INSERT INTO `players` VALUES(1, 'Bob', 'Baker');
INSERT INTO `players` VALUES(2, 'Tim', 'Thomas');
INSERT INTO `players` VALUES(3, 'Rachel', 'Roberts');
INSERT INTO `players` VALUES(4, 'Sam', 'Smith');

Save these php files all in the same folder in a place where you can run them using your server (I'm assuming you are using something like WAMP for the server? I'm not sure if Dreamweaver includes something like that by default.)

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 = 'root';
    $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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>View Records</title>
</head>
<body>

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

    // connect to the database
    include('connect-db.php');

    // get results from database
    $result = mysql_query("SELECT * FROM players") 
        or die(mysql_error());  
        
    // display data in table
    echo "<table border='1' cellpadding='10'>";
    echo "<tr> <th>ID</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
    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['firstname'] . '</td>';
        echo '<td>' . $row['lastname'] . '</td>';
        echo '<td><a href="edit.php?id=' . $row['id'] . '">Edit</a></td>';
        echo '<td><a href="delete.php?id=' . $row['id'] . '">Delete</a></td>';
        echo "</tr>"; 
    } 

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

</body>
</html>    

new.php

<?php
/* 
    NEW.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($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>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
        $firstname = htmlspecialchars($_POST['firstname']);
        $lastname = htmlspecialchars($_POST['lastname']);
        
        // check to make sure both fields are entered
        if ($firstname == '' || $lastname == '')
        {
            // generate error message
            $error = 'ERROR: Please fill in all required fields!';
            
            // if either field is blank, display the form again
            renderForm($firstname, $lastname, $error);
        }
        else
        {
            // save the data to the database
            mysql_query("INSERT players SET 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.php

<?php
/* 
    EDIT.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, $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>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'];
            $firstname = htmlspecialchars($_POST['firstname']);
            $lastname = htmlspecialchars($_POST['lastname']);
            
            // check that firstname/lastname fields are both filled in
            if ($firstname == '' || $lastname == '')
            {
                // generate error message
                $error = 'ERROR: Please fill in all required fields!';
            
                //error, display form
                renderForm($id, $firstname, $lastname, $error);
            }
            else
            {
                // save the data to the database
                mysql_query("UPDATE players SET 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 players 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
                $firstname = $row['firstname'];
                $lastname = $row['lastname'];
            
                // show form
                renderForm($id, $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.php

<?php
/* 
    DELETE.PHP
    Deletes a specific entry from the 'players' 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 players 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");
    }
        
?>

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

That looks as if it will be very useful, Ben.

In new.php you have the comment "making sure it is valid". Can you explain how the code works? I don't see any elseif (empty($firstname) code if a field is left empty.

This site is very useful to find out about functions
http://us2.php.net/manual/en/function.h … lchars.php
and I looked up htmlspecialchars thinking that would check for errors or omissions but it only converts special characters.

Also, would it be a good idea to add a doctype and meta tag for a charset in the head section in view.php?

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

@Wickham

Thanks for the comments! I've added in the doctype/metatag, and made a comment in my post about the validation on the fields. Yes, ideally, I should be checking if either field is is blank, and then generating some sort of error if they are. I guess I missed that when I initially did the coding. At the moment, it is possible to generate a record with just an id value and no data for any of the other fields (no error results from this). I'll see if I can add some basic validation to the code in the near future (as soon as I get the time!)

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

Nice work. This should help those wishing to learn some php. It is also a good start to the Admin side of small applications.

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

Wickham wrote:

In new.php you have the comment "making sure it is valid". Can you explain how the code works? I don't see any elseif (empty($firstname) code if a field is left empty.

A quick update... I have modified my code in the example to include a check to ensure that both cannot be left blank, and to generate a basic error message if they are.