Activity 4. Passing Variables on the URL


Problem 1

Create a simple form with two input fields for the user to enter two numbers performs arithmetic operations (addition, subtraction, multiplication, division) on them. The form submits the data to a PHP script using the GET method.

Solution

HTML Forms
    <form class="form-horizontal" method="get" action="calculatorHandle.php">
        <legend>Calculator</legend>
        <label class="control-label" for="num1">Number 1</label>
        <input type="number" class="form-control" id="inputDefault" name="num1">
        <label class="control-label" for="num2">Number 2</label>
        <input type="number" class="form-control" id="inputDefault" name="num2">
        <select class="form-control" id="select" name="operation">
            <option value="add">Add</option>
            <option value="sub">Subtract</option>
            <option value="mul">Multiply</option>
            <option value="div">Divide</option>
        </select>
        <button type="submit" class="btn btn-primary" id="calcSubmit">Submit</button>
    </form>

PHP Code
if(isset($_GET['num1']) && isset($_GET['num2']) && isset($_GET['operation'])){
    $num1 = $_GET['num1'];
    $num2 = $_GET['num2'];
    $operation = $_GET['operation'];
    // calculate according to operation passed
    if($operation == "add"){
        echo $num1 + $num2;
    } else if($operation == "sub"){
        echo $num1 - $num2;
    } else if($operation == "mul"){
        echo $num1 * $num2;
    } else if($operation == "div"){
        echo $num1 / $num2;
    }
} else {
    echo "missing variable name parameters";
}

Demo

Calculator

Problem 2

Create a simple form that allows to input a message and counts the number of words in it. The form submits the data to a PHP script using the GET method.

Solution

HTML Forms
<form class="form-horizontal" method="get" action="messageHandle.php">
    <label class="control-label" for="mes">Message</label>
    <textarea class="form-control" rows="3" id="textArea" name="mes"></textarea>
    <button type="submit" class="btn btn-primary" id="calcSubmit">Submit</button>
</form>

PHP Code
if(isset($_GET['mes'])){
    $message = $_GET['mes'];
    $count = str_word_count($message);
    echo "Your message has " . $count . " word/s.";
} 
else {
    echo "missing variable name parameters";
}

Demo

Message