将JSON解析为mySQL [英] Parse JSON to mySQL

查看:112
本文介绍了将JSON解析为mySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的PHP脚本JSON字符串中获取如下所示(包含任何对象的数组):

A get in my PHP script JSON string that looks like this (array with any objects):

[
    {
        "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"
    }
]

我如何使用MySQL中的记录将每个JSON对象保存在该数组中?

How i can save each JSON object in this array with a record in mySQL?

推荐答案

尝试一下:

<?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)进行数据库操作. 在此处

Note: But it is recommended to use PHP Data Objects(PDO) to do database operations. Check here

这篇关于将JSON解析为mySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆