JSONParser不更新MySQL数据库

时间:2012-07-22 15:13:10

标签: php android mysql

我有一个包含MySQL数据库值的列表。这些值随列表一起传输,但是当我查看我的变量时(在调试模式下)。我看到只有旧值被发送到PHP文件而不是“更新”值。

在这里,我得到了“喜欢”的旧价值:

  protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                // Check for success tag
                int success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("id", cid));

                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jParser.makeHttpRequest(url_details, "GET", params);

                    // check your log for json response
                    Log.d("Details Song", json.toString());

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received product details
                        JSONArray chartsObj = json.getJSONArray(TAG_CHARTS); // JSON Array

                        // get first product object from JSON Array
                        JSONObject charts = chartsObj.getJSONObject(0);

                        // product with this id found
                        // Edit Text
                        txtInterpret = (TextView)findViewById(R.id.tblInterpret);
                        txtTitel = (TextView)findViewById(R.id.tblTitel);
                        txtAlbum = (TextView)findViewById(R.id.tblAlbum);
                        txtLikes = (TextView)findViewById(R.id.like);
                        thumb_image = (ImageView)findViewById(R.id.albumcover); 

                        imageLoader = new ImageLoader(getApplicationContext());
                        imageLoader.DisplayImage(charts.getString(TAG_ALBUMCOVER), thumb_image);
                        txtInterpret.setText(charts.getString(TAG_INTERPRET));
                        txtTitel.setText(charts.getString(TAG_TITEL));
                        txtAlbum.setText(charts.getString(TAG_ALBUM));
                        txtLikes.setText(Integer.toString(charts.getInt(TAG_LIKES)));
                        likes = charts.getInt(TAG_LIKES);

                    }else{
                        // product with id not found
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }

此功能在我的OnCreate功能中。当你点击一个按钮时,你应该将int值增加一个!

        like.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                System.out.println("Vorher: " +likes);
                likes = (likes++);
                System.out.println("Nachher: " +likes);
                new Like().execute();
            }
        });

这是我的清单中的功能。

protected String doInBackground(String... args) {

         List<NameValuePair> params = new ArrayList<NameValuePair>();
         params.add(new BasicNameValuePair("id", cid));
         params.add(new BasicNameValuePair(TAG_LIKES, Integer.toString(likes)));

    // getting JSON Object
    // Note that create product url accepts POST method
         JSONObject json = jParser.makeHttpRequest(url_like,"POST", params);

    // check log cat for response
    Log.d("Create Response", json.toString());

    return null;
    }

这是我的JSONParser:

if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            json = EntityUtils.toString(httpEntity, HTTP.UTF_8);
            System.out.println("JSON: " + json);

最后是我的PHP文件:

<?php

/*
 * Following code will update a product information
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['likes']) && isset($_POST['id'])) {

$id = $_POST['id'];
$likes = $_POST['likes'];

// include db connect class
require_once (connection);

// connecting to db
$db = new DB_CONNECT();

// mysql update row with matched pid
$result = mysql_query("UPDATE Charts SET likes = '$likes' WHERE id = '$id'");

// check if row inserted or not
if ($result) {
    // successfully updated
    $response["success"] = 1;
    $response["message"] = "Like erfolgreich";

    // echoing JSON response
    echo json_encode($response);
} else {

}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Ein Fehler ist aufgetreten";

// echoing JSON response
echo json_encode($response);
}
?>

2 个答案:

答案 0 :(得分:1)

你很容易被SQL injection attacks攻击,并且几乎可以保证JSON文本将包含两个或多个'字符,“破坏”你的sql查询。实质上,您正在注入自己的SQL查询。

您的查询也没有错误处理,并假设它们成功了。这真是太糟了。即使您的SQL语法100%完美,但是查询无法检查错误还有太多其他原因:

至少,你应该

$safe_json = mysql_real_escape_string($_POST['likes']);
$sql = "UPDATE .... WHERE likes='$safe_json' ...";
$result = mysql_query($sql) or die(mysql_error());

作为一般提示,自PHP 5.4起,mysql_*()函数已被弃用。您应该考虑切换到mysqli,或者最好是PDO

答案 1 :(得分:1)

首先, JSONParser 中的if条件从未执行过,因为,

你的if条件应该是,

if(method.equals("POST"))

不是,

if(method == "POST")

第二个,

此外,不是在doInBackground()中使用runOnUiThread,而是将您的UI更新代码放在AsyncTask的onPostExecute()方法中。