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的时间戳与具体时间转化的简单实现

三个内置函数: time() //获取UNIX系统时间戳 mktime(hour,minute,second,month,day,year) //将指定时间转化为时间戳 d...

php检查页面是否被百度收录

最近需要检测网站内哪些页面没有被百度搜索引擎收录从而进行相关的调整。由于使用site命令一条条的去看实在是看不过来,就想到了使用php程序来批量处理一下,研究了一下,发现其实很简单,下面...

jQuery+php实现ajax文件即时上传的详解

jQuery+php实现ajax文件即时上传的详解

很多项目中需要用到即时上传功能,比如,选择本地图片后,立即上传并显示图像。本文结合实例讲解如何使用jQuery和PHP实现Ajax即时上传文件的功能,用户只需选择本地图片确定后即实现上传...

php htmlspecialchars()与shtmlspecialchars()函数的深入分析

定义和用法htmlspecialchars() 函数把一些预定义的字符转换为 HTML 实体。 预定义的字符是:•& (和号) 成为 &•" (双引号)...

php 多线程上下文中安全写文件实现代码

复制代码 代码如下: <?php /** * @usage: used to offer safe file write operation in multiple threads...