PHP接收json 并将接收数据插入数据库的实现代码

yipeiwu_com6年前PHP代码库

最近有一个需求,前端向后台提交json,后台解析并且将提交的值插入数据库中,
难点
1、php解析json(这个不算难点了,网上实例一抓一大把)
2、解析json后,php怎样拿到该拿的值

<?php
require ('connect.php');
/*
本例用到的数据:
post_array={"order_id":"0022015112305010013","buyer_id":"2","seller_id":"1","all_price":"100.00","json_list":[{"product_id":"3","product_number":"3"},{"product_id":"8","product_number":"2"},{"product_id":"10","product_number":"4"}]} 
*/
$post_array=$_POST['post_array'];

//--解析Json,获取对应的变量值
$obj=json_decode($post_array,TRUE);
$order_id = $obj['order_id'];
$buyer_id = $obj['buyer_id'];
$seller_id = $obj['seller_id'];
$all_price = $obj['all_price'];

$i=0;//循环变量

//--得到Json_list数组长度
$num=count($obj["json_list"]);

//--遍历数组,将对应信息添加入数据库
for ($i;$i<$num;$i++)
{
	$list_product_id[]=$obj["json_list"][$i]["product_id"];
	$list_product_number[]=$obj["json_list"][$i]["product_number"];
	$insert_order_product_sql="INSERT INTO tbl_order_product (order_id,product_id,product_number) VALUES (?,?,?)";
	$result = $sqlconn -> prepare($insert_order_product_sql);
	$result -> bind_param("sss", $order_id,$list_product_id[$i],$list_product_number[$i]);
	$result->execute();
}

//--添加订单信息
$insert_order_sql="INSERT INTO tbl_order (order_id,buyer_id,seller_id,all_price) VALUES (?,?,?,?)";
$result=$sqlconn->prepare($insert_order_sql);
$result->bind_param("ssss",$order_id,$buyer_id,$seller_id,$all_price);
$result->execute();

$result -> close();
$sqlconn -> close();
?>

投稿者信息
昵称: Hola
Email: jamcistos@outlook.com

相关文章

PHP伪静态写法附代码

比如这个网页 //www.jb51.net/soft.php/1,100,8630.html 其实处理的脚本是soft.php 参数为1,100,8630 相当于soft.ph...

php文件下载处理方法分析

本文实例讲述了php文件下载的处理方法。分享给大家供大家参考。具体分析如下: php能够处理多种条件的文件下载,先来看下面示例: <?php header("Conte...

讲解WordPress中用于获取评论模板和搜索表单的PHP函数

comments_template()(获取评论模板) comments_template() 函数用来获取评论模板,一般只能用在文章或者页面上,如果不是文章或者页面将无法显示。 用法...

解析PHP生成静态html文件的三种方法

本文将介绍Php 生成静态html文件的三种方法 。1,下面使用模版的一个方法!复制代码 代码如下:<?php $fp = fopen ("templets.html","a");...

深入理解PHP中的global

一、实现原理 在PHP的函数中,global语法是比较常见的,大家一定都知道一旦在函数中global了某个外部变量后,这个变量就可以在这个函数中使用了,但是也有不少网友不知道这是一个什么...