2012-06-29 86 views
1

一大家子在我的PHP腳本的JSON字符串,看起來像這樣(陣列用任何物體):解析JSON到MySQL

[ 
    { 
     "source":"symbols/2/2.png", 
     "ypos":133, 
     "template":"8B82CA47-41D2-D624-D6A2-37177CD82F28", 
     "rotation":0, 
     "type":"MyImage", 
     "width":252, 
     "depth":5, 
     "height":159, 
     "xpos":581 
    }, 
    { 
     "source":"symbols/2/2.png", 
     "ypos":175, 
     "template":"8B82CA47-41D2-D624-D6A2-37177CD82F28", 
     "rotation":0, 
     "type":"MyImage", 
     "width":258, 
     "depth":3, 
     "height":163, 
     "xpos":214 
    }, 
    { 
     "color":"0", 
     "ypos":468.38, 
     "fontSize":28, 
     "xpos":156.95, 
     "rotation":0, 
     "type":"MyTextArea", 
     "width":268.05, 
     "depth":7, 
     "height":244.62, 
     "fontFamily":"Verdana Bold", 
     "template":"8B82CA47-41D2-D624-D6A2-37177CD82F28" 
    } 
] 

我怎麼能在這個數組中保存每個JSON對象與MySQL中的記錄?

+0

@Astraport檢查答案:-) – Vimalnath

+0

我以爲我只是在別的地方回答這個問題 – zinking

回答

6

試試這個插入語句:

<?php 
$json = '[ 
    { 
     "source":"symbols/2/2.png", 
     "ypos":133, 
     "template":"8B82CA47-41D2-D624-D6A2-37177CD82F28", 
     "rotation":0, 
     "type":"MyImage", 
     "width":252, 
     "depth":5, 
     "height":159, 
     "xpos":581 
    }, 
    { 
     "source":"symbols/2/2.png", 
     "ypos":175, 
     "template":"8B82CA47-41D2-D624-D6A2-37177CD82F28", 
     "rotation":0, 
     "type":"MyImage", 
     "width":258, 
     "depth":3, 
     "height":163, 
     "xpos":214 
    }, 
    { 
     "color":"0", 
     "ypos":468.38, 
     "fontSize":28, 
     "xpos":156.95, 
     "rotation":0, 
     "type":"MyTextArea", 
     "width":268.05, 
     "depth":7, 
     "height":244.62, 
     "fontFamily":"Verdana Bold", 
     "template":"8B82CA47-41D2-D624-D6A2-37177CD82F28" 
    } 
]'; 
//create a DB connection 
con = mysql_connect("localhost","username","password"); 
mysql_connect _db('your_database',$con); 


$result = json_decode($json); 
foreach($result as $key => $value) { 
    if($value) { 

      //how to use json array to insert data in Database 
     mysql_query("INSERT INTO tablename (source, ypos, template) VALUES ($value->source, $value->ypos,$value->template)"); 
    } 
    mysql_close($con); 
} 

注:但建議使用PHP數據對象(PDO)做數據庫操作。 檢查here

+0

謝謝vimalnath。代碼有小錯誤,但這正是我所期待的。 – Astraport

1

使用json_decode,然後建立基於陣列的值