奇怪的布尔反应

时间:2011-03-15 14:03:41

标签: php string return

$alerter2="false";
for ( $counter = 0; $counter <= count($filter); $counter++) {
    $questionsubmitted=strtolower($_POST[question]);
    $currentcheck =$filter[$counter];
    $foundvalue=stripos((string)$questionsubmitted,(string)$currentcheck);
    echo $foundvalue;
    if ($foundvalue==0) {
        $alerter2="true";
    } else { }
}

if (!($alerter2=="true")) {
    $sql="INSERT INTO Persons (Name, Email, Question)
        VALUES
        ('$_POST[name]','$_POST[email]','$_POST[question]')";
} else {
    echo "Please only post appropriate questions";
}

出于某种原因,每当我运行它时,stripos每次迭代都会返回0。它应该是一个过滤器,使用echo我发现每次出现时stripos为0。但是,当我在if中使用0时,即使那些没有单词的人也会返回true。

我应该在哪里使用mysql_real_escape_string?查询后?注意,我正在制作一段代码,我希望将用户输入保存到数据库中。

3 个答案:

答案 0 :(得分:2)

stripos如果找不到值则返回false,如果是第一个字符则返回0。问题是,php自动将布尔值转换为0整数或0整数转换为false。所以我觉得演员阵容正在这里发生,因此条件不符合你的要求。

您可以使用===检查变量的类型:

if ($foundvalue === 0) {
    $alerter2="true";
}

stripos的链接文档中有关于此问题的更多详细信息。

您还应该删除空的else子句以获得更干净的代码,并在将值放入数据库之前使用mysql_real_escape_string来清理这些值。

答案 1 :(得分:0)

您需要更改

if ($foundvalue==0)

if ($foundvalue===0) // three equals signs

或类似的东西,取决于你的逻辑(我不太明白发生了什么)。

但正如大家所说,此代码对SQL注入攻击开放(以及其他问题)。

答案 2 :(得分:0)

此外,

$questionsubmitted=strtolower($_POST[question]);

应该是:

$questionsubmitted=strtolower($_POST['question']);