I wonder if there any better ideas to solve the problem below,
I have a form with a number of input fields, such as,
It is an interesting question and I await the answers.
However, little trick, you can do inline :
$pg_title = isset($_POST['pg_title']) && !empty($_POST['pg_title']) ? $_POST['pg_title'] : null;
This function check if variable is set, is not empty, eventually if has any value.
/**
* @param var - testing variable
* @param value
* @return boolean
*/
function is(&$var, $value = null){
if(!is_null($value)){ return IsSet($var) && $var == $value; }
return IsSet($var) && !empty($var);
}
echo $_GET['id']; // this produce Warning
echo is($_GET['id'])?'1':'0'; // return false
echo $_GET['id']; // after first using function is(), will not be produce Warning!!!
is($_GET['id']); // return false
IsSet($_GET['id']); // return false
$_GET['id'] = 7;
is($_GET['id'], 7); // return true;
I do not have enough rep to comment. However, the suggestion that vladkras made to use:
$some_var = $_POST['some_var'] ? $_POST['some_var'] : NULL;
is not E_ALL compliant. You should be checking array keys before accessing them using either empty() or isset() as others have suggested. Especially for user input.
Also, his second suggestion to use the MySQL function "NULLIF()" as in the following manner:
NULLIF('".$_REQUEST['some_var']."', '')
is even worse. Inserting unsanitized user input directly into a SQL query is a primary vector for a SQL injection attack.
Consider using the available-by-default filter extension's filter_input function. You'll avoid the missing index Notice and get data sanitization at the same time.
+1 for array_merge()
but I think that nevertheless short form for:
if (isset($_POST['some_var']) and !empty($_POST['some_var'])) $some_var = $_POST['some_var'];
else $some_var = NULL;
should be:
$some_var = $_POST['some_var'] ? $_POST['some_var'] : NULL;
yes, it causes "undefined index" notice, but it checks for both existance and emptiness
EDIT: and returns NULL of course, as OP asked.
During a small research, I've found an interesting "Control Flow Function" for this case, I've never used before: NULLIF()
So you can perform this task without PHP. Just wrap all variables in it:
NULLIF('".$_REQUEST['some_var']."', '')
in your query instead of '".$_REQUEST['some_var']."'
If variable is empty or doesn't exist it will be NULLIF('', '')
as far as '' == ''
it will return NULL. Otherwise it will return first arg == your variable.
You can create a small function that can do this job for you simply.
function sc_post_isset(...$args) {
$exists = true;
foreach($args as $arg) {
if ( !isset($_POST[$arg]) || empty($_POST[$arg]) ) {
$exists = false;
}
}
return $exists;
}
Use,
if(sc_post_isset('key')) {
// it exists.
}
OR
if(sc_post_isset('key1', 'key2', 'key3')) {
// it exists.
}
It just simply check if all the provided keys exist within $_POST and not empty