dongniechi7825 2017-08-19 18:37
浏览 101
已采纳

使用eval() - 函数检查变量

I have a list of variables (var1, var2, ...). Now I'd like to check these variables using several conditions and print out an error message if the condition is true.

As there are many "checks" that should be done I saved the "conditions" in a MySQL-DB (varchar):

condition               errormsg
--------------------------------------------------------
$var1!=1 && $var1!=2    var1 should be 1 or 2
$var1==''               var1 is missing
$var3<0 & $var3>10      var3 should be between 0 and 10

Now I'd like to check these variables using the eval-Function:

$res=mysqli_query($con, "SELECT * FROM conditions");

while($row=mysqli_fetch_object($res)){
 if(eval($row->condition))
  echo $row->errormsg;
}

Can this work or is there a better solution without eval()? Thank you for your help!

  • 写回答

3条回答 默认 最新

  • dongyanghan0556 2017-08-19 19:12
    关注

    Many people suggest to get alternate of this . But if you really need this you can do this way. I don't have your data so I have made this with my own way

     <?php
        $condition = "1!=1";
        //$condition = "1==1";
       $error = "test";
       eval("\$con = $condition ;");
       if($con){
       echo $error;
       }else {
      echo "not found";
      }
    ?>
    

    Uncomment second line to get another change. Just keep in mind that statement should be complete in eval function.

    Live demo : https://eval.in/847626

    Pay special attention not to pass any user provided data into it without properly validating it beforehand.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码