Question

I have a FORM:

 <form name="myform" action="" method="post">
 Unilateral lower limb pain:
 <select name="pain">
     <option value="1">yes</option>
     <option value="0">no</option>
 </select>
 <input type="submit" name="submit" value="submit" />
 </form>

I am trying to add values to the var $_POST[pain] but I keep getting 0 as the result

 <?php
 if (isset($_POST['submit'])){

 $thescore=0;

 $_POST['pain']=intval($painScore);

 if($painScore==1){
  $thescore=$thescore+3; 
 }

 echo 'score is: '.$thescore;

 }
 ?>

This outputs "score is: 0" if "yes" is selected as an option when it should output 1

I have also tried:

  int()$_POST[pain]=$painscore;

with the same result, output is 0.

How do I add numbers (floating points and integers) together when retrieved from a FORM?

Was it helpful?

Solution 2

This block of code does not make any sense

<?php
 if (isset($_POST['submit'])){

 $thescore=0;

 $_POST[pain]=intval($painScore);

 if($painScore==1){
  $thescore=$thescore+3; 
 }

 echo 'score is: '.$thescore;

 }
 ?>

I suppose you need to do as

<?php
 if (isset($_POST['submit'])){

 $thescore=0;
 $painScore = (int)$_POST['pain'] ;

 if($painScore==1){
  $thescore=$thescore+3; 
 }

 echo 'score is: '.$thescore;

 }
 ?>

OTHER TIPS

<?php

if (!empty($_POST)) {
    $score = filter_input(INPUT_POST, "pain", FILTER_VALIDATE_INT, array(
        "options" => array(
            "default"   => 0,
            "min_range" => 0,
            "max_range" => 1,
        )
    ));
    if ($score === 1) {
        $score += 3;
    }
    echo "Score is: {$score}";
}

?>

Your syntax is wrong

$_POST[pain]=intval($painScore);

must be

$painScore=intval($_POST[pain]);

$painScore=intval($_POST['pain']);

$_POST is a superglobal containing data passed to the script in the HTTP body (e.g. from a <form> with method="post") - you can't really "write" to $_POST at runtime in the way you're trying to.

A neater way to write what you're attempting, assuming I understand it correctly (and one that might actually work) would be:

// variable definition
$iPainScore = 0;

// evaluation
if(!empty($_POST)) {

  // increment $iPainScore by the value of $_POST['pain']
  // unless $_POST['pain'] == 1, in which case increment $iPainScore by 3
  $iPainScore += $_POST['pain'] == 1 ? 3 : (int) $_POST['pain'];
}

// output
echo "The score is {$iPainScore}";

EDIT

... actually, since $_POST['pain'] can only ever be 0 or 1 you don't really need to add it to your pain score at all; you're using $_POST['pain'] as a boolean it seems, actually incrementing your pain score by 3 if $_POST['pain'] is 'true' ( for (int) 1 == (bool) true ).

You could therefore reduce the entire thing (assuming you're starting here with a pain score of 0 rather than incrementing an existing pain score) to:

$iPainScore = !empty($_POST['pain']) ? 3 : 0;
echo "The score is{$iPainScore}"'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top