Skip to content
Advertisement

PHP: a short cut for isset and !empty?

I wonder if there any better ideas to solve the problem below,

I have a form with a number of input fields, such as,

<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

But sometimes don’t need certain input fields above in my form, for instance, I only need the page title for my db injection,

<input name="pg_title" type="text" value="" />
 etc

And I have another php page to handle the $_POST data,

$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'];

Every time I will have to check if the $_POST of a certain input field is set and not empty, otherwise its variable will be set to null, so that I won’t inject an empty space into my DB.

I find the isset and !empty in the if-condition are very repetitive when I have a long list of variables to handle.

Is there any default PHP function to ‘shorten‘ the process above? Or do I have to write a user-defined function to handle this?

Or maybe there is another way to do this?

Just some extra code in my php page that handle the $_POST data,

$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
        ));

as you see that $pg_subtitle, $pg_backdate, $pg_description, etc always present in my query. so if I get $pg_subtitle = '' instead of $pg_subtitle = null when there is no data in it, my db record will have an empty space for that column.

Advertisement

Answer

You can use a simple function

function post_value_or($key, $default = NULL) {
    return isset($_POST[$key]) && !empty($_POST[$key]) ? $_POST[$key] : $default;
}

Then use:

$pg_title = post_value_or('pg_title');
// OR with a default
$pg_title = post_value_or('pg_title', 'No Title');
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement