2016-02-24 23 views
1

當我測試的Web瀏覽器我得到的消息我的PHP文件...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); 
} 


?> 

我的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; 

    } 
} 

我呼籲我的PHP文件

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(); 
    } 

} 
} 

我一直堅持這個問題幾天,現在請幫助我。

+0

'$ response [「message」] =「必填字段丟失」;'。這是你自己的信息。你自己的代碼。當它被執行時.'if(isset($ _ POST ['date'])&& isset($ _ POST ['time']))'爲false。所以缺少的字段是日期和時間在數組中。好?現在輪到你了。 – greenapps

+0

你發佈了太多不相關的代碼。 Php腳本,AsyncTask類以及如何調用AsyncTask就足夠了。請刪除。 – greenapps

+0

請給我一個解決方案,我在這個領域是新的。 – vai

回答

0

有一件事可能是您可能正在發出GET請求,但在PHP腳本中您使用的是$ _POST數組,只有當它是POST請求時纔會有有效的數據。

因爲您想要同時使用GET和POST方法,請在PHP腳本中使用$ _REQUEST。因此將適用於get和POST請求。