首页 > 解决方案 > PHP 从选择 html 页面中获取值

问题描述

我有以下html代码

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" class="contact">
            <label id="name">
                <h4>name*</h4>
                <input type="text" name="name" placeholder="full name" autofocus/>
            </label>
            <label id="city">
                <h4>city</h4>
            <select name="city">
            <option value="Afghanistan">Afghanistan</option>
            <option value="Albania">Albania</option>
                        </select>
            </label>

PHP 代码

if($_POST["name"] == null)
{
    echo "<p class='wrong'><strong>wrong: </strong> name is empty</p>";
}
if($_POST["city"] == null)
{
    echo "<p class='wrong'><strong>wrong: </strong> city is empty</p>";
}

这用于检查空值并始终给出城市为空,这意味着未选择任何值

标签: phphtmlforms

解决方案


还不能评论。

也许尝试在选择之前关闭标签。

 <label id="city">
   <h4>city</h4>
 </label>         
 <select name="city">
   <option value="Afghanistan">Afghanistan</option>
   <option value="Albania">Albania</option>
 </select>

也许做

<?php echo "<pre>".print_r($_POST,true)."<pre>";

查看设置了哪些值。

正如其他人建议的那样检查值是空的()

if(!isset($_POST['city'])||empty($_POST['city']))

如果 city 为空,则返回 true,没有值,如果不存在则返回 true。

希望这可以帮助!

编辑1:

此外,由于 php 代码可能在同一页面上,因此可以省略 action 属性。

<form method="POST" class="contact">
 <label for="city">
   <h4>city</h4>
 </label>         
 <select id="city" name="city">
   <option value="Afghanistan">Afghanistan</option>
   <option value="Albania">Albania</option>
 </select>
</form>

还可以将 for 属性与您希望它表示的输入字段的 ID 一起使用


推荐阅读