$ _POST方法显示undefine变量

时间:2016-03-12 17:39:42

标签: php mysql json localhost

如何解决这个问题我不使用$ _Post方法添加数据,但没有$ _POST方法显示未定义变量?

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);
    }

2 个答案:

答案 0 :(得分:1)

如果未设置$ _POST,则需要将变量定义为某些内容。

所以代码看起来像这样:

$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);
    }

<强>加成:

您可以轻松注入代码。使用预备语句来避免这种情况。

$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';
}

您可以详细了解here

答案 1 :(得分:0)

尝试更改此内容:

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

对此:

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