PHP中的REST Web服务MySQL JSON - 将空值插入数据库

时间:2015-11-12 08:20:38

标签: php mysql json rest

我在Google Chrome上使用Advanced Rest Client来处理POST次请求。 一切正常,我甚至收到消息User has been successfully registered!但是在查看数据库时我看到的是attributes viz firstnamelastname等的值只是BLANK虽然查询成功发出 怎么了 ?

create.php

<?php

require_once 'connect.php';


if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Get post data`
    $firstName = isset($_POST['firstname']) ? mysqli_real_escape_string($connection, $_POST['firstname']) : "";
    $lastName = isset($_POST['lastname']) ? mysqli_real_escape_string($connection, $_POST['lastname']) : "";
    $email = isset($_POST['email']) ? mysqli_real_escape_string($connection, $_POST['email']) : "";
    $password = isset($_POST['password']) ? sha1(md5(mysqli_real_escape_string($connection, $_POST['password']))) : "";
    $status = 0; // Here we set by default status In-active.
    // Save data into database
    $query = "INSERT INTO users (firstname,lastname,email,password,status) VALUES ('{$firstName}',
    '{$lastName}','{$email}','{$password}','{$status}')";

    $insert = mysqli_query($connection, $query);

    if($insert){
        $data = array("result" => 1, "message" => "User has been successfully registered!");
        } else {
        $data = array("result" => 0, "message" => "Error!");
    }
}
else {
    $data = array("result" => 0, "message" => "Incorrect Request Method!");
}

mysqli_close($connection);
/* JSON Response */
header('Content-type: application/json');
echo json_encode($data);
?>

Screenshots From The REST Client Screenshots From The REST Client

Screenshot From Database

2 个答案:

答案 0 :(得分:1)

将您的参数放入请求正文,而不是标题。也许这是在&#34; Payload&#34;您的HTTP客户端的部分?此外,您是否需要json_decode PHP中的POST数据,因为您将数据作为JSON发送?

尝试通过转储$_POST数组中的空白值来进行调试。

此外,您可能希望通过验证发送的数据来使后端更加强大。例如,不要为您收到的每个参数接受NULL值。

答案 1 :(得分:0)

也许问题发生在Advanced Rest Client 我发送了payload作为application/json并且它没有获得POST数据,但是在将Content-Typ e更改为application/x-www-form-urlencoded时,一切正常!