How do I prevent `undefined index` by using values already set in a database by default?

266 views Asked by At

I am working on an admin panel for my website that will change website settings. Everything works the way it's supposed to, except for the number of PHP warnings I get when a submit some values. I get the error undefined index. I know you can use isset(), but in my case, that would be very messy. How would I use a value in a database as a default value if my value is not set?

My code:

<?php
    
 if(!empty($_POST)) {
    $_POST['cms_and_posting'] = (bool) $_POST['cms_and_posting'];
    $_POST['google_verify'] = (bool) $_POST['google_verify'];
 }

?>

I have heard of something called the "null-coalescing-operator" in PHP, but I am a bit confused on how I would use that in my code.

2

There are 2 answers

2
Lucas Gervas On BEST ANSWER

You can use null coalescing operator.

 <?php
    
  if(!empty($_POST)) {
    $_POST['cms_and_posting'] = $_POST['cms_and_posting'] ?? $youdbvalue1;
    $_POST['google_verify'] =   $_POST['google_verify'] ?? $youdbvalue2;
  }

?>
1
LSerni On

You have a series of settings from the database, so I figure you have something like

$options['cms_and_posting'] = 1;

You can then use foreach():

foreach (array_keys($options) as $key) {
    if (array_key_exists($key, $_POST)) {
        $options[$key] = $_POST[$key];
    }
}

Note that, here, you do not have any check on what the value is. Usually your configuration table would be something like

varname           varvalue          vartype    varregex    varcomment
cms_and_posting   1                 bool       ^[01]$      Option
google_verify     1                 bool       ^[01]$      Option
user_email        [email protected]  email      NULL        Admin Email
pagesize          50                int        ^\\d+$      Rows per page
...

You would still run a foreach cycle, using the filter functions to appropriately validate each entry:

switch($option['vartype']) {
    case 'bool':
        if (in_array($value, [ '1', 'Y', 'y', 'YES', 'ON', 1 ], true)) {
            $value = true;
        } else if (in_array($value, [ '0', 'N', 'n', 'NO', 'OFF', 0 ], true)) {
            $value = false;
        } else {
            throw new \Exception("{$value} is not a valid boolean");
        }
        break;
    case 'email':
        ...