从选择选项HTML PHP中获取值

问题描述 投票:-2回答:1

我想从带有HTML和PHP的select选项中获取值,但是我得到这个“注意:未定义的索引:行中文件路径中的selectOptionName ...”

我的目标是从选项中获取值,因此以后可以将其放入数据库中。由于我什至无法回显该值,因此此刻我陷入了困境。在此示例中,我希望在按下按钮时获得“ 1”或“ 2”或“ 3”或“ 4”,具体取决于下拉菜单中的选择。

<html>
    <form action="file.php", method="post", name="formName">
        <select name="type", id="1000", form="formName">
            <option value="1">Type_1</option>
            <option value="2">Type_2</option>
            <option value="3">Type_3</option>
            <option value="4">Type_4</option>
        </select>
        <input type="submit", name="submit">
    </form>
</html>
<?php
$values = $_POST['type'];
if(isset($_POST['submit'])){
echo $values;
}
?>
php html select option
1个回答
0
投票

除了一些语法错误之外,您还处于正确的轨道。只需确保检查HTTP请求VERB(来自$_SERVER['REQUEST_METHOD']),而不是假设它始终为POST。当用户首次访问该页面时,该页面可能是GET,因此在这种情况下,您不必理会那段代码。

作为旁注,您可能应该通过在其中一个选项上设置selected属性来为选择框设置默认选择值。

这里是一个例子:

<html>
    <form action="file.php" method="post" name="formName">
        <select name="type" id="1000" form="formName">
            <option value="1" selected>Type_1</option>
            <option value="2">Type_2</option>
            <option value="3">Type_3</option>
            <option value="4">Type_4</option>
        </select>
        <input type="submit" name="submit">
    </form>
</html>
<?php
// First make sure you check the HTTP request VERB whether its POST or GET
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // We only do this if it's POST
    if (!empty($_POST['type'])) { // the value was sent by the client
        echo "Value sent: $type"; // you see it here
    } else { // user didn't send the value
        echo "You did not send a value!";
    }
}
?>

最后,如果要将其存储在数据库中,请考虑仅允许通过whitelisted值。这样,用户就无法毫不费力地发送您不期望的内容。

在上面的代码块中,您可能会这样做。

<?php
// A preset whitelist of values we allow
$whitelist = [1, 2, 3, 4]; // only these are allowed
// First make sure you check the HTTP request VERB whether its POST or GET
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // We only do this if it's POST
    if (!empty($_POST['type'])) { // the value was sent by the client
        if (in_array($_POST['type'], $whitelist)) { // it's in the whitelist
            echo "Value sent: $type"; // you see it here
        } else { // it's not in the whitelist
            echo "You selected an option that's not allowed!";
        }
    } else { // user didn't send the value
        echo "You did not send a value!";
    }
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.