Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'Notice: Undefined index:' in PHP form action

Tags:

I received the following error message when I tried to submit the content to my form. How may I fix it?

Notice: Undefined index: filename in D:\wamp\www\update.php on line 4

Example Update.php code:

<?php      $index = 1;     $filename = $_POST['filename'];      echo $filename; ?> 

And $_POST['filename'] comes from another page:

<?php     $db = substr($string[0],14) . "_" . substr($string[1],14) . "_db.txt"; ?>  <input type="hidden" name="filename" value="<?php echo $db; ?>"> 
like image 385
Ting Ping Avatar asked Dec 31 '12 05:12

Ting Ping


People also ask

How do I fix Undefined index in PHP?

Undefined Index in PHP is a Notice generated by the language. The simplest way to ignore such a notice is to ask PHP to stop generating such notices. You can either add a small line of code at the top of the PHP page or edit the field error_reporting in the php. ini file.

How do I get rid of notice Undefined index?

You can get rid of the PHP undefined index notice by using the isset() function. The PHP undefined variable notice can be removed by either using the isset() function or setting the variable value as an empty string.

What causes Undefined index in PHP?

Notice Undefined Index in PHP is an error which occurs when we try to access the value or variable which does not even exist in reality. Undefined Index is the usual error that comes up when we try to access the variable which does not persist.


2 Answers

Assuming you only copy/pasted the relevant code and your form includes <form method="POST">


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

If _POST is not set the filename variable won't be either in the above example.

An alternative way:

$filename = false; if(isset($_POST['filename'])){     $filename = $_POST['filename'];  }      echo $filename; //guarenteed to be set so isset not needed 

In this example filename is set regardless of the situation with _POST. This should demonstrate the use of isset nicely.

More information here: http://php.net/manual/en/function.isset.php

like image 184
Sir Avatar answered Sep 19 '22 15:09

Sir


if(isset($_POST['form_field_name'])) {     $variable_name = $_POST['form_field_name']; } 
like image 39
Rabby shah Avatar answered Sep 18 '22 15:09

Rabby shah