Home  >  Article  >  Backend Development  >  PHP receives json and inserts the received data into the database implementation code_php skills

PHP receives json and inserts the received data into the database implementation code_php skills

WBOY
WBOYOriginal
2016-05-16 20:03:541005browse

There is a requirement recently. The front end submits json to the background, and the background parses and inserts the submitted value into the database.
Difficulty
1. PHP parses json (this is not difficult, there are a lot of examples online)
2. After parsing json, how does php get the value it should get

<&#63;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 (&#63;,&#63;,&#63;)";
	$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 (&#63;,&#63;,&#63;,&#63;)";
$result=$sqlconn->prepare($insert_order_sql);
$result->bind_param("ssss",$order_id,$buyer_id,$seller_id,$all_price);
$result->execute();

$result -> close();
$sqlconn -> close();
&#63;>

Contributor information
Nickname: Hola
Email: jamcistos@outlook.com

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn