2015-02-24 47 views
-2

我所要做的就是從數據庫中獲取已保存的運算符,並在if條件中使用它。這是我的代碼。它總是迴歸真實。沒能找出什麼我做錯了在PHP變量中保存運算符符號

$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'; 
     } 

回聲顯示「Hello」 ===「你好」,但如果條件是無法正常工作

+0

任何非空字符串的計算結果爲「true」。如果您想將字符串評估爲代碼,則需要使用'eval'。 – jeroen 2015-02-24 12:31:03

+0

參考以下鏈接 http://stackoverflow.com/questions/24102923/setting-a-variable-to-an-operator-then-executing-it – 2015-02-24 12:51:57

回答

0

您不能使用字符串作爲這樣的運營商。

在此請看:

您可以使用eval(),但最安全的路線是這樣的:

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

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

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

} 

資源:

PHP use string as operator