我正在尝试使用 android 应用程序和网站 url 将 php 发布到 mysql 数据库。
但我不知道如何通过 url 发出 post 请求。
我试过 http://localhost/api/create_product.php?name=chetan&price=2000&description=someDescription
这将返回缺少的必填字段。
也许我要传递的网址不正确
帮助我了解如何使用成功返回 JSON 的 URL 在数据库中发帖。
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
DB_CONNECT() 工作正常,因为我能够成功执行 GET 查询
最佳答案
http://localhost/api/create_product.php?name=chetan&price=2000&description=someDescription => 这是一个带有 GET 参数的请求和您在此处的声明:
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
正在检查 POST 参数,要么将每个 $_POST 更改为 $_GET,要么更改传递参数的方法,因为通常当您提供参数以将其放入数据库时,出于安全原因,它是通过 POST 而不是 GET。 GET 参数用于读取内容但不用于插入。
关于PHP 通过 URL 参数发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246060/