开发者

JSON Array and PHP problem

array 0 => array 'categoryID' => string '1' (length=1) 'category' => string 'Restaurants' (length=11) 'subcategory' => string 'Chinese' (length=7)

'subcategoryID' => string '12' (length=2)

How can I get this data in MYSQL. I have tried JSON_Decode but problem is I am getting "Array" stored in MYSQL instead of string.

Please help. Sorry I am new in stackoverflow. I following is base code with database structure:

CategoryID Int(5), Category Var(254), Subcategory Var(254), SubCategoryID Int (5).

Following is code I used:

<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("cp");
$alldate = '[{ "categoryID": "1", "category": "Restaurants", "subcategory": "Chinese", "subcategoryID": "12" }]';
$json = json_decode($alldate);
$i=0;
foreach ($json  as $k1=>$v1) {
    echo $i;
  foreach($v1 as $k2=>$v2){
    if ($k2 == 'categoryID')$vals['categoryID'][]=$v2;
    if ($k2 == 'category')$vals['category'][]=$v2;
    if ($k2 == 'subcategory')$vals['subcategory'][]=$v2;
    if ($k2 == 'subcategoryID')$vals['subcategoryID'][]=$v2;
  }
    $insert_categoryID[]='Name:'.$vals['categoryID'][$i];
    $insert_category[]= $vals['category'][$i];
    $insert_subcategory[]= $vals['subcategory'][$i];
    $insert_subcategoryID[]= $vals['subcategoryID'][$i];
    }

    print_r($insert_categoryID);
    print_r($insert_category);
    print_r($insert_subcategory);
    print_r($insert_subcategoryID);
    ?>

Thanks for your answers. I am che开发者_Python百科cking this with solution provided here


On your array (for example $array), you will need to do a foreach:

$array = json_decode($json);
$inserts = "";
$values = "";
foreach($array as $key => $value){
     $inserts .= "'$key', ";
     $values .= "'$value', ";
}
$inserts = substr($inserts,0,-2);
$values =  substr($values,0,-2);
$query = mysql_query("INSERT INTO `table` (".$inserts.") VALUES (".$values.")")or die(mysql_error());

Wrote that blind, it should work


try something like:

for($x=0; $x<count($arrayJson); $x++){
    $sql = "Insert into TABLENAME (field1, field2) VALUES (".$arrayJson[$]['categoryID'].", '".$arrayJson[$]['category']."')";
}

That is assumming you know both your Json structure and the DB one.


Array is because it's an array. You have to put there something like

$decoded = json_decode($json);
$query = "INSERT INTO something VALUES ('".mysql_real_escape_string($json[0]['categoryID'])."','".mysql_real_escape_string($json[0]['category'])."','".mysql_real_escape_string($json[0]['subcategory'])."','".mysql_real_escape_string($json[0]['subcategoryID'])."')";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜