-1

I am sending this jsonArray from android side And need to insert it into database.

I have following JSONArray:

[{
"pid":"28",
"prod_brand_name":"IPCA",
"prod_cat_name":"Zerodol P",
"prod_comp_name":"Zedfit Tablet",
"prod_mrp":"100",
"prod_name":"Collaflex",
"prod_quantity":"2",
"prod_size":"11",
"prod_total":"200",
"prod_unit":"90",
"ref_pid":"24"
},
}]

I am not able to fetch this array value using foreach and then write insert query. Thanks in advance!!

  • use json_encode function – PHP Ninja Nov 01 '18 at 06:27
  • like $arr = ['key'=>1,'value'=>json_encode($_POST['json_value'])] – PHP Ninja Nov 01 '18 at 06:28
  • Please provide the table's or tables' structure, do you have any code written already? are you using an SQL db? – Guy Louzon Nov 01 '18 at 06:29
  • No,i dont have any code.I have phpmyadmin – SHAMAL KASWATE Nov 01 '18 at 06:33
  • 1
    PHPMyAdmin is just a web based management tool for managing MySQL databases. Your application has nothing to do with that. You need to write PHP code that takes the request and insert it into the MySQL database. That's your job. We can help you if you run into _specific_ issues with your _existing_ code, but we won't write it all for you. So you should start by doing some research and make some attempts. – M. Eriksson Nov 01 '18 at 06:38

3 Answers3

1

use the json_decode function like this:

 $json= '[{
    "pid":"28",
    "prod_brand_name":"IPCA",
    "prod_cat_name":"Zerodol P",
    "prod_comp_name":"Zedfit Tablet",
    "prod_mrp":"100",
    "prod_name":"Collaflex",
    "prod_quantity":"2",
    "prod_size":"11",
    "prod_total":"200",
    "prod_unit":"90",
    "ref_pid":"24"
    }]';

$array= json_decode($json);

print_r($array);

now you have array using json_decode !

alex
  • 31
  • 3
0
$json= '[{
 "pid":"28",
 "prod_brand_name":"IPCA",
 "prod_cat_name":"Zerodol P",
 "prod_comp_name":"Zedfit Tablet",
 "prod_mrp":"100",
 "prod_name":"Collaflex",
 "prod_quantity":"2",
 "prod_size":"11",
 "prod_total":"200",
 "prod_unit":"90",
 "ref_pid":"24"
 }]';

$array= json_decode($json, true);

if you pass TRUE to the json_decode function, returned objects will be converted into associative arrays. By default this function take it as FALSE.

echo "<pre>";
print_r($array);
Sarwar
  • 59
  • 8
0

There are a few assumptions that are taken: The one table and its colum name matches exactly the json keys only one json array at a time, that is, one row And, an SQL db. I wrote an example using php mysqli

hope that helps

<?php

$arr = json_decode(JSONArray, true);

// the insert command and table columns 
$query = "INSERT INTO table (" ;
$query .= implode(", ", array_keys($arr)) . ") " ;

// the insert value
$query .= " VALUES ('" ;
$query .= implode("','" , $arr) . "')" ;

//run the query
$con=mysqli_connect("localhost","my_user","my_password","my_db");
mysqli_query($con, $query);

?>
Guy Louzon
  • 1,175
  • 9
  • 19