Pages

Basic PHP Crash Course (part 2)

Sunday, March 25, 2012
This post is part 2 of the Basic PHP Crash Course. In part 1, we discuss about the html form, php variable, post method and some operator. In this part, we will discuss about php if() statement and comparison operators by enhancing our pizza shop site.

We created two file index.php and process.php in part 1.
There is no need to change in our index.php.

For our process.php,
we should know whether the form is submitted or not before we process the form. If the user run this url "http://localhost/pizza_shop/process.php" directly, user can get error.
So we have to change in our process.php. Our new process.php is as follow.


<html>
<head>
 <title>Order Process</title>
</head>
<body>
 <?php
 if($_POST['submit']=='Submit Order')
 {
  $cus_name = $_POST['cus_name'];
  $quantity = $_POST['quantity'];
  $address = $_POST['address'];
 ?>
 <p>Thank <?php echo $cus_name; ?> !</p>
 <p>You order <?php echo $quantity; ?> pizza.</p>
 <?php
  $total = $quantity * 10;
 ?>
 <p>It will cost you <?php echo $total; ?> $.</p>
 <p>We will send withing 2 hours to <?php echo $address; ?>.</p>
 <?php } ?>
</body>
</html>

Explanation

Sometime we need to do some action depend on other condition. For this saturation we will use if statement. Below is the idea of the "if" conditional statement.

if

if (this condition is true)
this action will be execute

if...else

if (condition one is true)
action one will be execute
else
action two will be execute

if...elseif...else

if (condition one is true)
action one will be execute
elseif (condition two is true)
action two will be execute
.
.
.
else
last action will be execute

Examples

Below is syntax of the "if" conditional statements.

if


<?php
 $a = 5;
 $b = 3;
 if($a > $b)
  echo "a is greater than b";
?>

if...else


<?php
 $a = 5;
 $b = 7;
 if($a > $b)
  echo "a is greater than b";
 else
  echo "a is less than b"; 
?>

if...elseif...else


<?php
 $a = 5;
 $b = 5;
 if($a > $b)
  echo "a is greater than b";
 elseif($a < $b)
  echo "a is less than b"; 
 else
  echo "a is equal to b";
?>

Note: If your action code is more than one statement, you must use the curly braces {}.

Comparison Operators

PHP has the following comparison operators.
==is equal to
===is identical
!=is not equal
!==is not identical
<>is not equal
>greater than
<less than
>=greater than or equal
<=less than or equal

1 comment: