A Complete, Practical Example

Now that you know how to use the basics of cPanel, HTML, CSS and PHP, you can actually combine all of this information to make a working, practical example to use on your websites.

For this tutorial, this practical example will essentially be a contact form on your website where you will collect the visitors name, email address, and their message/comment.

This example is also going to include an HTML table on the same page that will show all of the previously saved messages that have been entered. Obviously, you would NOT want to use this actual example on a live website because it would share all of that information with your public visitors, but this example should show you how you could use one page to collect the information and a second page to use for yourself to view the information that people have entered.

Here is the complete, working example - just copy and paste this code into a WordPress page/post to try it out (be sure to have EXEC-PHP plugin installed and active on the site):

<?php
 
// This function is used to retrieve the saved messages from the database // The messages are returned as an array function myf_get_messages()
 
{
 
// Be sure to bring $wpdb into the local scope of the function to use it global $wpdb;
 
// Setting a temporary variable as a blank string, which will be returned // If no results are found in the database $tmp_string = '';
 
// Create a MYSQL query to pull the results from the database
 
$sql = 'SELECT * FROM '.$wpdb->prefix.'myform ORDER BY myfid DESC';
 
// Process the MYSQL query with $wpdb->get_results
 
// Results are saved as the array $rows
 
$rows = $wpdb->get_results($sql, ARRAY_A);
 
// The PHP command COUNT tells you how many items are in an array // This IF statement is looking to see if there are results found if (count($rows) > 0)
 
{
 
// This code is only reached when results are found
 
// To start, we will save the variable $tmp_string with some HTML
 
// This HTML will create the table to display the information 
 
$tmp_string = '<table class="myf-comment-list-table"><thead><tr><th>ID # /
 
Date / Name / Email Address</th><th>Message /
 
Comment</th><th>Delete</th></tr></thead><tfoot><tr><th>ID # / Date / Name / Email Address</th><th>Message</th><th>Delete</th></tr></tfoot><tbody>';
 
// Now I want to loop through each of the database results that were found // Use the FOREACH command to do so
 
// Since $rows is holding the database results, I use that first with FOREACH // Then I use the word 'as' and finally I specify a new variable name to // store each of result as it is looped through. foreach ($rows as $row)
 
{
 
// $row['myftime'] contains a timestamp of the date/time when this // message was saved. I want to turn this into something I can read.
 
// This is done using the DATE command. I give an argument to that // command to format the timestamp and another to provide the number. $tmptime = date('m/d/Y H:i:s', $row['myftime']);
 
// Each time this code is processed, $row will contain a different
 
// database result, so I am going to add to the $tmp_string each
 
// time to add this result to the table. Note that I reference each
 
// item as variable in the $row array! I have also used a new PHP
 
// function here - STRIPSLASHES - this removes forward slashes
 
// from text, which may have been added when saving that text in
 
// the database (this happens when you have things like quotes in your text).
 
// Also note that I have added a form here with a Delete button so you
 
// can delete records from this database.
 
$tmp_string .= '<tr><td><strong>ID #:</strong> '.$row['myfid'].'<br />'. $tmptime.'<br />'.stripslashes($row['myfname']).'<br
 
/>'.stripslashes($row['myfemail']).'</td><td>'.stripslashes($row['myfcomment']).'</td><td><f orm method="post"><input type="hidden" name="myfid" value-".$row['myfid'].'" /><input type="submit" name="myfdelete" value="Delete" /></form></td></tr>';
 
}
 
// After looping through all of the results, I need to add some closing HTML // for my table to the $tmp_string variable.
 
$tmp_string .= '</tbody></table>';
 
}
 
// Now I return the value of $tmp_string when this function is called // This value will be blank is no results were found in the database return $tmp_string;
 
}
 
// Call $wpdb in the local scope to use. We did this already for the function,
 
// but functions do not operate in the same local scope as code outside of functions. global $wpdb;
 
// Next, I am going to set some default values (which will be blank as default)
 
// The first three store the default values to show in the HTML form on the page // These can be set in this PHP code when someone saves the form without completing // all of the information it needs to process (this keeps the information entered in the form // from being lost).
 
$myfname = '';
 
$myfemail = '';
 
$myfcomment = '';
 
// These two default values are for error and success messages that can be shown on the page. // They are only set in the code when they need to be displayed.
 
$myferror = '';
 
$myfsuccess = '';
 
// This holds the saved database results table, which will be blank if there are no results $myf_comment_list = '';
 
// This looks in the global variable array, $_POST, to see if someone has clicked the button // to save a new message to the database. if ($_POST['myfsave'] == 'Save')
 
{
 
// This IF statement test ensures that the form information is not blank before proceeding if ($_POST['myfname'] != '' && $_POST['myfemail'] != '' && $_POST['myfcomment'] ! =
 
")
 
{
 
// Now we create the MYSQL query to save the form information $sql = 'INSERT INTO '.$wpdb->prefix.'myform SET myftime = %d, myfname = %s, myfemail = %s, myfcomment = %s';
 
// The data array is populated with the POST global array variables $data_array = array(time(), $_POST['myfname'], $_POST['myfemail'], $_POST['myfcomment']);
 
// Now we process the MYSQL query with the data array to save to the database $wpdb->query($wpdb->prepare($sql, $data_array));
 
// This variable gets set to display this success message on the page $myfsuccess = 'Message successfully saved in the database!';
 
}else{
 
// This code only runs when a new message Save button is clicked but all of the // form information is not provided. This sets an error message and also sets // default form values to ensure information already entered is not lost. $myferror = 'Please fill out the entire form before submitting it!';
 
$myfname = stripslashes($_POST['myfname']);
 
$myfemail= stripslashes($_POST['myfemail']);
 
$myfcomment= stripslashes($_POST['myfcomment']);
 
}
 
}
 
// This detects if a delete button has been clicked if ($_POST['myfdelete'] == 'Delete')
 
{
 
// This checks the hidden form field, myfid
 
// (int) converts the posted value to a whole number, which it should already be // This is used as a security measure to ensure that the value is a realistic value // and not malicious code.
 
$myfid = (int) $_POST['myfid'];
 
// Now I only proceed if $myfid is greater than 0 if ($myfid > 0)
 
{
 
// This creates the MYSQL query to delete this one row of information // from the database. Notice that I used $myfid directly on the end of the query // instead of using a placeholder, like %d. This is done because I have already // verified this user input myself (I know it is a whole number greater than 0). $sql = 'DELETE FROM '.$wpdb->prefix.'myform WHERE myfid = '.$myfid;
 
// Now I process the MYSQL query using $wpdb->query $wpdb->query($sql);
 
// And then I set a message for the success variable to be displayed on the page $myfsuccess = 'The message was successfully deleted from the database!';
 
}
 
}
 
// This calls the function from the beginning of this code to retrieve the saved messages $myf_comment_list = myf_get_messages();
 
// The rest of the code below is the actual HTML and CSS code for my page, while // everything above is PHP code that is used to process information for this page // I have also used some random PHP code below to help make this page dynamic (it changes // depending on what is happening on the page).
 
// To start, I am providing the CSS code that will control the design of this page // Everything here should be information that was already covered in the CSS tutorial. ?><style type="text/css">
 
.myf-new-comment-box { padding:10px; background-color:#eeeeee; border:1px solid #666666; margin-bottom :30px;
 
}
 
.myf-new-comment-box label { font-size:16px; font-weight:bold; color:#000000;
 
}
 
.myferror-message { padding:5px;
 
background-color:#FFE0E0; border:1px solid #B33B3B; margin-top:10px; margin-bottom: 10px; font-weight:bold;
 
}
 
.myfsuccess-message { padding:5px;
 
background-color:#FCFFE0; border:1px solid #676E2A; margin-top:10px; margin-bottom: 10px; font-weight:bold;
 
}
 
.myf-comment-list-empty { padding:10px;
 
background-color:#FFE0E0; border:1px solid #B33B3B; font-weight:bold;
 
}
 
</style>
 
<?php
 
// Now I am beginning the HTML code for my page (everything below these comments)
 
// Note how I have also used some PHP code below. In some instances, I have used the PHP // code to determine whether to display additional HTML code or not (for the error or success // messages, for example). I have also used PHP code to echo variables in this HTML code,
 
// which may be used for the error/success messages or to show default values in the form.
 
?>
 
<div class="myf-new-comment-box">
 
<form method="post">
 
<?php if ($myferror != '') { ?>
 
<div class="myferror-message"><?php echo $myferror; ?></div>
 
<?php } ?>
 
<label for="myfname">Name</label>
 
<input type="text" name="myfname" value="<?php echo $myfname; ?>" size="48" /><br
 
/>
 
<label for="myfemail">Email Address</label>
 
<input type="text" name="myfemail" value="<?php echo $myfemail; ?>" size="48" /><br
 
/>
 
<label for="myfcomment">Message / Comments</label>
 
<textarea name="myfcomment" rows="5" cols="50"><?php echo $myfcomment; ? ></textarea>
 
<br /><input type="submit" name="myfsave" value="Save" />
 
</form>
 
</div>
 
<?php
 
// Everything below here is HTML/PHP code for the success message and the table that // lists the saved messages in the database. I have even used a more complicated IF, ELSE // statement here to change the HTML that is shown on the page depending on whether // saved messages exist in the database or not.
 
?>
 
<?php if ($myfsuccess != '') { ?>
 
<div class="myfsuccess-message"><?php echo $myfsuccess; ?></div>
 
<?php } ?>
 
<?php if ($myf_comment_list != '') { ?>
 
<div class="myf-comment-list"><?php echo $myf_comment_list; ?></div>
 
<?php }else{ ?>
 
<div class="myf-comment-list-empty">There are no saved messages / comments in the database.</div>
 
<?php } ?>

© PHP Training Guide

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (25.08.2014)
Views: 757 | Rating: 0.0/0
Total comments: 0
avatar