通过PHP脚本在Android中将数据插入MySQL出错

时间:2016-12-14 06:01:43

标签: php android mysql

我想将ListView中的数据插入MySQL,但列的插入值出错了,

详情:

我有这样的布局:

|--------------------|
|<id> TextView       |
| * * *              |
|--------------------|
|<id> TextView       |
| * * * *            |
|--------------------|
|<id> TextView       |
| * * * * *          |
|--------------------|

然后我要插入的数据库列看起来像:

|----|-------|
| ID | Nilai |
|----|-------|
| 1  |   3   |
| 2  |   4   |
| 3  |   5   |
|====|=======|

但是为什么当按下按钮时插入的数据是错误的?所有id column值都是&#34; 0&#34;,而nilai column是不明确的

我做错了吗?

我用来插入的代码是:

Button onClick :

int size = adapter3.getCount();
StringBuilder b = new StringBuilder();
JSONArray jArray = new JSONArray();
for (int i=0;i<size;i++){
    id = String.valueOf(adapter3.getItem(i).getId());
    nilai = String.valueOf(adapter3.getItem(i).getRatingStar());
    new PostDataTOServer().execute();
}

PostDataTOServer class :

protected Void doInBackground(Void... arg0) {
postDataParams= new HashMap<>();
postDataParams.put("id", id);
postDataParams.put("nilai", nilai);
String path = "<MY URL>";
response= service.ServerData(path,postDataParams);
    try {
        JSONObject json = new JSONObject(response);
        //Get Values from JSONobject
        System.out.println("success=" + json.get("success"));
        success = json.getInt("success");

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

insert2.php

<?php
include 'dbconfig.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}
$id=$_POST["id"];
$nilai=$_POST["nilai"];

$success=0;
$sql = "INSERT INTO  nilai_3 (id, nilai) 
VALUES ('$id','$nilai')";

if(mysqli_query($con, $sql))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysql_close($con);
?>

0 个答案:

没有答案