2014-03-26 35 views
0

我正在做一个调查网站。我只想知道是否真的有必要通过使用isset!empty验证每个POST数据到数据库中。我有大约30列,我觉得它是多余的。在php中验证一堆表单数据 - 是否有必要?

有没有比这更清洁的方法?

编辑:

如果我有可选字段?我该如何解决这个问题?

+0

没有也不会'[NULL,NULL,NULL]'是不是'空()' –

回答

0

你可以做到这一点这样的方式:

PHP 5.5:

if(!empty(array_filter($_POST))) 
{ 
    //there are non-empty fields in $_POST 
} 

PHP < 5.5:

$filtered = array_filter($_POST); 
if(!empty($filtered)) 
{ 
    //there are non-empty fields in $_POST 
} 

这种差异是因为PHP 5.5 empty()之前无法接受非 - 变量(例如表达式)

编辑:如果你有一些可选字段,那么你就可以解决这个问题,例如,具有强制性的字段列表:

$array  = ['one'=>36, 'two'=>null, 'three'=>'data', 'four'=>0]; 
$mandatory = ['one', 'three']; 

$data = array_intersect_key($array, array_flip($mandatory)); 
if(!empty($data)) 
{ 
    //all mandatory fields are not empty 
} 
+0

如果我有可选字段? – Wax

+0

然后,你需要决定哪些是可选的,并将它们分开(检查编辑) –

+0

嘿,男人。将测试这一点。这看起来像一个天才ID。无论如何,只是为了弄清楚事情。强制性数组是我通过使用name属性来放置必填字段的地方吗? – Wax