尽管if语句,代码仍在运行?

时间:2014-03-29 21:10:07

标签: php mysql forms if-statement input

                echo '<form method="post">
                                <input type="text" name="selector3">
                                <input type="submit" name="submit3" value="submit3">
                                  </form>';

                                  if (!empty($_POST['selector3'])) {

                        $eventsquery = mysql_query("
                            SELECT studentid, statusid, timestamp, elapsed
                            FROM events
                            WHERE studentid = '$name'
                            AND statusid = '$_POST['selector3']'
                            ORDER BY timestamp DESC
                            LIMIT 1
                            ")
                            or die("Error querying database ".mysql_error()); }

即使未设置选择器3,它也会在if语句中运行代码!

2 个答案:

答案 0 :(得分:0)

您可以尝试使用isset而不是空。

if (isset($_POST["selector3"])) {
    ...
}

答案 1 :(得分:0)

代码在这里按预期工作.i.e。当$ _POST ['selector3']为空时,查询不会执行。

但是,查询中存在语法错误。它被$ _POST ['selector3']搞糊涂了。

<?php
var_dump($_POST);
$name = '';
echo '<form method="post">
                                <input type="text" name="selector3">
                                <input type="submit" name="submit3" value="submit3">
                                  </form>';

                                  if (!empty($_POST['selector3'])) {

                        $eventsquery = mysql_query("
                            SELECT studentid, statusid, timestamp, elapsed
                            FROM events
                            WHERE studentid = '$name'
                            AND statusid = '{$_POST['selector3']}'
                            ORDER BY timestamp DESC
                            LIMIT 1
                            ")
                            or die("Error querying database ".mysql_error()); }
var_dump($_POST);
?>