PHP POST没有在mysql中保存我的数据,使用postman检查我的api

时间:2017-06-09 06:52:19

标签: php mysql json rest

我正在使用php,我希望使用 chrome postman

制作一个简单的API来保存我的name字段在数据库中

这是我的PHP代码:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
header('Cache-Control: max-age=900');
header("Content-Type: application/json"); // tell client that we are sending json data


$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$dxname  =$_GET['name'];

$sql = "INSERT INTO crudtable(firstname, lastname, email,favjob)
VALUES ('".$dxname."', 'Doe', 'john@example.com','coder')";

if ($conn->query($sql) === TRUE) {
    echo json_encode("New record created successfully");
   // echo "New record created successfully";
} else {
    echo json_encode("Some error");
   // echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

当我使用邮递员时, 1.名称未保存在db [仅保存硬编码值] 中 2.保存数据后,我没有收到echo json_encode("New record created successfully");

请帮助,附上我的邮递员结果的截图以及我如何传递名称变量

Click here to see the image

2 个答案:

答案 0 :(得分:2)

您正在通过post方法发送数据,而您正在使用GET。

变化:

$dxname  =$_GET['name'];

$dxname  =$_POST['name'];

也:

if ($conn->query($sql) === TRUE) {

if ($result = $conn->query($sql))
{ echo json_encode("New record created successfully");
   // echo "New record created successfully";
} else {
    echo json_encode("Some error");
   // echo "Error: " . $sql . "<br>" . $conn->error;
}

Cannot query MySQL database via PHP

答案 1 :(得分:0)

Json应该是一个数组..试试这个

echo json_encode(array("Success"));

你在哪里得到$ _GET方法?你能告诉我们HTML页面吗?你可以尝试使用  $_POST['name'];