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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?