Jump to content

Recommended Posts

I have a mostly working example of a real form I'm building for a website and would like to ask some questions about the parts I don't understand.

 

This is my first form validation code in PHP. I'm very new to PHP but have coded in several other languages over the years, including form validation, so it's mostly a matter of learning how to do this in PHP rather than learning how to do it from scratch in my first language. The basic approach was taken from a reply to another question I asked in the Design portion of these forums.

 

Here is my form, called topic_proposal.shtml:

<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css" media="screen"/>
<link rel="stylesheet" type="text/css" href="css/print.css" media="print"/>
</head>
<body>
<h1>Meeting Topic Proposal Form</h1>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>Use this form to make a suggestion for a future meeting topic. All of the fields are mandatory, except for the Comments field. Complete the form and press the Submit button. To clear the form without submitting it, press the Reset button.</p>
Topic proposal submitted by: <input type="text" name="proposer" size="30" value=""/></br></br>
<fieldset><legend>Proposed Topic</legend>
Topic Title: <input type="text" name="topic" size="50" value=""/></br></br>
Author/Director: <input type="text" name="creator" size="30" value=""/></br></br>
Topic Type:
<select name="topic_type">
<option value="Book">Book</option>
<option value="Film">Film</option>
<option value="TV">TV (Movie, Series, or Miniseries)</option>
<option value="Theme">Theme</option>
<option value="Other">Other</option>
</select></br>
</fieldset>
<br/><br/>
<fieldset><legend>Availability</legend>
Library Availability:
<input type="radio" name="library_availability" value="Yes">Yes   
<input type="radio" name="library_availability" value="No">No   
<input type="radio" name="library_availability" value="N/A">N/A</br></br>
Bookstore Availability (Mass-market paperback or Trade paperback):
<input type="radio" name="bookstore_availability" value="Yes">Yes   
<input type="radio" name="bookstore_availability" value="No">No   
<input type="radio" name="bookstore_availability" value="N/A">N/A</br></br>
</fieldset>
<br/><br/>
Brief Synopsis:<br>
<textarea name="synopsis" rows="10" cols="50"></textarea></br></br>
Additional Comments:<br>
<textarea name="comments" rows="10" cols="50"></textarea></br></br>
<input type="hidden" name="_submit_check" value="1"/>
<input name="submitForm" id="submitForm" type="submit" value="Submit" />
<input name="reset" id="reset" type="reset" value="Reset" />
</form>
</body>
</html>

 

This is the confirmation if the insert of the new row works correctly, topic_proposal_accepted.shtml:

 

<!DOCTYPE html>
<html>
<head>
<title>Thank You!</title>
</head>
<body>
<h1>Thank you!</h1>
<p>Your proposed topic has been added to the database. It will be considered at the next planning session. Planning sessions are typically held during the regular June and December meetings.</p>
<p>You can <a href="topic_proposal.php">make another suggestion</a> or <a href="index.shtml">return to the home page</a>.</p>
</body>
</html>

 

And this is the php code that shows and validates the form, topic_proposal.php:

 

<?php
$debug = 1;
$Defaults = array();
$Errors = array();
include('topic_proposal.shtml');


if ($debug) {
 echo 'Current php version: ' . phpversion() . '<br/>'; //Gives 5.3.19 on absolut server on 2013-01-18
 echo 'Request method: ' . $_SERVER['REQUEST_METHOD'] . '<br/>'; //determine request method
}

if ($debug) {echo "Count: " . count($_POST) . "<br/>";}

/* If any of the form elements were completed, validate them. If all elements were valid, insert a record
 * to the database. */
if (count($_POST) > 0) {
	 $Defaults = $_POST;

	 $proposer = $_POST['proposer'];
	 $topic = $_POST['topic'];
	 $creator = $_POST['creator'];
	 $topic_type = $_POST['topic_type'];
	 $library_availability = $_POST['library_availability'];
	 $bookstore_availability = $_POST['bookstore_availability'];
	 $synopsis = $_POST['synopsis'];
	 $comments = $_POST['comments'];

	 if ($debug) {
		 echo "Proposer: $proposer<br/>";
		 echo "Topic: $topic<br/>";
		 echo "Creator: $creator<br/>";
		 echo "Topic type: $topic_type<br/>";
		 echo "Library availability: $library_availability<br/>";
		 echo "Bookstore availability: $bookstore_availability<br/>";
		 echo "Synopsis: $synopsis<br/>";
		 echo "Comments: $comments<br/>";
	 }

	 /* Verify that all mandatory fields contain data. The radio buttons and dropdown lists will inevitably contain
		 * so assume that it is accurate.
		 */
	 if (empty($proposer) || strlen(trim($proposer))==0) {
			 $Errors[] = 'The name of the person proposing the topic is a required field. Example: Bob T.';
	 }

	 if (empty($topic) || strlen(trim($topic))==0) {
			 $Errors[] = 'The topic is a required field. Example: The War of the Worlds';
	 }

	 if (empty($creator) || strlen(trim($creator))==0) {
		 $Errors[] = 'The creator is a required field. Example: H. G. Wells';
	 }

	 if (empty($synopsis) || strlen(trim($synopsis))==0) {
		 $Errors[] = 'The synopsis is a required field. Example: A short story about the consequences of time travel.';
	 }

	 /* Verify that no text field or text area contains more data than the maximum for that field. */
	 if (strlen(trim($proposer))>30) {
		 $Errors[] = 'The proposer cannot exceed 30 characters. Please shorten your input.';
		 //colour any input over the maximum length red so user knows how short it needs to be
	 }

	 if (strlen(trim($topic))>50) {
		 $Errors[] = 'The topic cannot exceed 50 characters. Please shorten your input.';
	 }

	 if (strlen(trim($creator))>30) {
		 $Errors[] = 'The creator cannot exceed 30 characters. Please shorten your input.';
	 }

	 if (strlen(trim($synopsis))>500) {
		 $Errors[] = 'The proposer cannot exceed 500 characters. Please shorten your input.';
	 }

	 if (strlen(trim($comments))>500) {
		 $Errors[] = 'The comments cannot exceed 500 characters. Please shorten your input.';
	 }

	 /* Cross checks */
	 //If the type is Theme, library and bookstore availability must be N/A.
	 if ($topic_type = 'Theme') {
		 if ($library_availability = 'Yes' || ($library_availability = 'No')) {
			 $Errors[] = "When the topic type is Theme, library availability must be N/A. Please change it.";
		 }
		 if ($bookstore_availability = 'Yes' || ($bookstore_availability = 'No')) {
			 $Errors[] = "When the topic type is Theme, bookstore availability must be N/A. Please change it.";
		 }
	 }

	 //If the type is Book, library and bookstore availability must be Yes or No.
	 if ($topic_type = 'Book') {
		 if ($library_availability = 'N/A') {
			 $Errors[] = "When the topic type is Book, library availability must be Yes or No. Please change it.";
		 }
		 if ($bookstore_availability = 'N/A') {
			 $Errors[] = "When the topic type is Book, bookstore availability must be Yes or No. Please change it.";
		 }
	 }


	 if (count($Errors)==0){
				 echo "<h3>Your data has all been validated successfully. Attempting to insert into database...</h3>";

			 Insert_Proposal($proposer, $topic, $creator, $topic_type, $library_availability, $bookstore_availability, $synopsis, $comments);

	 }
	 else {
		 echo "<p>The form contains errors as noted below. Please fix them and then press the Submit button again.</p>";
		 foreach ($Errors as $oneError) {
			 echo "<p>" . $oneError . "</p>";
		 }
	 }
}

function Insert_Proposal($proposer, $topic, $creator, $topic_type, $library_availability, $bookstore_availability, $synopsis, $comments) {
 $debug = 1; //temporary

 include('#php-signin-insert.shtml'); //Sign in, connect and select database

 $date_proposed = date('Y-m-d'); //The date is generated here, not obtained from the form.

 if ($debug) {
	 echo "Date proposed: $date_proposed<br/>";
	 echo "Proposer: $proposer<br/>";
	 echo "Topic: $topic<br/>";
	 echo "Creator: $creator<br/>";
	 echo "Topic type: $topic_type<br/>";
	 echo "Library availability: $library_availability<br/>";
	 echo "Bookstore availability: $bookstore_availability<br/>";
	 echo "Synopsis: $synopsis<br/>";
	 echo "Comments: $comments<br/>";
 }

 $insert = "INSERT INTO TopicProposals (Date_Proposed, Proposer, Topic, Creator, Topic_Type, Library_Availability, Bookstore_Availability, Synopsis, Comments)
		 VALUES ('$date_proposed', '$proposer', '$topic', '$creator', '$topic_type', '$library_availability', '$bookstore_availability', '$synopsis', '$comments')";

 echo "Insert statement: " . $insert . '<b/>';

 $result = mysql_query($insert, $con);

 if (!$result) {
	 throw new Exception('Insert of Topic Proposal into table failed. Please contact the webmaster. Error number: ' . mysql_errno($con) . '. Error message: ' . mysql_error($con));
 }

 include('topic_proposal_accepted.shtml');

 mysql_close($con);	
}
?>

I won't bother showing you #php-signin-insert.shtml since it is working fine; it simply initializes a few variables, gets the connection and then selects the appropriate database. I'm also not showing you the definition of the database table since I can't think of a good reason for you wanting to see it. All the fields in the table are Varchars, except for date_proposed, which is a Date. If you execute this code, just comment out the Insert statement and the exception handling for the insert and you should be good to go.

 

As I said, the code mostly works and will successfully insert records into the MySQL database as long as a I comment out the cross-checks involving topic_type, library_availability and bookstore_availability. That's my first question.

 

1. If I complete the form by choosing a topic type of Book, all four of the cross-check errors are displayed, even if I have chosen Yes or No for the bookstore and library availability radio buttons. Why?

2. If the cross-checks detect an error, the error messages are displayed but the form itself gets blanked out, as if the Reset button had been clicked. Why?

3. If the edits show no errors and the insert is successful, the "Thank you" page appears at the end of the page, not on a new page. What would I need to do put the "Thank you" page on a fresh page?

4. How can I position the cursor with PHP? I'd like to be able to set the cursor on the first error that is discovered by the edits but I'm not sure how that's done. I don't see anything (relevant) in the PHP manual when I search on "cursor". I gather I can use Javascript to set the focus but I'd rather stay pure PHP if I can. If I must use Javascript, how do I execute Javascript statements within PHP? Or can I just code them as if they were PHP statements?

5. I was going to ask if there is a debugger for PHP in Eclipse, my IDE, but Google has helped me determine that there is. Apparently it can use either Zend or XDebug. Which of the two seems to be the best? I'm running PHP 5.3.19 if that makes a difference. I should mention that I don't have a development environment on my computer; I'm using a hosting service which has PHP installed on it and that's the level they're running. That means I can't alter their setup if it isn't to my liking but, so far, that hasn't been a problem.

Link to comment
https://forums.phpfreaks.com/topic/273400-form-validation-questions/
Share on other sites

Okay, this was apparently too big a question, i..e. too many aspects to it.

 

I figured out the answer to the first question on my own: my cross-checks used = instead of ==; as soon as I caught that, they started working correctly. I'll ask questions two and three in another post unless I just go straight to a framework like JQUERY or AJAX.

 

I got an answer to the fourth question - use JQUERY or something equivalent - on another forum. I'll ask the fifth question in another post.

Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.