[英]How to Properly Insert Decoded JSON to Mysql Database
Iv been searching the internet on how to make my php code for my database works and i cant understand any of it!我一直在互联网上搜索如何使我的数据库的 php 代码正常工作,但我无法理解! thats why i have no choice but to just ask a question i hope someone can help me or guide me on this matter.
这就是为什么我别无选择,只能问一个问题,我希望有人能在这件事上帮助我或指导我。 Any help is very much appreciated!
很感谢任何形式的帮助!
Question: I want to insert a JSON format data to mysql database.问题:我想插入一个JSON格式的数据到mysql数据库。
String Request Code in Android Android 中的字符串请求代码
public void insertCartProducttoDatabase() {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.cartdata_url,
new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.getBoolean("error")) {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("response", "" + error);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_VC_ARRAY, convertedArray);
//params.put(KEY_VC_BRANCH, branchid);
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
logcat Result: This is the array result comming from my recycler view logcat 结果:这是来自我的回收站视图的数组结果
[
{
"productname": "Siopao",
"quantity": "3",
"totalprice": 1500
},
{
"productname": "Siomai",
"quantity": "3",
"totalprice": 297
},
{
"productname": "Burger",
"quantity": "4",
"totalprice": 200
}
]
PHP CODE DB Operations.php (UPDATEDv2) PHP 代码 DB Operations.php (UPDATEDv2)
//INSERT CART PRODUCTS
public function insertIndividualCart($cartarray){
$receivedArray = $_POST['cartarray'];
$new_array = json_decode($receivedArray,true);
var_dump($new_array);
$stmt = $this->con->prepare("INSERT INTO `cart_data` (`cartid`, `productname`, `quantity`, `totalprice`, `created`)
VALUES (NULL, ?, ?, ?, CURRENT_TIMESTAMP )");
foreach($new_array as $row){
$stmt->bind_param('ssi', $row['productname'], $row['quantity'], $row['totalprice']);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
PHP CODE cartData.php PHP代码cartData.php
<?php
require_once '../DbOperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(
isset($_POST['cartarray'])
){
//operations data
$db = new DbOperations();
$result = $db->insertIndividualCart(
$_POST['cartarray']
);
if($result == 1){
$response['error'] = false;
$response['message'] = "Success";
}elseif($result == 2){
$response['error'] = true;
$response['message'] = "Failed, Error Occured";
}
}else{
$response['error'] = true;
$response['message'] = "Required Field are missing";
}
}else{
$response['error'] = true;
$response['message'] = "Invalid Request";
}
echo json_encode($response);
I know my php code Dboperation.php is wrong.我知道我的 php 代码 Dboperation.php 是错误的。 its just i dont know how to start i saw a video, that i have to decode first my array comming from android and then use foreach and inside use Insert, What i cant understand is that how can i use bind params on the array that i just decoded?
只是我不知道如何开始,我看到了一个视频,我必须首先解码来自 android 的数组,然后使用 foreach 并在内部使用 Insert,我无法理解的是我如何在我的数组上使用绑定参数刚刚解码? or do i need to?
或者我需要吗? cause what i understand is in order for my code to work i need to use bind params depending on the paramter that i used on public function right?
因为我的理解是为了让我的代码正常工作,我需要根据我在公共函数中使用的参数来使用绑定参数,对吗? (idk what its called what i mean by public function is like this one " public function insertIndividualCart($cartarray){} " ) im just a beginner guys so go easy on me!
(我知道它叫什么,我所说的公共函数就像这样一个“公共函数 insertIndividualCart($cartarray){}”)我只是一个初学者,所以对我放轻松! i just dont have any choice but to just ask since i really cant understand the things that they did in their post.
我只是别无选择,只能问,因为我真的无法理解他们在帖子中所做的事情。
This is not a full answer, but it should give you an idea where you have gone wrong.这不是一个完整的答案,但它应该让你知道你哪里出错了。 You need to execute the query inside a loop.
您需要在循环内执行查询。
public function insertIndividualCart($cartarray)
{
$new_array = json_decode($cartarray, true);
$stmt = $this->con->prepare("INSERT INTO `cart_data` (`cartid`, `productname`, `quantity`, `totalprice`, `created`)
VALUES (NULL, ?, ?, ?, CURRENT_TIMESTAMP)");
foreach ($new_array as $row) {
// you have 3 placeholders in SQL, so you need 3 variables bound
$stmt->bind_param('sss', $row['productname'], $row['quantity'], $row['totalprice']);
$stmt->execute();
}
return true;
}
See how much shorter it is?看看它短了多少? Prepare the query before the loop and then bind values inside the loop and execute
在循环之前准备查询,然后在循环内绑定值并执行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.