简体   繁体   中英

PHP and form on same page

I have already seen all codes on StackOverflow. If I use action in form and paste php code on another file then it is fine but if I post php and form code on same file then it gives me this error:

Notice: Undefined index: fname in C:\\xampp\\htdocs\\php_codes\\form.php on line 50
Notice: Undefined index: lastname in C:\\xampp\\htdocs\\php_codes\\form.php on line 51

Here is the HTML/CSS code:

 table, td { border: 1px solid black; } 
 <h1 align="center">Enter Data below</h1> <br> <br> <br> <form method="post" action=""> <table align="center"> <tr> <td><input type="test" name="fname" placeholder="first name"></td> </tr> <tr> <td><input type="text" name="lastname" placeholder="last name"></td> </tr> <tr> <td align="right"><input type="submit" value="submit"></td> </table> </form> 

<?php

$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "1st_database";
$conn       = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("connection failed" . $conn->connect_error);
}
$fname = $_POST['fname'];
$lname = $_POST['lastname'];
if (empty($_POST['fname']) && empty($_POST['lastname'])) {
    echo "please enter name first";
} elseif ($query = "SELECT First_Name FROM sample_table WHERE First_Name = 
    '$fname'")
    if (mysqli_query($conn, $query) === true) {
        echo "this name already exists";
    } else {
        $sql = "INSERT INTO sample_table (First_Name,Last_Name)
          VALUES ('$fname','$lname')";
        if (!$conn->query($sql) === true) {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }
        echo "<br>";
        echo "<br>";
        echo "<br>";
        echo "<br>";
        echo "<br>";
        echo "<br>";

        $sql    = "SELECT * FROM sample_table";
        $result = $conn->query($sql);
        echo "<table>";

        while ($row = $result->fetch_assoc()) {
            echo "<tr><td><b>First Name: </b> " . "<td>" . $row["First_Name"] . "</td>" . "</td><td><b>Last Name: </b>" . "<td>" . $row["Last_Name"] . "</td>" . "</td></tr>";
        }

        echo "</table>";

    }

$conn->close();

Wrap your php code with this:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

This way the code will only be executed after submit.
Or simply check if isset($var) before trying to use it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM