如何将已解码的json数据存储到变量中并将其插入到mysql表中

时间:2014-11-21 22:06:23

标签: php android json

您好我的Android应用程序Iam从sqlite检索数据,现在通过使用JSON我想将该数据存储到mysql表中。请帮我实现这个目标

我没有得到如何在表中存储所有值,每次尝试插入时只插入一行。

这是代码。

<?php

error_reporting(0);

include_once 'db_conn.php';  //Include the database connection strings


$received_json = $_POST["sparesJSON"];

if (get_magic_quotes_gpc())

{
    $received_json = stripslashes($received_json);
}

$received_json = json_decode($received_json);

//catch variable

$item_name = $received_json[0]->item_name;

$quantity = $received_json[0]->quantity;

$total_price = $received_json[0]->total_price;

$cycle_id = $received_json[0]->cycle_id;

$date = $received_json[0]->date;

for($i=0;i<count($received_json;i++)
{


            $insert_spares = "insert into spares_items (item_name, quantity, total_price,    cycle_id, date) values (\"$item_name\", \"$quantity\", \"$total_price\", \"$cycle_id\", \"$date\")";

            mysql_query($insert_spares);
}

//encode result array in json

echo json_encode($cycle_id);


//send this as an response to the Android
?>

2 个答案:

答案 0 :(得分:1)

$received_json = json_decode($received_json);



for($i=0;$i<count($received_json);$i++)
{


    $item_name = $received_json[$i]->item_name;

    $quantity = $received_json[$i]->quantity;

    $total_price = $received_json[$i]->total_price;

    $cycle_id = $received_json[$i]->cycle_id;

    $date = $received_json[$i]->date;    
    $insert_spares = "insert into spares_items (item_name, quantity, total_price,    cycle_id, date) values (\"$item_name\", \"$quantity\", \"$total_price\", \"$cycle_id\", \"$date\")";

    mysql_query($insert_spares);
}

答案 1 :(得分:0)

$received_json = json_decode($received_json);

$inserted_names = array();

for($i=0;$i<count($received_json);$i++)
{


    $item_name = $received_json[$i]->item_name;
    // if we have already inserted this name, don't insert again
    if (in_array($item_name, $inserted_names)) {
        continue;
    }

    $quantity = $received_json[$i]->quantity;

    $total_price = $received_json[$i]->total_price;

    $cycle_id = $received_json[$i]->cycle_id;

    $date = $received_json[$i]->date;    
    $insert_spares = "insert into spares_items (item_name, quantity, total_price,    cycle_id, date) values (\"$item_name\", \"$quantity\", \"$total_price\", \"$cycle_id\", \"$date\")";

    mysql_query($insert_spares);
    // save item name to list of names already inserted
    array_push($inserted_names, $item_name);
}