-2

All I want to do is to get saved operator from database and used it in if else condition. Here is my code. It always return true. Not able to figure out what I am doing wrong

$sql_c = "select cc.operator, cc.dpt_id, dp.dpt_value as value from criteria_condition cc
                join decision_point_type dp on cc.dpt_id = dp.dpt_id where criteria_id = $nodecriteria";
        $res_c = mysql_query($sql_c);
        while($row = mysql_fetch_array($res_c)){
             $operand = $row['operator'];
             $dpt_value = $row['value'];
        }
        echo "'$userinput'".$operand ."'$dpt_value'".'<br>';
        if("'$userinput'".$operand."'$dpt_value'"){
            echo 'true';
        }else{
            echo 'false';
        }

Echo displays "hello"==="hello" but in if condition it is not work properly

astonish
  • 223
  • 2
  • 8
  • Any non-empty string evaluates to `true`. You need something like `eval` if you want to evaluate strings as code. – jeroen Feb 24 '15 at 12:31
  • refer to following link http://stackoverflow.com/questions/24102923/setting-a-variable-to-an-operator-then-executing-it – Bhagawati Kumar Feb 24 '15 at 12:51

1 Answers1

0

You aren't able to use a string as a operator like that.

Take a look at this:

You can use eval(), however the safest route would be something like:

$left = (int)$a;
$right = (int)$b;
$result = 0;
switch($char){

  case "*":
    $result = $left * $right;
    break;

 case "+";
   $result = $left + $right;
   break;
// etc

}

Resource:

PHP use string as operator

Community
  • 1
  • 1
Jesper
  • 3,816
  • 2
  • 16
  • 24