从JSON数组向MySQL插入多个空行

时间:2015-08-07 15:48:56

标签: php mysql json

以下PHP代码从Python脚本接收JSON数组,格式为:

{'payload': '[{"sample": 1, "count": 60, "sqlTimeStamp": "2015-08-03 15:14:05", "id": 1, "zone": 1}, {"sample": 2, "count": 60, "sqlTimeStamp": "2015-08-03 15:14:07", "id": 2, "zone": 1}, {"sample": 3, "count": 60, "sqlTimeStamp": "2015-08-03 15:14:09", "id": 3, "zone": 1}]'}

PHP代码如下:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";

$payload_dump = $_POST['payload'];
//$payload_dump = '{"device":"gabriel","data_type":"data","zone":1,"sample":6,"count":0,"time_stamp":"00:00"}';
echo $payload_dump;

$payload_array = json_decode($payload_dump,true);

if(is_array($payload_array)){
foreach($payload_array as $row){
//get the data_payload details
$sample = $payload_array['sample'];
$count = $payload_array['count'];
$time = $payload_array['sqlTimeStamp'];
$id = $payload_array['id'];
$zone = $payload_array['zone'];
//$time = $payload_array['time_stamp'];

$sql = "INSERT INTO data(sample, count, sqlTimeStamp, id, zone) VALUES('$sample', '$count', '$time', '$id', '$zone')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>

PHP脚本在MySQL数据库中创建正确数量的新行,但所有值都为零/ null。我做错了什么?

2 个答案:

答案 0 :(得分:1)

假设JSON实际上是这样的:

[{"sample": 1, "count": 60, "sqlTimeStamp": "2015-08-03 15:14:05", "id": 1, "zone": 1}, 
    {"sample": 2, "count": 60, "sqlTimeStamp": "2015-08-03 15:14:07", "id": 2, "zone": 1}, 
    {"sample": 3, "count": 60, "sqlTimeStamp": "2015-08-03 15:14:09", "id": 3, "zone": 1}]

看起来问题是你正在循环$payload_array,但是你没有引用当前迭代循环的$row变量。而不是

foreach($payload_array as $row) {
    $sample = $payload_array['sample'];
    $count = $payload_array['count'];
    $time = $payload_array['sqlTimeStamp'];
    $id = $payload_array['id'];
    $zone = $payload_array['zone'];

需要

foreach($payload_array as $row) {
    $sample = $row['sample'];
    $count = $row['count'];
    $time = $row['sqlTimeStamp'];
    $id = $row['id'];
    $zone = $row['zone'];

答案 1 :(得分:0)

在执行json_decode

之后再继续添加此测试之前
$payload_array = json_decode($payload_dump,true);
if ( json_last_error() !== JSON_ERROR_NONE ) {
    echo 'JSON Error : ' . json_last_error() . 
         ' ' . 
         json_last_error_msg();
    exit;
}

如果您正在处理的JSON数据无效,则应该告诉您。