【问题标题】:PHP post through URL parametersPHP 通过 URL 参数发布
【发布时间】: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


    【解决方案1】:

    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 参数用于读取某些内容,但不用于插入。

    【讨论】:

    • 谢谢,你能告诉我如何正确地在 URL 中传递参数以进行 POST
    • POST 参数在 URL 中没有给出,你需要在你的 android 应用中指定它是 POST 参数。
    • 正如我所说,它是在 android 端,你在哪里调用 url,你有你的应用程序的 sn-p 代码吗?
    猜你喜欢
    • 2012-04-30
    • 2013-10-17
    • 2017-08-07
    • 2013-06-21
    • 2022-01-22
    • 2012-08-01
    • 2020-11-27
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多