HANDOUT TITLE:

INTRODUCTION TO PHP AND MySQL – TRY
THIS! EXERCISE 5 – TESTING ODD AND EVEN
NUMBERS
The following example, using conditional statements, will ask the user to enter a number into
a web form, test it to see whether it is odd or even and return a corresponding message.
1.
If you have not already done so, create a new folder in your My PHP Sites folder called
Beginning PHP.
2.
If you have not already done so, create a new Dreamweaver site pointing to this folder.
You will need to add Remote Info and Testing Server information, and create a new folder
on the server Beginning_PHP to which you will publish.
3.
Open a new PHP file, and enter the following code:
<!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>
<title>Testing Odd and Even Numbers</title>
</head>
<body>
<h2>Testing Odd and Even Numbers</h2>
<?php
//If form not yet submitted then display form
if(!isset($_POST['submit'])) {
?>
<form method = "post" action = "oddeven.php">
Enter value: <br />
<input type = "text" name = "num" size = "3" />
<br />
<input type = "submit" name = "submit" value = "Submit" />
<br />
</form>
<?php
//If form submitted, then process form input
}
81920264
Page 1 of 3
Version 2
else {
//Retrieve number from POST submission
$num = $_POST['num'];
//Test value for evenness and display appropriate message
if(($num % 2) == 0) {
echo 'You entered ' . $num . ', which is an even number.';
}
else {
echo 'You entered ' . $num . ', which is an odd number.';
}
}
?>
</body>
</html>
4.
Save your PHP file as oddeven.php.
5.
Publish your file, and view the published file in a browser. Enter a number and click the
Submit button.
81920264
Page 2 of 3
Version 2
Note: This program consists of two sections. The first half generates a web form for the user
to enter a value, while the second half checks whether the value is odd or even and displays an
appropriate message. In many cases, these two sections would be in separate files. Here, they
have been combined into a single PHP script by the use of a conditional statement.
How does it work? When the web form is submitted, the $_POST variable will contain an entry
for the <input type='submit'...> element. A conditional test then checks for the presence or
absence of this variable. If absent, the program understands that the web form has not been
submitted yet and so displays the form’s elements. If present, the program understands that the
web form has been submitted and it then proceeds to test the input value.
Testing the input value for evenness is handled by a second if-else conditional statement. Here,
the conditional expression consists of dividing the input value by 2 and testing if the remainder
is zero. If this test returns true, one message is displayed - else, another message is displayed.
81920264
Page 3 of 3
Version 2