Tag Archives: data

Converting variable types in C#

This tutorial explains how to convert variable types in the C# language (eg. convert from string to integer or float, or convert from integer or float to string). Here is a summary of the methods used:

  • float.Parse() – converts to float type
  • int.Parse() – converts to int type
  • .ToString() – converts to string type

Watch the video below and then scroll down to see the sample code.

Example of converting from string to float:

float myFloatVariable = float.Parse(myStringVariable);

Example of converting from string to int:

int myIntVariable = int.Parse(myStringVariable);

Example of converting from int or float to string:

string myStringVariable = myFloatVariable.ToString();

Here is the full sample code from the tutorial video:

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Console.WriteLine("Enter your name: ");
      string username = Console.ReadLine(); // store user input as string
      Console.WriteLine("Hello there, " + username);

      Console.WriteLine("Enter two numbers");
      float num1 = float.Parse(Console.ReadLine()); // convert user input from string to float
      float num2 = float.Parse(Console.ReadLine()); // convert user input from string to float
      Console.WriteLine("The result is: " + (num1 + num2)); // display string of text and float result 

      int num3 = 5;
      int num4 = 10;
      Console.WriteLine(num3.ToString() + num4.ToString()); // convert int to string
    }
  }
}


Next tutorial: Making comparisons in C#

Variables, constants and data types in C#

In this tutorial you will learn about variables, constants and data types in the C# language.

Variables are like containers that can store data that you will use in your application. Variables can be given a value to store that can be accessed and modified or updated throughout the program whereas constants are given a value that can’t be changed in another part of the program – in other words the variable’s value is constant throughout the program.

Variables and constants must be given a unique name (starting with lowercase letter and cannot contain spaces or special characters) and they must have a certain type. A type specifies the kind of data that a variable can hold. A variable that has a name and a type can then have a value assigned to it.

Take a look at the following line of code:

int myNumber = 5;

The line of code above says that a new variable called myNumber is being declared. It is of the int (integer) type and is assigned a value of 5.

The table below shows the data types available in the C# language.

Type Description
int The integer data type stores positive or negative whole numbers eg. 5
float The float data type stores floating point numbers (numbers with decimal places).
double The double data type stores floating point numbers but with double precision.
bool The bool (short for Boolean) data type stores true or false values only eg. true
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is written in single quotes eg. ‘a’.
string The string data type stores letters, numbers and other characters in the form of words or sentences. A string value is written inside double quotes eg. “Hello World”.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      const string mySentence = "The quick brown fox jumps over the lazy dog.";
      Console.WriteLine(mySentence);

      int myNumber = 5;
      Console.WriteLine(myNumber);

      float myFloat = 15.279f;
      Console.WriteLine(myFloat);

      double myDouble = 150.24649;
      Console.WriteLine(myDouble);

      bool myBool = false;

      Console.ReadLine();
    }
  }
}

Next tutorial: Arithmetic and assignment operators

Data types in Java

A data type classifies various types of data eg. String, integer, float, boolean, the types of accepted values for that data type, operations that can be performed on the data type, the meaning of the data, and the way that data of that type can be stored.

The table below shows the most commonly used data types used in the Java programming language.

Type Description Example
int The integer (int) data type stores positive or negative whole number values. 20
float The float data type stores floating point numbers (numbers with decimal places) eg. 43.65 . Often, you will need to end a float value with an ‘f’ character eg. 43.65f 43.65f
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is always surrounded by single quotes eg. ‘a’. ‘a’
String The String data type stores letters, numbers and other characters in the form of words or sentences. A string value is always surrounded by double quotes eg. “Hello World”. “Hello world”
boolean The boolean data type stores true or false values only eg. true true

The table below shows some of the other data types used in the Java programming language.

Type Description Example
byte The byte data type stores integer numbers ranging from -128 to +127 118
short The short data type is used for integer numbers ranging from -32,768 to +32,767 -28,471
long The long data type is used for integer values exceeding 2.14 billion ‘a’
double The double data type is used for extremely long floating point numbers 1.7976931348623157 × 10^308

Sample code

The sample Java code below shows how some of the different data types can be stored in variables. Later on, we will look at how to actually work with the values of different data types (eg. math calculations with integers and floats, and decision making with booleans).

The code includes comments explaining each data type.

package myjavaproject;

public class DataTypes {
    public static void main (String[] args){
        String message = "Hello"; // variable of String data type
        char letter = 'a'; // variable of char data type
        int number = 20; // variabe of int (integer) data type
        float decimal = 43.65f; // variable of float (floating point) data type
        boolean result = true; // variable of Boolean data type
        
        // now let's output the values of the different variables
        System.out.println("Message is " + message);
        System.out.println("Letter is " + letter);
        System.out.println("Age is " + number);
        System.out.println("Score is " + decimal);
        System.out.println("The answer is " + result);
    }
}

Passing data between screens on iOS with Xamarin

In this tutorial you will learn how to create an iOS app that can pass data from one screen to another. This will be demonstrated in an example app that will ask the user for their age and will then convert their age to into animal years (of different types of animals). The user will select an animal by tapping a button and then the result will be displayed on the same screen. Tapping a button will take the user to another screen that grabs information from the first screen and displays a fact. The app will look like this…

ipd1

Step 1

Open Xamarin and click File > New Solution to get started. Give your app a name (the app is called AnimalAgeCalculatorIOS in this example). Select a target iOS version and click Next.

ipd3

Step 2

Confirm the project and solution name as well as the project location. Click Create.

 

ipd4

Step 3

Open the Main.storyboard file in the Resources folder and drag a Label on to the screen. The label in this example app is given the Text value Enter your age in years.

ipd5

Then drag a Text Field element on to the screen with the placeholder text Age. Give this Text Field the Name ageTextField.

ipd6

Step 4

Add another label with the text value Convert to… and then four buttons with the following names:

  • dogButton
  • catButton
  • goatButton
  • hamsterButton

Then add another label with the text value Your result and a button with the text value Find out more and the Name detailsButton – as shown below.

ipd7

Step 5

Now open the ViewController.cs file and add a TouchUpInside+= event for the dogButton element inside the ViewDidLoad() method. As you type in the line dogButton.TouchUpInside+= and press the spacebar on your keyboard you will be presented with some options. Double-click on DogButton_TouchUpInside to create a new method of the same name. If you don’t see the option immediately, start typing it in until it shows up in the list and then double-click it to add the new method for the touch event.

ipd8

Step 6

Now repeat the last step for each of the buttons (adding a new method for the TouchUpInside events for each of the four animal buttons).

ipd9

Step 7

Add the following variables to the ViewController : UIViewController class:

  • float age; (stores the user’s age)
  • float animalAge; (stores the age of the user in selected animal years)
  • string animal; (stores the name of the animal the user selected)

ipd10

Step 8

Now add the following highlighted code in the methods for the button touch events. This will get the user’s age from the text field and store it in the age variable as a float value. The animal’s age will also be calculated (based on which animal button the user pressed) and stored in the animalAge variable as a float value. The selected animal’s name will be stored in the animal variable as a string value. The label displaying the result will also be updated.

ipd11

Step 9

Now drag a Navigation Controller from the toolbox onto the screen in the Main.storyboard file.

ipd12

Step 10

Right-click and delete the Root View Controller screen on the left (may have to do this twice).

ipd13

Step 11

Hold down the Control (Ctrl) key while clicking and dragging from the Navigation Controller screen (on the left) to the main screen (on the right). You’ll see a blue line appear connecting the two screens together and a menu will also appear.

ipd14

When the menu appears make sure you select Root.ipd14b

 

 

 

Step 12

Now drag a View Controller from the toolbox on to the screen and place it on the right side of the main screen. This will be the second screen in the app.

ipd15

Step 13

Drag a Label on to the screen. Give it a name and you will notice that a warning icon appears. Clicking on the warning icon will reveal the warning message.

ipd16

The warning message tells us that there is no codebehind for this screen so we will need to create one. This will create a second ViewController.cs file for this screen. Give it the name ResultViewController and press the Enter key.

ipd17

In the solution panel you should now see the ResultViewController.cs file in the list. This file is where we add the code for the second screen.

ipd18

Step 14

Now Control (Ctrl) click the Find out more button on the main screen and while holding down the mouse key, drag on to the second screen and release. A small menu will appear. Select Show (this means when the button is pressed, it will show the second screen).

ipd19

Step 15

Now go back to ViewController.cs and add a new method. Start typing public override PrepareForSegue and then double-click the method shown in the list to create it.

ipd21
Click the image for a larger version.

Add the following highlighted code to the new PrepareForSegue method. This will create a variable for the second screen/view controller and the two variables that will have their values passed to the second screen are also specified here.

ipd22
Click the image for a larger version.

Step 16

Now go to the ResultViewController.cs file (for the second screen) and add the following highlighted code in the ResultViewController : UIViewController class. This will declare the animalAge and animal variables with initial values of 0f for animalAge and an empty string for animal.

ipd23
Click the image for a larger version.

Step 17

Now drag a Text View element on to the second screen with the Name resultLabel and the Text value of Your result. Resize it so it has plenty of room for text.

ipd24

Step 18

Go back to the ResultViewController.cs file and add the ViewDidLoad method.

ipd25
Click the image for a larger version.

Inside the ViewDidLoad method, add the following highlighted code. This will display the result to the user based on their animal age and selected animal.

ipd26
Click the image for a larger version.

Step 19

Now drag a Button element from the toolbox on to the second screen in the Main.storyboard file and give it the Name value backButton and the Text value Back.

ipd27

Step 20

Now Control (Ctrl) click and drag from the Back button on the second screen to the main screen and click Show when the menu appears after releasing the mouse button. This will make the app take the user back to the main screen when they press the Back button.

ipd28

Step 21

The final step is to allow the user to dismiss the keyboard on the main screen when the keyboard is no longer required. Go back to the ViewController.cs file and add an override TouchesBegan method as shown below.

ipd29
Click the image for a larger version.

Inside the new override method, add the following highlighted line of code which will end editing and dismiss the keyboard when the user no longer requires it.

ipd30
Click the image for a larger version.

That’s it! Now go and save all your files and test your app.

Passing data between screens on Android with Xamarin

In this tutorial you will learn how to create an Android app that can pass data from one screen to another. This will be demonstrated in an example app that will ask the user for their age and will then convert their age to into animal years (of different types of animals). The user will select an animal by tapping a button and then the result will be displayed on another screen. The app will look like this…

pda_app

Step 1

Open Xamarin Studio. Click File > New Solution. Select Android App (C#) as the template.

pda1

Step 2

Give your app a name, for example AnimalAgeCalculator. Click Next.

pda2

Step 3

Confirm the project and solution name as well as the project folder location and click Create.

pda3

Step 3

Navigate to the Resources > layout folder and click the cog icon (or right-click the folder). Then Click Add > New File. We will be adding the second screen to the app.

pda4

Step 4

Select Android > Layout, give the new screen a name (eg. Result.axml) and then click New.

pda5

Step 5

Open the Main.axml folder in the Resources > layout folder. Add a Text (Large) element and change the Text value to say ‘Enter your age in years’.

pda6

Step 6

Now add a Plain Text element and change its Id to @+id/ageEditText .

pda7

Step 7

Now add a Text (Medium) element which says ‘Convert to…’. Underneath this, add some Button elements such as those shown below. Change their Text values and Id’s. The buttons below have the following Id’s in order:

@+id/dogButton

@+id/catButton

@+id/goatButton

@+id/hamsterButton

pda8

Save the file.

Step 8

Now open the Results.axml file and add a Text (Large) element – replace its Text value with ‘Result’. Then add a Text (Medium) element, change its Id value to @+id/resultTextView and give it a default Text value (it doesn’t matter what you put here as the result text will change).

pda8b

Step 9

Add some spacing and then a Button element. Rename the Id of this button @+id/backButton and change the Text value to ‘Go back’. Save the file.

pda9

Step 10 

Now click on the project folder (not the solution folder) and click the cog icon (or right-click) > Add > New File.

pda10

Select Activity from the Android list, name it ResultActivity and then click New.

pda11

Step 11

Open the MainActivity.cs file and delete the two sections of highlighted code shown below inside the MainActivity class. This code will not be required in this app.

pda12
Click image to view larger version.

Step 12

In the MainActivity class, define the EditText and Button elements, and create two float variables (age and animalAge) and a string variable (animal) as highlighted on lines 11-18 below. In the OnCreate method, add the following highlighted code (shown in lines 27-31).

pda13
Click image to view larger version.

Step 13 

In the OnCreate method, after adding the EditText and Button elements to the code, start typing dogButton.Click+= to create a button click event and then press the Spacebar key. You will see a list of options – double-click the DogButton_Click option to create a new method of the same name.

pda14
Click image to view larger version.

The new method called DogButton_Click will be created as shown below.

pda14b
Click image to view larger version.

Step 14

Repeat the last step for each button click event. You should now have click events and matching methods for the dog, cat, goat, and hamster buttons. This is where we will start adding code to convert the human years to animal years and take the user to another screen.

pda14c

Add the following code to the methods show below.

pda14d

Step 15

Make sure you have the line of code using Android.Content; at the top section of the MainActivity.cs file’s code.

pda15

Step 16

In the HamsterButton_Click method, change the animal variable’s value to “Hamster” and then create a new intent which will send the values of the animalAge and animal variables to the ResultActivity screen.

pda16

Step 17

The last step will need to be repeated for each button click method as shown below. Just change the value for the animal variable in each method to the appropriate animal as shown below. Save the file.

pda17

Step 18

Open the ResultActivity.cs file and make sure your code is the same as shown in the highlighted areas in the image below. You will need to define the resultTextView and backButton elements as well as get the animalAge and animal values from the Intent created in the MainActivity.cs file. The resultTextView element will display the result of the age conversion (the selected animal name and result in animal years). Save the file.

pda18
Click image to view larger version.

Now just add a click event and method for the backButton element which will take the user back to the main screen when they click on the button which says ‘Go back’.

pda18b
Click image to view larger version.

Step 19

The last step before testing is to go back to the Main.axml file and change the Input Type for the ageEditText element to number. Save the file and test your app.

pda19

Click the Build icon to test your app using an Android simulator.
pda19b

Improving the app

One last thing we can do is prevent any errors from occurring or the app from crashing if the user does not enter a value to convert before tapping a button. We can check if the text field has been left empty and only run the conversion and open the result screen if a value exists in the text input field. Here is an example of this in the HamsterButton_Click method.

pda20

You could repeat this step for all of the button click methods. Now go and test your app again – it should no longer crash if the user does not enter a value in the text field!

Integers and floats in C#

In the previous tutorial we looked at how to create variables and work with the string data type in C#. In this tutorial we will look at how to work with the integer and float data types in C# and also how to convert strings to integers or floats using the int.Parse() and float.Parse() methods. You will also learn how to manipulate numbers using arithmetic operators.

Watch the video below or scroll down to see the sample code.

Sample C# code

using System;

namespace MyCSharpApp
{
  class MainClass

  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("Enter two numbers...");
      float num1 = float.Parse(Console.ReadLine ());
      float num2 = float.Parse(Console.ReadLine ());
      Console.WriteLine (num1 + num2);
    }
  }
}

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used number variables (although they can be used for other things too).

Operator Name / description
+ Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together.
Subtraction – this operator is used to subtract one number from another.
* Multiplication – this operator is used to multiply two numbers together.
/ Division – this operator is used to divide one number by another.
% Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

<variable name> <assignment operator> <value>;

For example: x = 5;

The table below shows the different assignment operators available in C#.

Operator Description
= The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign.
+= , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5.
++ and — These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Next tutorial: Conditional programming in C#

Variables and strings in C#

This tutorial explains how to create variables and use strings in the C# programming language. Variables are used to store data that can be used throughout a program.

Variables can store data of different types. One data type is the string. Strings can contain characters such as letters, numbers or symbols. Strings can be a single character, a bunch of mixed characters, words, or sentences.

Other data types include integers (whole numbers eg. 4), floats, (numbers with decimal place eg. 3.56), and Booleans (true or false values). There are other data types that exist but these are the main ones we will start with. In this tutorial we will focus on strings and how they can be used in variables and statements.

When you create a variable you must declare its data type (eg. string), give it a name (eg. age, score, name), and then you can assign it a value. For example,  look at the following statement:

string firstName = "Joe";

The statement above would create a new variable called firstName of the string data type containing the value Joe. Strings are always contained inside single or double quotes.

Watch the video below and then scroll down to see the sample code.

Sample C# code

The code below contains comments to explain each statement.

using System;

namespace MyCSharpApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("What is your name?"); // this displays a message in console
      string message = "Hello there, "; // creates a string variable that contains a message
      string name = Console.ReadLine (); // creates a string that stores the user's name from input
      Console.WriteLine (message + name); // writes the message and name to the console
    }
  }
}

Next tutorial: Integers and floats in C#

More data validation in PHP

This tutorial shows some more data validation methods following on from the form data validation tutorial. In this tutorial, you will be shown how to implement the following data validation methods:

  • Limit number of characters that can be entered in a text box
  • Ask the user to enter a password twice and check that both passwords are identical
  • Validate an email address
  • Check that all parts of a form are completed

Watch the video below and then scroll down to see the sample code.

Sample PHP code

There are two files being used in this example which will validate a username, email address and password. The files are form.php and action_handler.php.

The form.php code:

<html>
<head>
  <title>Form that validates data</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <h3>Enter a username, email and password to sign up.</h3>
    <p>Username: <input type="text" name="username"></p>
    <p>Email address: <input type="text" name="email"></p>
    <p>Password: <input type="password" name="password"></p>
    <p>Password again: <input type="password" name="password2"></p>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>

The action_handler.php code:

<?php
  if(!empty($_POST['username'])){
    $username = $_POST['username'];
    if(strlen($username) > 30){
      $username = NULL; echo "Username cannot be longer than 30 characters.<br/>";
    }
  }
  else{
    $username = NULL; echo "You must enter a username.<br/>";
  }


  if(!empty($_POST['email'])){
    $email = $_POST['email'];
    if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
      $email = NULL; echo "Email address is not in the correct format.<br/>";
    }
  }
  else{
    $email = NULL; echo "You must enter an email address.<br/>";
  }

  if(!empty($_POST['password']) || !empty($_POST['password2'])){
    $password = $_POST['password'];
    $password2 = $_POST['password2'];
    if($password != $password2){
      $password = NULL; $password2 = NULL; echo "Both passwords must be the same.<br/>";
    }

  }
  else{
    $password = NULL; $password2 = NULL; echo "You must enter your password twice.";
  }

  if(strlen($password) <10 && strlen($password2) <10){
    $password=NULL;$password2=NULL;echo "Password must be 10 characters or longer<br/>";
  }

  if(($username != NULL) && ($email != NULL) && ($password != NULL) && ($password2 != NULL)){
    $passwordLength = strlen($password);
    $hiddenPassword= "$password[0]"."$password[1]".str_repeat("*",($passwordLength-2));
    echo "<h3>Thank you for registering. Here are your details...</h3>";
    echo "Username: $username <br/>Email: $email<br/>Password: $hiddenPassword";
  }
?>

Ignore or strip HTML tags from strings in PHP

This tutorial explains how to use the htmlentities and strip_tags functions in PHP to ignore or strip HTML tags in strings. You may want to do this if you are allowing users to enter data into a form element such as a text box and don’t want the user to be able to mess up the display of your website by adding HTML tags to data.

The first function called htmlentities, is used to ignore HTML tags in strings. The second function called strip_tags is used to completely remove the HTML tags from a string. Watch the video below to see how you can protect your website or web app using these functions with forms and then scroll down to see the sample code.

Sample PHP code:

<!DOCTYPE html>
<html>
<head>
  <title>HTML entities and strip tags</title>
</head>

<body>
  <?php
    if(isset($_GET['string1'])){
      echo "Using htmlentities function: " , htmlentities($_GET['string2']), "<br/>";
      // htmlentities displays HTML tags as they are
    }

    if(isset($_GET['string2'])){
      echo "Using strip_tags function: " , strip_tags($_GET['string2']), "<br/>";
      // strip_tags will strip the HTML tags
    }
  ?>
  <h3>Enter your name below:</h3>
  <form action="" method="GET">
    First string (using htmlentities): <input type="text" name="string1"><br/>
    Second string (using strip_tags): <input type="text" name="string2"><br/>
    <input type="submit">
  </form>
</body>
</html>

Select lists and PHP

Select lists, which are created in HTML code, can be useful when a user needs to select one or more items from a list of different items. This tutorial explains how to add a select list to a form in a web page using some simple HTML code and then how to use PHP code to use the submitted data from the form.

You can watch the video below or scroll down to see the sample code.

Sample PHP code

There are two files used in this tutorial: form.php which creates a select list and collects the user input, and action_handler.php which uses and processes the submitted data.

Here is the code for the form.php file:

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Which countries would you like to visit?</p>
    <select multiple name="countries[]" style="width:100px;">
      <option value="France">France</option>
      <option value="Brazil">Brazil</option>
      <option value="India">India</option>
      <option value="Japan">Japan</option>
    </select>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Here is the code for the action_handler.php file:

<?php
  if(isset($_POST['countries'])){
    $countries = $_POST['countries'];
    echo "You selected the following countries:<br/>";
    foreach($countries as $key => $value){
      echo "$value<br/>";
    }
  }
  else{
    echo "You must select at least one country.";
  }
?>

Form elements (text, text area and password) and PHP

This tutorial explains how to create forms which include a range of form elements include text (textbox), textarea, and password.

  • text – this element is used to get a short amount of text input from the user (a single line)
  • textarea – this element is used to get longer amounts of text input from the user (more than one line)
  • password – this element is used to get password input from a user and will mask any text entered by the user with dots (or asterisks) so that other people cannot see the password

The tutorial will also show how to handle submitted form data using PHP code. Other tutorials have already shown how to use radio buttons and check boxes.

You can watch the video below or scroll down to see the sample code.

Sample PHP code

Step 1: Create a PHP file which will contain the form (eg. form.php) and then copy the following code into it.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Username: <input type="text" name="username"> 
      Password: <input type="password" name="password"></p>
    <p><textarea name="comment"></textarea>
      <input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate file called action_handler.php which will handle the submitted form data. Copy the following code.

<?php
  $username = $_POST['username'];
  $password = $_POST['password'];
  $comment = $_POST['comment'];

  if(empty($username) || empty($password) || empty($comment)){
    echo "You must complete all fields.";
  }
  else{
    echo "Hello there, $username.<br/>";
    echo "Thank you for your comment:<br><i>$comment</i>";
  }
?>

Important note

Please note that this tutorial and sample code only explains how to use different form elements including the password element. It does not explain security or encryption when submitting sensitive information such as passwords. It is important to be aware of security and encryption when working passwords and other sensitive data before you publish a website that allows the user to submit this kind of data.

I will discuss some security methods in future tutorials but do not take any responsibility for the security of your own website.

Check boxes in forms (PHP)

This tutorial explains how to create a form which contains check boxes and how to handle the form data using PHP. Check boxes are used when you want the user to be able to select one or several options (unlike radio buttons which only allow the user to select one option at a time). Watch the video below and then scroll down to see the sample code.

Sample PHP code:

Step 1: Create a PHP file which will contain the form (eg. form.php) and copy the following code into it. This example will ask the user to select a country or multiple countries they would like to visit.

<html>
<head>
  <title>My form</title>
</head>

<body>
  <form action="action_handler.php" method="POST">
    <p>Which countries would you like to visit?</p>
    <input type="checkbox" value="France" name="countries[]"> France<br/>
    <input type="checkbox" value="India" name="countries[]"> India<br/>
    <input type="checkbox" value="Brazil" name="countries[]"> Brazil<br/>
    <input type="checkbox" value="Japan" name="countries[]"> Japan<br/>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate PHP file which will handle the submitted form data and call it action_handler.php – then copy the following code into the file.

<?php
  if(isset($_POST['countries'])){
    $countries = $_POST['countries'];
    echo "You selected the following countries:<br/>";
    foreach($countries as $key => $value){
      echo "$value<br/>";
    }
  }
  else{
    echo "You must select at least one country.";
  }
?>

Checking set values (radio buttons) in PHP

This tutorial explains how to use radio buttons in forms and check set values in PHP to ensure that the user has entered data in the form. Watch the video below and then scroll down to see the sample code.

Sample PHP code:

Step 1: Create a PHP file (eg. form.php) which contains a form with radio buttons by copying the following code. This example will quiz the user on the capital city of Australia.

<html>
<head>
  <title>Form that checks set values</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <p>What is the capital city of Australia?</p>
    <input type="radio" name="capital" value="Sydney"> Sydney<br>
    <input type="radio" name="capital" value="Canberra"> Canberra<br>
    <input type="radio" name="capital" value="Melbourne"> Melbourne
    <p><input type="submit"></p>
  </form>
</body>
</html>

Step 2: Create a separate PHP file called action_handler.php and copy the following code into it. This file will handle the form data.

<?php
  if(isset($_POST['capital'])){
    $capital = $_POST['capital'];
  }
  else{
    $capital = NULL;
  }

  if($capital != NULL){
    if($capital != "Canberra"){
      echo "$capital is incorrect";
    }
    else{
      echo "$capital is correct";
    }
  }
  else{
    echo "You must select an answer";
  }
?>

Form data validation with PHP

This tutorial explains how to validate data that has been submitted by a user in a form. We will look at the following types of data validation:

  • Check that a text field has not been left empty
  • Check only numbers have been entered
  • Check that an email address is in the correct format

We will use the empty, is_numeric, and filter_var functions for data validation in this example. Watch the video below and then scroll down to see the sample code.

Sample PHP code

Step 1: Create a PHP file (eg. form.php) and copy the following code into that file. This file will contain the form.

<html>
<head>
  <title>Form that validates data</title>
</head>
<body>
  <form action="action_handler.php" method="POST">
    <h3>Enter a postcode and email address.</h3>
    <p>Post code: <input type="text" name="postcode"></p>
    <p>Email address: <input type="text" name="email"></p>
    <p><input type="submit" value="Submit"></p>
  </form>
</body>

Step 2: Create a PHP file called action_handler.php and copy the following code into it. This file will handle the submitted form data.

<?php
  if(!empty($_POST['postcode'])){
    $postcode = $_POST['postcode'];
    if(!is_numeric($postcode)){
      $postcode = NULL; echo "Postcode must be numeric.<br/>";
    }
  }
  else{
    $postcode = NULL; echo "You must enter a postcode.<br/>";
  }

  if(!empty($_POST['email'])){
    $email = $_POST['email'];
    if(!filter_var($email,FILTER_VALIDATE_EMAIL)){
      $email = NULL; echo "Email address is not in the correct format.";
    }
  }
  else{
    $email = NULL; echo "You must enter an email address.<br/>";
  }

  if(($postcode != NULL) && ($email != NULL)){
    echo "Email: $email<br/>Postcode: $postcode";
  }
?>