php - 从android问题更新数据库

标签 php android mysql

我做了这个教程。 here

最终解决了很多问题。但仍然无法创建新项目。我通过将参数传递给 url 检查了 .php 文件,它工作正常。但来自安卓应用

jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

结果不成功,success=0 是我的结果。

这是我的 Activity :

import android.app.Activity;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewProductActivity extends Activity{

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputPrice;
    EditText inputDesc;

    // url to create new product
    private static String url_create_product = "http://192.168.19.101:81/android/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);

        //StrictMode.enableDefaults();

        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputPrice = (EditText) findViewById(R.id.inputPrice);
        inputDesc = (EditText) findViewById(R.id.inputDesc);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String price = inputPrice.getText().toString();
            String description = inputDesc.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("description", description));

            // getting JSON Object
            // Note that create product url accepts POST method
            Log.i("WEB", "c1");
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);
            Log.i("WEB", "c2");
            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);
                Log.i("WEB", "c success="+success);
                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}

这是 php 文件:

<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

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

// check for required fields
if (isset($_GET['name']) && isset($_GET['price']) && isset($_GET['description'])) {

    $name = $_GET['name'];
    $price = $_GET['price'];
    $description = $_GET['description'];

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

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

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

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

这是 logcat:

01-28 12:41:18.046: D/ProgressBar(28763): setProgress = 0
01-28 12:41:18.046: D/ProgressBar(28763): setProgress = 0, fromUser = false
01-28 12:41:18.046: D/ProgressBar(28763): mProgress = 0mIndeterminate = false, mMin = 0, mMax = 10000
01-28 12:41:18.136: I/WEB(28763): c1
01-28 12:41:18.156: D/ProgressBar(28763): updateDrawableBounds: left = 0
01-28 12:41:18.156: D/ProgressBar(28763): updateDrawableBounds: top = 0
01-28 12:41:18.156: D/ProgressBar(28763): updateDrawableBounds: right = 96
01-28 12:41:18.156: D/ProgressBar(28763): updateDrawableBounds: bottom = 96
01-28 12:41:18.236: D/dalvikvm(28763): GC_FOR_ALLOC freed 367K, 39% free 12037K/19624K, paused 31ms, total 31ms
01-28 12:41:18.266: I/WEB(28763): c2
01-28 12:41:18.266: D/Create Response(28763): {"message":"Required field(s) is missing","success":0}
01-28 12:41:18.266: I/WEB(28763): c success=0
01-28 12:41:18.286: E/ViewRootImpl(28763): sendUserActionEvent() mView == null

最佳答案

试试这个,在所有出现的 php 代码中使用 $_POST 而不是 $_GET

由于您使用了 jsonParser.makeHttpRequest(url_create_product, "POST", params);

if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {

代替

if (isset($_GET['name']) && isset($_GET['price']) && isset($_GET['description'])) {

关于php - 从android问题更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21401332/

相关文章:

php - MyClass::class - 获取 MyClass 的字符串表示

php - 嵌套循环中 continue 2 和 break 之间的区别

PHP:如何在给定日期输入的情况下获得星期日和星期六?

php - .htaccess 将子域重定向到目录

android - 为什么 Android Chrome 从 61.0.3163.98 更新到 72.0.3626.76 会破坏 Chrome 自定义选项卡中的 OAuth 登录?

c# - 具有两个主键时的 FluentNhibernate 映射

php - MYSQL左连接A.table和b.table,同时保留a.table id

android - 如何防止为已回收的 View 生成不必要的工作线程?

android - 如何在 Android 应用程序中集成 Twitter

php - 摆脱 php 或 mysql 中的多个空格