mdot
mdot

Reputation: 5

how to use if conditions for post request data in php

    <?php
    $answer1;
    $answer2;
    $answer4;
    $answer5;
    $answer6;
    $answer7;
    $answer8;
    $answer9;
    $answer10; 
    $_POST["counter"] === 0;


    if($answer1 == 'question-1-answers-a'
    $_POST["counter"]++;
    else{
        $_POST["counter"] == $_POST["counter"]
        }

The purpose of this segment of my code is to keep track the number of correct answers the user is getting on the quiz. The primary issue is that I keep getting an error saying unexpected $_POST["counter"] on this line:

$_POST["counter"]++;

And based on the research I have done, I doubt that the error is only in this line. So if anyone has any advice at all, please share.

Upvotes: 0

Views: 73

Answers (1)

Naltroc
Naltroc

Reputation: 1007

The comments above are all valid. For an explicit answer to the question title, if conditions work as follows:

if ($case) {
  //do this
} else {
  //do this
}

When $case evaluates to some kind of true, then the first case happens. Otherwise the second will. Note the use of braces.

The = operator is only for assigning variables. The == and === operators are only for comparing variables and will evaulate to either true or false. Your statement of $_POST["counter"] === 0 is essentially the same as writing either true or false, depending on the contents of $_POST["counter"].

A properly formatted version of your code is as follows:

<?php
    $answer1;
    $answer2;
    $answer4;
    $answer5;
    $answer6;
    $answer7;
    $answer8;
    $answer9;
    $answer10; 
    $_POST["counter"] = 0;


    if ($answer1 == 'question-1-answers-a') {
        $_POST['counter'] = $_POST['counter'] + 1 ;
    } else {
        $_POST['counter'] = $_POST['counter']
    }
?>

You also do not need to declare variables as you did with $answerX. Just delcare it on assignment.

Upvotes: 1

Related Questions