【发布时间】:2016-03-27 09:58:33
【问题描述】:
我正在尝试使用 android 应用程序和网站 url 将 php 发布到 mysql 数据库。
但我不知道如何通过 url 发出 post 请求。
我试过http://localhost/api/create_product.php?name=chetan&price=2000&description=someDescription
这将返回缺少的必填字段。
也许我试图传递的网址不正确
帮助我了解如何使用返回 JSON 成功的 URL 在 DB 中发布帖子。
<?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 查询
【问题讨论】:
标签: php mysql json post http-post