quest4tech.net

 

A BASIC COUNTER IN PHP


  Example of a basic counter in php for incrementing a count. The program uses a form to enter numbers
and a session variable to hold the count.
  The web page first shows a form which asks for starting number. When a number is entered and the form
submitted, the page is refreshed. The web page then shows the starting count as the latest count.
It also shows a form to enter a number to increment the count. As the form is incremented so each page
is refreshed to show the latest count.

<?php 
session_start();
// Starts a session for the period of the program.

// Check if the form has been submitted.
if(!isset($_POST["action"]))
{
?>

  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
      <br> Name: <input type="text" name="start" size="20" maxlength="50">
      <input type="hidden" name="action" value="submitted">
      <input type="submit" name="Enter" VALUE="Enter">
  </form>
      
<?php
} else {
// After the number has been submitted it is stored in a count session
// variable at the server.  The number the session variable will be used
// to show the count as it is incremented.

if ($_POST['start'] > ""){
// Receive a value for start and check it has a value and if so store it.
   $_SESSION['count'] = $_POST['start'];
   echo "Latest count = ".$_SESSION['count']."<br>"; 
}
// After the number has been stored a second form is shown to increment the count.
 
if ($_POST['increment'] >""){
       $_SESSION['count'] = $_SESSION['count'] + $_POST['increment'];
	   echo "Latest count  = ".$_SESSION['count']."<br>"; 
}
	   
?>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>"" method="post">
      <br> Increment count by: <input name="increment" value=1 size='10' maxlength='10'>
      <input type="hidden" name="action" value="submitted">
      <input type="submit" name="Enter" VALUE="Enter">
  </form>
  
<?php       
} 
?>

When the form is submitted the data is sent to the server by the $_SERVER['PHP_SELF'] command.
From this simple example more complex forms and means of data entry can be designed. Click here to see a working example of the counter.
 

Main Index

(c) Compiled by B V Wood.

 Main Index

UK SPONSERS

 
USA SPONSERS