-2

How to solve this i don't add data using by $_Post Method, but without $_POST method showing undefine variable?

if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['age'])){

        //Getting values
        $firstname = $_POST['firstname'];
        $lastname = $_POST['lastname'];
        $age = $_POST['age'];

        //Creating an sql query
        $sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";

        //Importing our db connection script
        require_once('connect.php');

        //Executing query to database
        if(mysqli_query($con,$sql)){
            echo 'Employee Added Successfully';
        }else{
            echo 'Could Not Add Employee';
        }

        //Closing the database 
        mysqli_close($con);
    }
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77

2 Answers2

1

You need to define your variables to something if $_POST is not set.

So code would look something like this:

$firstname = isset($_POST['firstname']) ? $_POST['firstname'] ? "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$age = isset($_POST['age']) ? $_POST['age'] : "";
//if isset $_POST['age'] then assign it to $_POST['age'] else assign it to ""  



if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['age'])){

        //Creating an sql query
        $sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";

        //Importing our db connection script
        require_once('connect.php');

        //Executing query to database
        if(mysqli_query($con,$sql)){
            echo 'Employee Added Successfully';
        }else{
            echo 'Could Not Add Employee';
        }

        //Closing the database 
        mysqli_close($con);
    }

Bonus:

You code can be easily injected. Use prepared statements to avoid this.

$sql = "INSERT INTO info (firstname,lastname,age) VALUES (?,?,?)"; // question marks are placeholders to bind values to
$stmt = $con->prepare($sql); // prepare query
$stmt->bind_param("sss", $firstname, $lastname, $age); // bind values to your query
if($stmt->execute()){ // if success
    echo 'Employee Added Successfully';
}else{
    echo 'Could Not Add Employee';
}

You can learn more about it here

Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77
0

Try changing this one:

$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('$firstname','$lastname','$age')";

To this one:

$sql = "INSERT INTO info (firstname,lastname,age) VALUES ('".$firstname."','".$lastname."','."$age."')";
lulu
  • 24
  • 6
  • @C.Liddell Yes you are right. Try using empty() instead of isset(). – lulu Mar 12 '16 at 18:00
  • @Azharul Islam Maybe it is $_GET not $_POST ? :D (sorry to post here, I cannot post comment to your question) Where did the variables came from? Can you post more code? – lulu Mar 12 '16 at 18:11