PHP:isset的一个捷径而且是空的?
发布时间:2020-12-13 17:52:54 所属栏目:PHP教程 来源:网络整理
导读:我想知道下面的问题是否有更好的想法, 我有一个包含许多输入字段的表单,例如 input name="pg_title" type="text" value="" /input name="pg_subtitle" type="text" value="" /input name="pg_description" type="text" value="" /input name="pg_backdate" t
我想知道下面的问题是否有更好的想法,
我有一个包含许多输入字段的表单,例如 <input name="pg_title" type="text" value="" /> <input name="pg_subtitle" type="text" value="" /> <input name="pg_description" type="text" value="" /> <input name="pg_backdate" type="text" value="" /> etc 但有时我的表单中不需要上面的某些输入字段,例如,我只需要我的数据库注入的页面标题, <input name="pg_title" type="text" value="" /> etc 我有另一个PHP页面来处理$_POST数据, $pg_title = null; $pg_subtitle = null; $pg_description = null; $pg_backdate = null; if(isset($_POST['pg_title']) && !empty($_POST['pg_title']) ) $pg_title = $_POST['pg_title']; if(isset($_POST['pg_subtitle']) && !empty($_POST['pg_subtitle']) ) $pg_subtitle = $_POST['pg_subtitle']; if(isset($_POST['pg_description']) && !empty($_POST['pg_description']) ) $pg_description = $_POST['pg_description']; if(isset($_POST['pg_backdate']) && !empty($_POST['pg_backdate']) ) $pg_backdate = $_POST['pg_backdate']; 每次我必须检查某个输入字段的$_POST是否设置而不是空,否则它的变量将被设置为null,这样我就不会在我的数据库中注入一个空的空格. 当我有一长串要处理的变量时,我发现if-condition中的isset和!为非常重复. 是否有任何默认的PHP函数来“缩短”上面的过程?或者我是否必须编写用户定义函数来处理这个问题? 或者也许有另一种方式呢? 谢谢. 编辑: 非常感谢大家的帮助. 我的php页面中只有一些额外的代码可以处理$_POST数据, $sql = " UPDATE root_pages SET pg_url = ?,pg_title = ?,pg_subtitle = ?,pg_backdate = ?,pg_description = ?,... updated_by = ? WHERE pg_id = ? "; $result = $connection->run_query($sql,array( $pg_url,$pg_title,$pg_subtitle,$pg_backdate,$pg_description,... $pg_id )); 如你所见,$pg_description等总是存在于我的查询中.所以当我没有数据时,如果我得到$pg_subtitle =”而不是$pg_subtitle = null,我的数据库记录将为该列提供一个空的空间. 谢谢 :-)
您可以使用简单的功能
function post_value_or($key,$default = NULL) { return isset($_POST[$key]) && !empty($_POST[$key]) ? $_POST[$key] : $default; } 然后使用: $pg_title = post_value_or('pg_title'); // OR with a default $pg_title = post_value_or('pg_title','No Title'); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |