-1

How can I define my $_POST variables in below sample code before submission to prevent PHP Undefined index notice. HTML sample code:

<form action="" method="post">
<input type="text" name="my_input" id="my_input">
<button type="submit">Submit</button>
</form>

my php sample code:

$post_variable = $_POST["my_input"];

Thanks in advance.

4lisalehi
  • 29
  • 3
  • 14

2 Answers2

2

just check that the post variable exists before trying to access it:

$value1 = isset($_POST["my_input"]) ? $_POST['my_input'] : false;

now, if my_input is set in the post $value1 will contain it, otherwise it will be false

Jonathan Crowe
  • 5,793
  • 1
  • 18
  • 28
0

No, they're set on the server side in case of a POST request so you can't really set them before the request is sent

However, what you can do is this

if(isset($_POST["my_input"])) $value1 = $_POST["my_input"];

This makes sure that the value is set in the POST array before assigning it to a variable and thus removing the error of the undefined index

Ali
  • 3,479
  • 4
  • 16
  • 31