在我的网络服务中,我有一个用于插入经度和纬度值的页面。成功插入数据库后,将在表中创建一个新行,并使用键" id" (INT)是自动增量。
它返回一个JSON对象:
{"成功":1,"消息":"现货成功添加!"}
我的问题:我想将为每行创建的id添加到生成的JSON对象中。像这样:
{"成功":1,"消息":"现货成功添加!"," id":54}
这是我到目前为止所得到的。行被插入到表中,但是我无法在JSON对象中显示我的id:
{"成功":1,"消息":"现货成功添加!"," like_id":null}
idtest.php
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
if (!empty($_POST)) {
//initial query
if(isset($_POST['user_id']) && !empty($_POST['user_id'])) {
$query = "INSERT INTO spot ( latitude, longitude, user_id ) VALUES ( :lat, :long, :uid ) ";
//Update query
$query_params = array(
':lat' => $_POST['latitude'],
':long' => $_POST['longitude'],
':uid' => $_POST['user_id']
);
} else {
$query = "INSERT INTO spot ( latitude, longitude ) VALUES ( :lat, :long ) ";
//Update query
$query_params = array(
':lat' => $_POST['latitude'],
':long' => $_POST['longitude']
);
}
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't add lat/long-pair!";
die(json_encode($response));
}
$latt = $_POST['latitude'];
$longg = $_POST['longitude'];
$getId = "SELECT id FROM spot WHERE latitude=$latt AND longitude=$longg LIMIT 1";
echo $getId;
//execute query
try {
$stmt2 = $db->prepare($getId);
$result2 = $stmt2->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't retrieve like_id!";
die(json_encode($response));
}
$row = $stmt2->fetchAll();
if($row) {
$response["success"] = 1;
$response["message"] = "Spot Successfully Added!";
$response["like_id"] = $row["id"];
echo json_encode($response);
}
} else {
?>
<h1>Registrer GPS-koordinater</h1>
<form action="idtest.php" method="post">
Latitude:<br />
<input type="text" name="latitude" value="" />
<br /><br />
Longitude:<br />
<input type="text" name="longitude" value="" />
<br /><br />
Google ID:<br />
<input type="text" name="user_id" value="" />
<br /><br />
<input type="submit" value="Opprett kolonne i 'spot'" />
</form>
<?php
}
?>
答案 0 :(得分:2)
更改此行
if($row) {
到
if(!$row) {
因为在此之前找不到$ row