phpundefined-index

undefined index name1 and Undefined index name2


these are the two files in which error is occurred:

html_form.html

<html>
    <body>
        <center>
            <h1>Admission Form</h1>
            <br>
            <form action="php_register.php" name="registration">
            Firstname: <input type="text" name="name1" placeholder="Enter Firstname"/>
            <br>
            Lastname: <input type="text" name="name2" placeholder="Enter Lastname"/><br>
                <input type="submit" value="submit">
            </form>
        </center>
    </body>
</html>

php_register.php

<?php
     $fname=$_POST['name1'];
     $lname=$_POST['name2'];

    $conn=mysqli_connect("localhost","root","","test");

     if (isset($fname) && isset($lname))
      {
         mysqli_query($conn, "insert into test_table(firstname,lastname) 
         values ('$fname','$lname')");
      }
      else
         echo "<br> Errror....Values are not set in variables...!!!";
?>

( ! ) Notice: Undefined index: name1 in C:\wamp2\www\PHP_project\php_register.php on line 2 Call Stack

Time Memory Function Location

1 0.0022 131712 {main}( ) ...\php_register.php:0

( ! ) Notice: Undefined index: name2 in C:\wamp2\www\PHP_project\php_register.php on line 3 Call Stack

Time Memory Function Location

1 0.0022 131712 {main}( ) ...\php_register.php:0

Errror....Values are not set in variables...!!!


Solution

  • By default, form method is GET but you are trying to get values By $_POST.

    You didn't define form POST method then you can get values by $_GET or $_REQUEST as:

    $_GET['name1'];
    $_GET['name2'];
    

    or

    $_REQUEST['name1'];
    $_REQUEST['name2'];
    

    If you want to use $_POST then you should define form method="post"

    If you have no idea about form method, It's a better way to use $_REQUEST. By $_REQUEST you can get both type values.

    Example:

    $fname=isset($_POST['name1'])?$_POST['name1']:'';
     $lname=isset($_POST['name2'])?$_POST['name2']:'';
    
    $conn=mysqli_connect("localhost","root","","test");
    
     if (!empty($fname) && !empty($lname))
      {
         mysqli_query($conn, "insert into test_table(firstname,lastname) 
         values ('$fname','$lname')");
      }
      else
         echo "<br> Errror....Values are not set in variables...!!!";