Jump to content

Elementary question undefined index/variable


Lassie

Recommended Posts

Although I have been programming with php for a little while I am still failing to understand what causes errors such as

Undefined index:user_id or Undefined variable: ven:

I thought that variables did not have to be predefined and where defined when you created them.

Could some guide me please as I seem to misunderstand a basic regarding php.

 

Link to comment
Share on other sites

The undefined index notices are normally caused by not checking whether a user defined variable exists or not, such as $_GET, $_POST and $_COOKIE vars.

 

Consider this code:

<?php

$name = $_POST['name'];

if($name)
{
    echo 'Your Name is: '. $name;
}

?>
<form action="#" method="post">
   Name: <input type="text" name="name"><br>
   <input type="submit" value="Post my name">
</form>

That code is fine to use. However if you run the script without submitting the form you'll get an Undefined index 'name' notice message displayed. This is because PHP is assigning the $name variable to the value of $_POST['name']. But we haven't submitted the form yet! So $_POST['name'] wont exist.

 

If you call any variable within your code PHP is expecting that variable exists. What you should do to prevent notices is to first verify that variable exists before using it. PHP has handy function for this called isset. In stead of doing the following:

$name = $_POST['name'];

if($name)

You should do:

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

Now if you run the script again without submitting the form there will be no notice message.

Link to comment
Share on other sites

Thats just a warning.. If I had error displaying on I would have all kinds all over my pages

 

Turn off error reporting or define variables if they are going to be called without validation

 

Well, no... it's a notice (warnings are different) and if you get them then something is wrong with your code. It's not critical however, but it should still be fixed.

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.