将$ _POST中给出的字符串与php进行比较

时间:2008-10-08 20:22:04

标签: php post compare

我有一个发送大小东西的表单,我需要查看字符串是什么,以便我可以相应地设置价格。当我尝试这样做时,它说它们不相等,我没有价格。这是我正在使用的代码:

if ($_POST['sizes'] == "Small ($30)"){$total = "30";}
if ($_POST['sizes'] == "Medium ($40)"){$total = "40";}
if ($_POST['sizes'] == "Large ($50)"){$total = "50";}
else {$total = $_POST['price'];}

我在这里做错了什么?我可以回复$ _POST ['sizes'],它只给我一个这样的东西。

9 个答案:

答案 0 :(得分:8)

Paul Dixon said是正确的。可能我还建议使用switch语句而不是那些笨重的if语句(实际上有一个逻辑错误,我可能会添加 - $total总是等于$_POST['price']而不是'Large ($50)'

<?php

switch ( $_POST['sizes'] )
{
    case 'Small ($30)' :
        $total = 30;
        break;
    case 'Medium ($40)' :
        $total = 40;
        break;
    case 'Large ($50)' :
        $total = 50;
        break;
    default:
        $total = $_POST['price'];
        break;
}

?>

答案 1 :(得分:3)

这是切换/案例陈述的一个很好的候选者,你的'else'是默认的。

另外,如果你的$ _POST ['sizes']不大,那么不使用中大的elseif,那么你的$ total总是$ _POST ['price']。这也可能会让你失望。

答案 2 :(得分:2)

所以你知道,你的if / else的问题在于最后的其他事情总是在发生。交换机仍然更好,但这是您的代码应该是:

if ($_POST['sizes'] == "Small ($30)") { $total = "30";
} else if ($_POST['sizes'] == "Medium ($40)") { $total = "40";
} else if ($_POST['sizes'] == "Large ($50)") { $total = "50";
} else { $total = $_POST['price']; }

对于每个说问题是30美元,40美元等的人来说,事实并非如此。变量不能以数字开头,因此PHP将忽略40美元等等。

答案 3 :(得分:1)

尝试使用单引号

if ($_POST['sizes'] == 'Small ($30)'){$total = "30";}
elseif ($_POST['sizes'] == 'Medium ($40)'){$total = "40";}
elseif ($_POST['sizes'] == 'Large ($50)'){$total = "50";}
else {$total = $_POST['price'];}

双引号字符串使用变量插值,因此$符号变得重要!有关如何在PHP中声明字符串文字的差异,请参阅this manual page

(编辑纠正逻辑错误 - 正如其他人所说,这里的开关会更加清晰)

答案 4 :(得分:1)

或者,甚至比笨重的开关更好,你可以利用这个简单的逻辑并练习'数据驱动编程':

$vals = array(
    'Small ($30)' => 30,
    'Medium ($40)' => 40,
    'Large ($50)' => 50
);

$total = array_key_exists($_POST['sizes'], $vals)
    ? $vals[$_POST['sizes']]
    : $_POST['price'];

答案 5 :(得分:1)

除了这个错误的实际原因之外,如果您使用了除标签之外的其他值,则可以避免这种情况,例如:

<select name="sizes">
    <option value="small">Small ($30)</option>
    <option value="meduim">Medium ($40)</option>
    <option value="large">Large ($50)</option>
</select>

答案 6 :(得分:0)

$ total是一个字符串吗?

$ total =“30”;是字符串的语法。 $ total = 30;对于数字来说是正确的。

答案 7 :(得分:0)

这里没有安全漏洞吗?如果有人只是提交他们想要的默认条款价格怎么办?

答案 8 :(得分:0)

// remove any non-decimal characters from the front, then extract your value,
// then remove any trailing characters and cast to an integer
$total = (integer)preg_replace("/^\D*(\d+)\D.*/", "$1", $_POST['sizes']);
if (!$total) $total = $_POST['price'];