php - 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>";
}
这用于检查空值并始终给出城市为空,这意味着未选择任何值
解决方案
还不能评论。
也许尝试在选择之前关闭标签。
<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 一起使用
推荐阅读
- authentication - 如何禁用用户对 k8s 集群的访问?
- django - if 和 else 不保存到 None
- flutter - 如何创建子集合到 Firebase Firestore 文档
- visual-studio-code - 链接到 VSCode .ipynb 笔记本中的文件
- java - 如何从 JSON 而不是 LinkedHashMap 获取 List 对象?
- swift - 大量参数更改的动态视图更新 - 类 UUID?
- c++ - 如何将 SDL2 链接到编译器?
- php - PHP中的POST请求没有返回任何内容
- python - IndexError:列表索引超出范围,但卡片从零索引开始
- python - 如何使用for循环将django模板中创建的多个复选框中的数据传递到views.py而不使用表单