0

我有一个文本框。它的名字是例子。

<input type="text" name="example"/>

我想检查一下,任何数据是否来自示例。我尝试使用如下代码:

<?php
if(empty($_POST["example"]))
{
      echo "You need to enter any text to example box.";
}
?>

但是这段代码正在打印,当我进入页面时是第一个。我想看到打印的数据,只有当点击提交时。

4

7 回答 7

3

检查

if(!isset($_POST["submitButtonName"]))
{
   // validation logic here
} 
于 2012-06-06T19:32:37.187 回答
3

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 为空。

issetdocs)旨在“确定变量是否已设置且不为 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/

于 2012-06-06T19:39:18.413 回答
1
<?php
if(isset($_POST['example']) && empty($_POST['example']))
{
      echo "You need to enter any text to example box.";
}
?>
于 2012-06-06T19:32:39.743 回答
0

它是一个更好的选择:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if(empty($_POST["example"]))
       {
          echo "You need to enter any text to example box.";
       }
}

这将检查是否有POST服务器,然后您将拥有您的条件。

于 2012-06-06T19:34:07.450 回答
0
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. 
}
于 2012-06-06T19:36:47.213 回答
0

首先检查 $_POST 变量,因为它仅在提交页面时可用。

<?php
    if(!empty($_POST)){
      if(isset($_POST['example']) && empty($_POST['example'])){
         echo "You need to enter any text to example box.";
      }         
   }
 ?>
于 2012-06-06T19:41:44.650 回答
-1

首先检查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.";
        }
?>
于 2012-06-06T19:37:26.463 回答