-2

这是我得到的json字符串:

[data] => {"id":"0612833398","longitude":"-143.406417","latitude":"32.785834","timestamp":"10-10 07:56"}

我需要它把它像这样放在我的 php 文件中,但我只得到 NULL 值。

<?php
file_put_contents('dump.txt', "POST: \n" . print_r($_POST, true) . "\n\n\n GET: \n" . print_r($_GET, true));

$link = mysql_connect('server', 'bla', 'bla')
or die('Could not connect: ' . mysql_error());

mysql_select_db('md267052db227433') or die('Could not select database');

// Performing SQL query
if (isset($_POST['data'])) {
$data = json_decode($_POST['data']);
$id = $data['id'];
$latitude = $data['latitude'];
$longitude = $data['longitude'];
$timestamp = $data['timestamp'];

}
$query = sprintf("INSERT INTO locatie (id, longitude, latitude, timestamp) VALUES ('%s', '%s', '%s', '%s')", mysql_real_escape_string($id), mysql_real_escape_string($longitude),  mysql_real_escape_string($latitude), mysql_real_escape_string($timestamp))  ;
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
echo "OK";


// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?>

我觉得我真的很接近:第 1 行的 dump.txt 看起来像这样:

POST: 数组 ( )

 GET: 
Array
(
    [data] => {"id":"0612833398","longitude":"-143.406417","latitude":"32.785834","timestamp":"10-10 07:56"}
)
4

2 回答 2

4

您需要转换为数组,并更改为$_GET

if (isset($_GET['data'])) {
    $data = json_decode($_GET['data'], true);
    $id = $data['id'];
    $latitude = $data['latitude'];
    $longitude = $data['longitude'];
    $timestamp = $data['timestamp'];

    $query = sprintf("INSERT INTO locatie (id, longitude, latitude, timestamp) VALUES ('%s', '%s', '%s', '%s')", mysql_real_escape_string($id), mysql_real_escape_string($longitude),  mysql_real_escape_string($latitude), mysql_real_escape_string($timestamp))  ;
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());
    echo "OK";

    // Free resultset
    mysql_free_result($result);
}

如果 的第二个参数json_decode为真,则函数将返回关联数组而不是对象。

附带说明一下,如果您开始构建项目,最好将代码移动到 MySQLi 或 PDO,因为mysql_*函数已被弃用并且不应再使用。查看这个不错的教程以帮助您入门。

于 2012-10-10T08:34:14.633 回答
2

那个json是对象序列化而不是数组你应该写:

$data = json_decode($_GET['data']);
$id = $data->id;
$latitude = $data->latitude;
$longitude = $data->longitude;
$timestamp = $data->timestamp;

}
于 2012-10-10T08:37:25.470 回答