WordPress php undefined index with form posting to db

I am building a very small form for a wordpress widget. The form is just a drop down select input that allows users to select their business type – this is then stored in the wp_usermeta table in the database.

The dropdown is actually selected on registration, so this form is more of an opportunity for users to change the value.

Read More

Here is the php I am using to create the form:

<?php 
$user = wp_get_current_user();        
$selected = get_user_meta( $user->ID, 'i_am_a', true ); 
?>

<form method="post">        
<h3>I am a...</h3>
        <select name="i_am_a" id="i_am_a">
            <option value="musician" autocomplete="off" <?php echo ($selected == "musician")?  'selected="selected"' : '' ?>>Musician/Artist</option>
            <option value="band" autocomplete="off" <?php echo ($selected == "band")?  'selected="selected"' : '' ?>>Band</option>
            <option value="photographer" autocomplete="off" <?php echo ($selected == "photographer")?  'selected="selected"' : '' ?>>Photographer</option>
            <option value="business" autocomplete="off" <?php echo ($selected == "business")?  'selected="selected"' : '' ?>>Small Business</option>
            <option value="other" autocomplete="off" <?php echo ($selected == "other")?  'selected="selected"' : '' ?>>Other</option>
        </select>
<input type="submit" name="submit" value="change" class="button"/>

</form>
<?php
    $i_am_a = $_POST['i_am_a'];
    update_user_meta( $user->ID, 'i_am_a', $i_am_a );
?>

Notice: Undefined index: i_am_a in /home/…/layers-whitelabel.php on line 90

Line 90 is as follows:

$i_am_a = $_POST['i_am_a'];

How can I get rid of this error?

Related posts

2 comments

  1. Declare your variables. Or use isset() to check if they are declared before referencing them, as in:

    $i_am_a = isset($_POST['i_am_a']) ? $_POST['i_am_a'] : '';
    
  2. try this,

      $i_am_a = isset($_POST['i_am_a']) ? $i_am_a = $_POST['i_am_a'] : 0;
    

    Please see this answer for the explanation of using 0 to check.

Comments are closed.