Java 当我在浏览器上测试时,php必填字段丢失,因为它们显示了该消息

Java 当我在浏览器上测试时,php必填字段丢失,因为它们显示了该消息,java,php,android,json,Java,Php,Android,Json,当我在web浏览器中测试我的PHP文件时,我得到消息 {“成功”:0,“消息”:“缺少必需字段”} 我正在尝试将android应用程序中的数据添加到本地主机上的数据库中,但不知道缺少的必填字段可能是什么 我的php脚本是: <?php /* * Following code will create a new product row * All product details are read from HTTP Post Request */ // array for JSON

当我在web浏览器中测试我的PHP文件时,我得到消息

{“成功”:0,“消息”:“缺少必需字段”}

我正在尝试将android应用程序中的数据添加到本地主机上的数据库中,但不知道缺少的必填字段可能是什么

我的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($_POST['date']) && isset($_POST['time']) ) {

    $date = $_POST['date'];
    $time = $_POST['time'];


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

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


    // mysql inserting a new row
    $result = mysql_query("INSERT INTO datatime(date,time) VALUES('$date', '$time')");

    // check if row inserted or not
    if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "sit created.";
    $response["id"] = mysql_insert_id("SELECT id FROM sits ORDER BY id DESC LIMIT 1");
    // 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);
}


?>

一件事可能是,您可能发出一个GET请求,但在PHP脚本中,您使用的是$\u POST数组,它只有在发出POST请求时才具有有效数据


由于要同时使用GET和POST方法,请在PHP脚本中使用$\u REQUEST。因此,get和POST请求都适用

一件事可能是,您可能发出一个GET请求,但在PHP脚本中,您使用的是$\u POST数组,它只有在发出POST请求时才具有有效数据


由于要同时使用GET和POST方法,请在PHP脚本中使用$\u REQUEST。因此,get和POST请求都适用

$response[“message”]=“缺少必填字段”。这是你自己的信息。你自己的代码。当。
if(isset($\u POST['date'])和&isset($\u POST['time'])为false时执行。因此,缺少的字段是post数组中的日期和时间。好啊现在又轮到你了。你发布了太多不相关的代码。Php脚本、AsyncTask类以及如何调用AsyncTask就足够了。请删除。请给我一个解决方案。我是这个领域的新手。你对我说的话没有反应。我告诉过你一些事情,你明白我说的吗?我可以插入日期和时间,它们显示错误“json解析器错误字符串无法转换为json对象”值
$response[“message”]=“缺少必需字段”。这是你自己的信息。你自己的代码。当。
if(isset($\u POST['date'])和&isset($\u POST['time'])为false时执行。因此,缺少的字段是post数组中的日期和时间。好啊现在又轮到你了。你发布了太多不相关的代码。Php脚本、AsyncTask类以及如何调用AsyncTask就足够了。请删除。请给我一个解决方案。我是这个领域的新手。你对我说的话没有反应。我告诉过你一些事情,你明白我说的吗?我可以插入日期和时间,它们显示错误“json解析器错误字符串无法转换为json对象”值
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;


public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            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();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

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

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class MainActivity extends Activity implements
        OnClickListener {

    // Widget GUI
    //Button btnCalendar, btnTimePicker;
    EditText txtDate, txtTime;
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    // Variable for storing current date and time
    private int mYear, mMonth, mDay, mHour, mMinute;
    private static String url_create_product = "http://xxx.yyy.z.xxx/datetimejson/datetime.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";



    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtDate = (EditText) findViewById(R.id.txtDate);
        txtTime = (EditText) findViewById(R.id.txtTime);

        txtDate.setFocusable(false);
        txtDate.setClickable(true);
        txtTime.setFocusable(false);
        txtTime.setClickable(true);
        txtDate.setOnClickListener(this);
        txtTime.setOnClickListener(this);
        Button btnCreateProduct = (Button) findViewById(R.id.set);

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

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

    }
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if(pDialog.isShowing())
            pDialog.dismiss();
    }

    @Override
    public void onClick(View v) {

        if (v == txtDate) {

            // Process to get Current Date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);

            // Launch Date Picker Dialog
            DatePickerDialog dpd = new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {
                            // Display Selected date in textbox
                            txtDate.setText(dayOfMonth + "-"
                                    + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
            dpd.show();
        }
        if (v == txtTime) {

            // Process to get Current Time
            final Calendar c = Calendar.getInstance();
            mHour = c.get(Calendar.HOUR_OF_DAY);
            mMinute = c.get(Calendar.MINUTE);

            // Launch Time Picker Dialog
            TimePickerDialog tpd = new TimePickerDialog(this,
                    new TimePickerDialog.OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay,
                                int minute) {
                            // Display Selected time in textbox
                            txtTime.setText(hourOfDay + ":" + minute);
                        }
                    }, mHour, mMinute, false);
            tpd.show();
        }
    }

class CreateNewProduct extends AsyncTask<String, String, String> {

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

    /**
     * Creating product
     * */
    protected String doInBackground(String... args) {
         String date = txtDate.getText().toString();
         String time = txtTime.getText().toString();


        // Building Parameters
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("date", date));
        params.add(new BasicNameValuePair("time", time));

        Log.d("request!", "starting");

        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);


        Log.d("Post Update", json.toString());


        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
                 Log.d("Updated!", json.toString());
                 Intent i = new Intent(getApplicationContext(), DailogBox.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();
    }

}
}