2012-06-13 4 views
0

Я работаю над приложением, которое хранит пользовательские входы в таблицу базы данных через PHP API, но я получаю сообщение об ошибке из кода PHP в LogCat. Любые советы будут очень признательны.Не удается сохранить данные в базе данных

D/Create Response(284): {"message":"Required field(s) is missing","success":0} 

PHP API

<?php 
// array for JSON response 
$response = array(); 

// check for the fields 
if (isset($_POST['title']) && isset($_POST['request_date']) && isset($_POST['reqEndDate']) && isset($_POST['reason']) && isset($_POST['requestor']) && isset($_POST['status']) && isset($_POST['submitDate']) && isset($_POST['explanation']) && isset($_POST['hours']) && isset($_POST['id'])) { 

    $title = $_POST["request_title"]; 
    $date = $_POST["request_date"]; 
    $eDate = $_POST["reqEndDate"]; 
    $reason = $_POST["reason"]; 
    $requestor = $_POST["requestor"]; 
    $status = $_POST["status"]; 
    $dateSubmitted = $_POST["submitDate"]; 
    $explanation = $_POST["explanation"]; 
    $numhours = $_POST["hours"]; 
    $id = $_POST['id']; 


    // mysql inserting a new row 
    $result = mysql_query("INSERT INTO requests(request_title, request_date, reqEndDate, reason, requestor, status, submitDate, explanation, hours, empid) 
          VALUES('$title', '$date', '$eDate', '$reason', '$requestor', '$status', '$dateSubmitted', '$explanation', '$numhours', '$id')"); 


?> 

JAVA CLASS

// url to the PHP API to create new request 
    private static String url_create_request = "http://mywebsite.com/create_request.php"; 

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

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.add_request); 

     // Edit Text 
     inputTitle = (EditText) findViewById(R.id.inputTitle); 
     inputSdate = (EditText) findViewById(R.id.inputSdate); 
     inputEdate = (EditText) findViewById(R.id.inputEdate); 
     inputHours = (EditText) findViewById(R.id.inputHours); 
     inputReason = (EditText) findViewById(R.id.inputReason); 
     inputExp = (EditText) findViewById(R.id.inputExp); 

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

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

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


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

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(NewRequestActivity.this); 
      pDialog.setMessage("Creating Request.."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 

     /** 
     * Creating Request Required Fields 
     * */ 
     protected String doInBackground(String... args) { 
      String title = inputTitle.getText().toString(); 
      String date = inputSdate.getText().toString(); 
      String eDate = inputEdate.getText().toString(); 
      String hours = inputHours.getText().toString(); 
      String reason = inputReason.getText().toString(); 
      String explanation = inputExp.getText().toString(); 

      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("request_title", title)); 
      params.add(new BasicNameValuePair("request_date", date)); 
      params.add(new BasicNameValuePair("reqEndDate", eDate)); 
      params.add(new BasicNameValuePair("hours", hours)); 
      params.add(new BasicNameValuePair("reason", reason)); 
      params.add(new BasicNameValuePair("explanation", explanation)); 

      // getting JSON Object 
      // Note that create request url accepts POST method 
      JSONObject json = jsonParser.makeHttpRequest(url_create_request, 
        "POST", params); 

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

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

       if (success == 1) { 
        // successfully created request 
        Intent i = new Intent(getApplicationContext(), AllRequestsActivity.class); 
        startActivity(i); 

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

      return null; 
     } 

     protected void onPostExecute(String file_url) { 
      // dismiss the dialog once done 
      pDialog.dismiss(); 
     } 

    } 
} 
+0

Ваше определение базы данных не согласуется с инструкцией вставки. У вас есть 'empid' в одном, но не в другом, и то же самое для' userid' и, возможно, других. –

+1

Кроме того, это поможет показать реальное определение таблицы базы данных с помощью типов и всего. В частности, будет ли какое-либо из полей «разрешено null» и будет ли «request_id» автоинкрементным или каким-либо другим. –

+0

спасибо, Пол! – tvdog

ответ

2

Просто подсчет ваших БД столбцов: там, кажется, 12 из них. Вы только вставляете в 11, и после процесса устранения, похоже, что вы упускаете «активный», который, если он не имеет значения по умолчанию или может быть нулевым, будет выдавать «Требуемое поле (поля)) «ошибка, которую вы получаете при попытке вставить в БД.

Смежные вопросы