gpt4 book ai didi

php - 从 php 检索 JSON 时出错 - Android

转载 作者:行者123 更新时间:2023-11-29 00:39:56 26 4
gpt4 key购买 nike

我正在为我的 android 应用程序使用一个 php 文件来与我正在使用的 mySql 数据库进行通信。当我只使用 INSERT 查询时,php 工作得很好,但是当我添加 SELECT 查询时,它只是无法将 JSON 返回到我的应用程序。关键是,在我向数据库添加一行之后,我想返回新行的 id。 id 为 int,自增。

这是我的 PHP 代码:

<?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['lat']) && isset($_POST['lon']) && isset($_POST['alt'])) {

$name = $_POST['lat'];
$price = $_POST['lon'];
$description = $_POST['alt'];

// 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 sits(lat, lon, alt) VALUES($name, $price, $description)");

// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "sit created.";
$result2 = mysql_query("SELECT id FROM sits ORDER BY id DESC LIMIT 1")
while($row = mysql_fetch_array($result2))
{
$response["id"]=$row['id'];
}
// 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);
}
?>

最佳答案

你绝对需要mysql_insert_id () 为了那个原因。 SELECT 查询是不必要的。文档状态:

Return Values

The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.

if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "sit created.";
$response["id"] = mysql_insert_id();
// echoing JSON response
echo json_encode($response);
}

关于php - 从 php 检索 JSON 时出错 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12717893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com