if(isset())总是显示为true?

时间:2014-05-30 04:23:54

标签: php

我有4个必填字段。我使用AJAX表单处理,在表单提交之前提交表单时,它会检查论坛元素是否为空。使用以下 PHP 代码。

if(isset($_REQUEST['faq_topic'], $_REQUEST['faq_detail'], $_REQUEST['faq_name'], $_REQUEST['faq_email'])){

现在即使表格留空,也会因某种原因而提交?为什么会这样?难道不会发生这种情况吗?除了可以提交空白数据之外,该表格完美无缺。

这是整个脚本...减去HTML / jQuery

// Required Configuration
include_once('required.php');

// get data that sent from form
$topic=$_REQUEST['faq_topic'];
$detail=$_REQUEST['faq_detail'];
$name=$_REQUEST['faq_name'];
$email=$_REQUEST['faq_email'];

// check if all forms are filled out
if(isset($_REQUEST['faq_topic'], $_REQUEST['faq_detail'], $_REQUEST['faq_name'], $_REQUEST['faq_email'])){
    // Format Date And Time
    $datetime=date("m/d/y h:i");
    // SQL Insert Statement
    $sql="INSERT INTO $tbl_name_question(topic, detail, name, email, datetime)VALUES('$topic', '$detail', '$name', '$email', '$datetime')";
    // Check If SQL Went Through
    $result=mysql_query($sql);
    // Now Print Out Success Or MySQL Error
    if($result){
        $html = '<div class="alert alert-dismissable alert-success"><button type="button" class="close" data-dismiss="alert">×</button>You <strong>successfully</strong> submited a question to the FAQ bored.</div>';
        print($html);
    }
        else {
        $html = '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert">×</button>Opps there was a problem on our end... Please try again later.</div>';
        print($html);
    }
    // Close MySQL Connection
    mysql_close();
} else {
    // If the required items were not filled out print the following
    $html = '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert">×</button><strong>All</strong> forms are required.</div>';
    print($html);
}

如果你有建议那就太棒了!另外,如果你对我在我的代码中做错的事情有任何其他意见,那么如果你能在那里帮助我也会很好。

非常感谢提前!!

最诚挚的问候!

3 个答案:

答案 0 :(得分:1)

isset检查变量是否已设置,即使变量包含空字符串,也会设置变量。

如果要检查变量是否为空,则应使用empty代替。

执行类似

的操作
$topic=trim($_REQUEST['faq_topic']);
$detail=trim($_REQUEST['faq_detail']);
$name=trim($_REQUEST['faq_name']);
$email=trim($_REQUEST['faq_email']);

if (!empty($topic) && !empty($detail) && !empty($name) && !empty($email)) {

答案 1 :(得分:0)

isset()检查是否完全定义了变量。由于我假设您将变量发布为空,因此变量已设置,但值为空。

您需要使用的是empty(),它将决定变量的值是否留空。

if(!empty($_REQUEST['faq_topic']) && !empty($_REQUEST['faq_detail']) && empty($_REQUEST['faq_name']) && !empty($_REQUEST['faq_email']))

答案 2 :(得分:0)

删除可以执行的警告

$topic= isset($_REQUEST['faq_topic']) ? $_REQUEST['faq_topic'] : '';
$detail= isset( $_REQUEST['faq_detail'] ) ? $_REQUEST['faq_detail'] : '';

然后......

if( !empty($topic) && !empty($detail) ... ) 
{
  ...
}

这可能看起来有点矫枉过正,但你会摆脱一些警告并检查空字符串。

如果您不想允许空格,可以使用trim(...)。

相关问题