954,178 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

PHP form validation

Hey this is a code to print the times table of a particular number entered by a user, The thing is I want to validate the form so that it checks to see if what is entered is numeric, and ranges from 1 to 12 if not I want it to display an error.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
 <form method="post" "<?php echo $PHP_SELF;?>"> 
 Enter Number:<input type="text" name="Number" />
  
 <input type="submit" value="Show Time table"/> 
  
 </form> 

</body>
</html>
<?php
if (array_key_exists('Number',$_POST)) 
{
$numbers=range(1,12);
$Number = $_POST['Number'];
foreach($numbers as $times)
{
    echo '<tr>';
          
         $output = $Number * $times;      
        echo "<tr style='text-align: center'>$Number x $times = $output
</tr>";
     echo '</tr>';
    echo '</tr>';
	}
}
 ?>
KBL
Newbie Poster
19 posts since Mar 2010
Reputation Points: 10
Solved Threads: 0
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Untitled Document</title>
	</head>
	
	<body>
		<form method="post" action="<?php echo $PHP_SELF;?>">
			Enter Number:<input type="text" name="Number" />
			
			<input type="submit" value="Show Time table"/>
			
		</form>
		
	</body>
</html>
<?php
$numbers=range(1,12);
$Number = $_POST['Number'];
if ($Number < 1 or $Number > 12) {
	// insert code to display an error
}
else {
	foreach($numbers as $times) {
		echo '<tr>';

		$output = $Number * $times;
		echo "<tr style='text-align: center'>$Number x $times = $output
			</tr>";
		echo '</tr>';
		echo '</tr>';
	}
}
?>

This should do it. A form also needs an action. As you can see, there is no need to test for numeric input. If you enter anything else no output is generated.

colweb
Posting Whiz
318 posts since Nov 2007
Reputation Points: 34
Solved Threads: 52
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You