【问题标题】:PHP _POST['field'] is empty when using API url使用 API url 时 PHP _POST['field'] 为空
【发布时间】:2016-09-14 06:35:03
【问题描述】:

我按照下面的在线教程构建了一个 PHP API。

https://trinitytuts.com/restful-web-services-with-php-mysqli/

当我使用 Chrome 的“Advanced Rest Client”时,HTTP 请求运行良好。我得到以下回复:

{
"status": 1
"msg": "Your record inserted successfully"
}

我尝试将以下 URL 直接放入我的网络浏览器:

http://localhost/API/insert.php/name=paul&email=paul@domain.com&status=active

我希望得到与使用 Advanced Rest Client 时相同的结果,但是,我收到了以下错误:

Notice: Undefined index: name

我正在使用以下 PHP 代码设置变量“名称”:

$name = $_POST['name'];

我的理解是,当我将 URL 粘贴到浏览器中时,$name 变量没有设置为 $_POST['name'],因为输入 URL 实际上并不是一个发布操作。

我是否可以在 URL 中添加一个参数以告诉浏览器发布?例如:

http://localhost/API/insert.php/type=POST&name=paul&email=paul@domain.com&status=active

简而言之,我希望能够将 URL 直接传递到网络浏览器中,而不必通过 HTML 表单发布。

这是我的 insert.php 的 PHP 代码

<?php
include 'conn.php';

$name = $_POST['name'];
$email = $_POST['email'];
$status = $_POST['status'];
$id = 1;

$sql = "INSERT INTO `service`.`user` (`id`, `name`, `email`, `status`) VALUES ($id, '$name', '$email', '$status');";

if ($connection->query($sql)) {
$msg = array("status" =>1 , "msg" => "Your record inserted successfully");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}

$json = $msg;

header('content-type: application/json');
echo json_encode($json);


@mysqli_close($conn);

?>

【问题讨论】:

  • Post 不是通过浏览器 url 完成的,$_GET 是。将$_POST 更改为$_GET
  • localhost/API/insert.php?name=paul&email=paul@domain.com&status=active
  • 使用?作为 get 参数的开头,而不是 /

标签: php rest api http post


【解决方案1】:

问题已通过将 insert.php 中的 $_POST 更改为 $_GET 解决

【讨论】:

  • 但是真的吗?,你不想用GET“发布”,因为那不是RESTful
  • 糟糕..错字..现在已修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 2013-06-04
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多