Glese Posted December 2, 2011 Share Posted December 2, 2011 <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? Quote Link to comment https://forums.phpfreaks.com/topic/252299-avoidng-undefined-variable-notice/ Share on other sites More sharing options...
kickstart Posted December 2, 2011 Share Posted December 2, 2011 Hi Assign a default value to $user_name at the start of the script. You are using its value potentially before it has been assigned anything at all. All the best Keith Quote Link to comment https://forums.phpfreaks.com/topic/252299-avoidng-undefined-variable-notice/#findComment-1293428 Share on other sites More sharing options...
PFMaBiSmAd Posted December 2, 2011 Share Posted December 2, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/252299-avoidng-undefined-variable-notice/#findComment-1293446 Share on other sites More sharing options...
Glese Posted December 2, 2011 Author Share Posted December 2, 2011 Thanks a lot, and you are right, linear thinking helps. Quote Link to comment https://forums.phpfreaks.com/topic/252299-avoidng-undefined-variable-notice/#findComment-1293467 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.