我有一个文本框。它的名字是例子。
<input type="text" name="example"/>
我想检查一下,任何数据是否来自示例。我尝试使用如下代码:
<?php
if(empty($_POST["example"]))
{
echo "You need to enter any text to example box.";
}
?>
但是这段代码正在打印,当我进入页面时是第一个。我想看到打印的数据,只有当点击提交时。
检查
if(!isset($_POST["submitButtonName"]))
{
// validation logic here
}
isset
在这里是正确的选择 -empty
仅用于检查已知变量以查看它是否“空”。根据文档
以下内容被认为是空的:
"" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) var $var; (a variable declared, but without a value in a class)
它没有说的是它如何处理未定义的数组成员。文档页面上的评论让我们从测试中获得了一些见解:http ://www.php.net/manual/en/function.empty.php#105722
请注意,当子项不存在但父项存在并且是字符串时检查数组的子项是否存在,将返回 false 为空。
而isset
(docs)旨在“确定变量是否已设置且不为 NULL。” - 正是您所追求的。因此,您的代码最终看起来像这样:
// check the length, too, to avoid zero-length strings
if(!isset($_POST["example"]) || strlen(trim($_POST["example"])) < 1) {
echo "You need to enter any text to example box.";
} else {
// handle form submission
}
文档
PHP isset
- http://php.net/manual/en/function.isset.php
PHP empty
- http://www.php.net/manual/en/function.empty.php
更多阅读 - http://virendrachandak.wordpress.com/2012/01/21/php-isset-vs-empty-vs-is_null/
<?php
if(isset($_POST['example']) && empty($_POST['example']))
{
echo "You need to enter any text to example box.";
}
?>
它是一个更好的选择:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(empty($_POST["example"]))
{
echo "You need to enter any text to example box.";
}
}
这将检查是否有POST
服务器,然后您将拥有您的条件。
if (!empty ($_POST))
{
// Validation logic here
if ((!isset ($_POST ['example'])) || (empty ($_POST ["example"])))
{
echo "You need to enter any text to example box.";
}
}
else
{
// No need to do any validation logic, the form hasn't been submitted yet.
}
首先检查 $_POST 变量,因为它仅在提交页面时可用。
<?php
if(!empty($_POST)){
if(isset($_POST['example']) && empty($_POST['example'])){
echo "You need to enter any text to example box.";
}
}
?>
首先检查submit
按钮。
<input type="text" name="example" value="" />
<input type="submit" name="submit" value="submit" />
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['example'])) {
echo "You need to enter any text to example box.";
}
?>