Jump to content

Avoidng Undefined Variable Notice


Glese

Recommended Posts

<form method="post" action="">
    <input type="input" name="user_name" />
    <input type="submit" name="user_name_submit" />
</form>


<?php
if(!empty($_POST['user_name']))
    $user_name = $_POST['user_name'];

if(isset($_POST['user_name_submit'])) {
    $user_name_submit = $_POST['user_name_submit'];
}

$user_name_preg_match = preg_match('/[a-zA-Z0-9]/', $user_name);


if($user_name_preg_match) {
    
    echo 'true';
    
} else {
    
    echo 'false';
    
}

?>

 

 

 

In this script I am getting the notice:

 

Notice: Undefined variable: user_name

 

 

Any suggestions how to avoid the notice in this case?

Link to comment
Share on other sites

Here's a slightly different slant on the problem.

 

Your form processing code should only access the form data if the form has been submitted. You should have an if(isset($_POST['user_name_submit'])){... all the form processing code goes here...} statement around all the form processing code so that the form processing code will only be executed when the form has been submitted.

 

The first step of your user_name field validation logic, that is testing if $_POST['user_name'] is empty or not, should also determine if you execute any further code that uses the user_name value. If the user_name field is empty, you should setup an error message to be output telling the user that the required form field was empty. You would only execute the preg_match logic if the user_name form field was not empty.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.