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
https://forums.phpfreaks.com/topic/252299-avoidng-undefined-variable-notice/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.