将 ArrayList 从 android 发送到 php MySQL [英] Send ArrayList from android to php MySQL
问题描述
在表 work_details
中,我有 7 列 (id、project、work_description、百分比、time_in、time_out、fk)
.现在我想将 arraylist
和 fk
保存到表中.
In table work_details
, I have 7 column (id, project, work_description, percentage, time_in, time_out, fk)
. Now I want to save the arraylist
and fk
to the table.
我尝试过编码,但我知道这不是正确的方法.
I have tried to code but I know this is not the correct way.
public void addWorkDetails(ArrayList<SearchResults> listItems, long id)
{
JSONObject object= new JSONObject();
for(int i=0;i<listItems.size();i++)
{
try
{
object.put("Count : "+String.valueOf(i + 1),listItems.get(i));
}catch(JSONException e)
{
e.printStackTrace();
}
}
class AddWorkDetails extends AsyncTask<String, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(WorkDetailsTable.this, "Please Wait",null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
// what should I put here ?
RequestHandler rh=new RequestHandler();
String result = rh.sendPostRequest(Config.ADD_WORKDETAILS,data);
return result;
}
}
AddWorkDetails ru = new AddWorkDetails();
ru.execute(listItems,id);
}
PHP
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$list[]=$_POST['listItems'];
$id=$_POST['id'];
foreach($list as $value){
$value=mysqli_real_escape_string($val);
$sql="INSERT INTO work_details (project, work_description, percentage, timeIn, timeOut, id) VALUES ('$val', '$id')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo ' Added Successfully';
}else{
echo 'Could Not Add Data';
}
//Closing the database
mysqli_close($con);
}
?>
注意 listItems 包含 project,work_description,percentage,time_in 和 time_out
.
推荐答案
您的 SQL 查询不正确:
Your SQL query is incorrect:
$sql="INSERT INTO work_details (project, work_description, percentage, timeIn, timeOut, id) VALUES ('$val', '$id')";
您有 6 列要设置并且只提供 2 个值.
You have 6 columns to set and provide only 2 values.
与其迭代 $list
并为每个值执行查询,您应该在迭代时构造查询,并在完成时只在最后执行一次.示例:
Instead of iterating over $list
and executing a query for each value, you should rather construct the query while iterating and execute it only once at the end when it is complete. Example:
foreach (...) {
$sql = $sql . "'$val', ";
...
}
$sql = "INSERT INTO work_details (project, work_description, percentage, timeIn, timeOut, id) VALUES (" . $sql . "'$id')";
这只是想法.. 我不是 PHP 人,所以我写的东西有可能存在错误.
This is just the idea.. I'm not a PHP guy so there's probaby errors in what I wrote.
EDIT :这假设列表中的顺序始终相同.
EDIT : This assumes that order is always the same in the list.
这篇关于将 ArrayList 从 android 发送到 php MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!