dowy77780 2013-03-01 19:16
浏览 14
已采纳

这是测试已发布变量存在的正确方法吗?

If a query maybe be optionally run as a get() or a post(), so that $id = $_POST['id'] maybe get a null value, are any of these a good practice way to test for the possibly posted variable's existence.

if (!empty($_POST['id'])){ $id = $_POST['id'];}else{$id = FALSE;}

if (isset($_POST['id'])){ $id = $_POST['id'];}else{$id = FALSE;}

$id = isset($_POST['id']) ? $_POST['id'] : FALSE;

or is there some other preferred method? They all do a $_REQUEST() twice which inclines me to think there could be a better way.

Thanks!

  • 写回答

5条回答 默认 最新

  • dongxiezhuo8852 2013-03-01 19:32
    关注

    I would go with:

    $id = isset($_POST['id']) && strlen($_POST['id']) > 0 ? (int)$_POST['id'] : FALSE;
    

    First it checkes if the var is set, and then check if the length is longer than 0.

    In my opinion it is the best readable, as you dont need 5 lines of code if you indent it correctly, what makes it harder to read and makes your file longer:

     if (isset($_POST['id'])){ 
       $id = $_POST['id'];
     }else{
       $id = FALSE;
     }
    

    And if you use $_POST for a simple thing as an ID, just cast it to an int with (int)$_POST['id']. That way you are sure to have a number.

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

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面