This article mainly introduces PHP's implementation code for receiving json data and inserting the received data into the database. For more information, see
This article mainly introduces PHP's implementation code for receiving json data and inserting the received data into the database. For more information, see
There is a demand recently. The front-end submits json to the background, parses the background, and inserts the submitted value into the database,
Difficulties
1. parse json in php (this is not a difficult issue. When an online Instance tries to parse the volume)
2. After parsing json, how does php get the value?
<? Phprequire ('connect. php ');/* data used in this example: 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']; // -- parse Json, get the corresponding variable value $ obj = json_decode ($ post_array, TRUE); $ order_id = $ obj ['order _ id']; $ buyer_id = $ Obj ['bucket _ id']; $ seller_id = $ obj ['seller _ id']; $ all_price = $ obj ['all _ price']; $ I = 0; // loop variable // -- get the Json_list array length $ num = count ($ obj ["json_list"]); // -- traverse the array, add the corresponding information to the database 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 ();} // -- add order information $ 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 ();?>
Contributor Information
Nickname: Hola
Email: jamcistos@outlook.com