Pages

Basic PHP Crash Course (part 3)

Thursday, March 29, 2012
This post is part 3 of the Basic PHP Crash Course. If you have never red before this Crash Course, you should read part 1 and part 2 first. Before enhancing our site, I want to explain you about the function.

What is a function?

A function is a block of code that has a name. It is not executed when we load the page. We need to call its name when we need to execute that block of code. And then we can call any time whenever we need it. If you have some code that need to use many time, you should use as the function. The function name can start with a letter or underscore (not a number) To understand the idea of function, we need to create our own simple function.

Simple Function

Let's start with the hello world function.
<?php
  function hello()
  {
   echo "Hello World!";
  }
hello();
?>

Function with parameter

Parameter is a variable that we send to our function to use withing our function.
<?php
  function hello($name)
  {
   echo "Hello ".$name;
  }
hello("Jack");
?>

Function with return value

Return value is a variable that return from our function. Sometime we need a return value
<?php
function add($a,$b)
{
 $result = $a + $b;
 return $result;
}
$total = add(5,3);
echo $total;
echo add(3,5);
?>
We can use the return value like above example and like int our web site.

Enhancing our site

There is no need to change in our index.php. For our process.php, we need to test whether the user fill the form data or not. To determine whether a variable is set, we will use isset() function. In PHP, there are many built-in functions. I create a tutorial about this here. Following is our new process.php
<html>
<head>
 <title>Order Process</title>
</head>
<body>
<?php
if($_POST['submit']=='Submit Order')
{
 if( isset($_POST['cus_name']) && isset($_POST['quantity']) && isset($_POST['address']) )
 {
  $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
    } 
 else
  echo "You need to fill all data";
 ?> 
 <?php } ?>
</body>
</html>

Explanation

Let's talk about isset() function. We will pass at least one parameter and it will return boolean true or false. It will return TRUE if var exists; FALSE otherwise.

Logical Operators

If you need to combine the results of logical conditions, you must be use logical operators. Following table is PHP logical operators.
!NOT
&&AND
||OR
andAND
orOR
xorXOR

2 comments: