简体   繁体   English

带数字的PHP ElseIf语句

[英]PHP ElseIf Statement with Numbers

The user can only enter a number between 1 and 5 - if they enter 0, leave the field blank or enter a number greater than 5 it will be default reset to 5. 1,2,3,4 are accepted otherwise. 用户只能输入1到5之间的数字-如果输入0,则将该字段留空或输入大于5的数字,则默认将其重置为5。否则将接受1,2,3,4。

$max=mysql_real_escape_string($_POST["max"]);

if ($max=="0" || $max==""){
    $max_r="5";
} elseif ($max > "5"){
    $max_r="5";
} else {
    $max_r=$max;
}

However it always spits out 5. 但是它总是吐出5。

Well, you're comparing strings and not integers. 好吧,您正在比较字符串而不是整数。 Try $max = (int) $_POST['max'] and don't wrap the values in quotes. 尝试$max = (int) $_POST['max'] ,不要将值用引号引起来。 Then, you can always escape $max before writing it to the DB. 然后,您始终可以在将$max写入数据库之前对其进行转义。

$max = (int) $_POST['max'];

if ( ! $max || $max > 5){
  $max_r = 5;
} else {
  $max_r = $max;
}

Or, you could go one-liner FTW: 或者,您可以采用单线FTW:

$max_r = ( ! $max || $max > 5) ? 5 : $max;
$max = intval($_POST['max']);
if($max < 0 || $max > 5){
   $max = 5;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM