繁体   English   中英

Android Web服务PHP MYSQL

[英]Android WebServices PHP MYSQL

我正在尝试通过Webservices将学生数据从我的Android应用程序保存到MYSQL数据库。 但是问题在于它不是在数据库上保存数据。.Php文件的编程方式是将JSON显示为输出

$response["success"] = 1;
        $response["message"] = "Student record has been saved successfully";

其他

 $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

PHP文件在应用程序中返回“糟糕!发生错误”。

我用于创建新记录的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['rollno']) && isset($_POST['sname']) && isset($_POST['regid']) &&isset($_POST['class'])&& isset($_POST['fname'])&& isset($_POST['fno'])&& isset($_POST['mname'])&& isset($_POST['mno'])&& isset($_POST['route'])&& isset($_POST['timings'])&& isset($_POST['latitude'])&& isset($_POST['longitude'])) {

    $rollno = $_POST['rollno'];
    $sname = $_POST['sname'];
 $regid = $_POST['regid'];
    $class = $_POST['class'];
     $fname = $_POST['fname'];
      $fno = $_POST['fno'];
       $mname = $_POST['mname'];
  $mno = $_POST['mno'];
   $route = $_POST['route'];
    $timings = $_POST['timings'];
     $latitude = $_POST['latitude'];
      $longitude = $_POST['longitude'];
    // include db connect class
  require_once('/home/a9447544/public_html/school/db_connect.php');

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

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO school(rollno, sname,regid, class, fname, fno, mname, mno, route, timings, latitude, longitude) VALUES('$rollno', '$sname','$regid', '$class', '$fname', '$fno', '$mname', '$mno', '$route', '$timings', '$latitude', '$longitude')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Student record has been saved successfully";

        // 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);
}
?>

用于创建新记录的Android Java文件。

package com.example.akshay.productdata;

/**
 * Created by Akshay on 8/9/2015.
 */

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

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

import java.util.ArrayList;
import java.util.List;

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText RollNo, SName, Class, FatherName, FatherNo, MotherName, MotherNo, RouteNo, Timings;
    String ROLLNO, SNAME, ROUTE, FATHERNAME, FATHERNO, MOTHERNAME, MOTHERNO, TIMINGS, CLASS, REGID;
    // url to create new product
    private static String url_create_product = "http://www.funvilla.in/school/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);

        // Edit Text
        RollNo = (EditText) findViewById(R.id.ET_ROLL);
        SName = (EditText) findViewById(R.id.ET_SNAME);
        Class = (EditText) findViewById(R.id.ET_CLASS);
        FatherName = (EditText) findViewById(R.id.ET_FatherName);
        FatherNo = (EditText) findViewById(R.id.ET_FATHERNO);
        MotherName = (EditText) findViewById(R.id.ET_MotherName);
        MotherNo = (EditText) findViewById(R.id.ET_MotherNo);
        RouteNo = (EditText) findViewById(R.id.ET_Route);
        Timings = (EditText) findViewById(R.id.ET_Timings);


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

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

            @TargetApi(Build.VERSION_CODES.CUPCAKE)
            @Override
            public void onClick(View view) {
                // creating new product in background thread
                ROLLNO = RollNo.getText().toString();
                SNAME = SName.getText().toString();
                CLASS = Class.getText().toString();
                FATHERNAME = FatherName.getText().toString();
                FATHERNO = FatherNo.getText().toString();
                MOTHERNAME = MotherName.getText().toString();
                MOTHERNO = MotherNo.getText().toString();
                ROUTE = RouteNo.getText().toString();
                TIMINGS = Timings.getText().toString();
                new CreateNewProduct().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     */
    @TargetApi(Build.VERSION_CODES.CUPCAKE)
    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 LAT = "78.555454";
            String LONG = "78.545545";
            REGID = "jefk3je3eh";
            Log.e("ROLLNO==========", ROLLNO);
            Log.e("SNAME==========", SNAME);
            Log.e("REGID==========", REGID);
            Log.e("CLASS==========", CLASS);
            Log.e("FATHERNAME==========", FATHERNAME);
            Log.e("FATHERNO==========", FATHERNO);
            Log.e("MOTHERNAME==========", MOTHERNAME);
            Log.e("MOTHERNO==========", MOTHERNO);
            Log.e("ROUTE==========", ROUTE);
            Log.e("Timings==========", TIMINGS);
            Log.e("LAT==========", LAT);
            Log.e("LONG==========", LONG);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("rollno", ROLLNO));
            params.add(new BasicNameValuePair("sname", SNAME));
            params.add(new BasicNameValuePair("regid", REGID));
            params.add(new BasicNameValuePair("class", CLASS));
            params.add(new BasicNameValuePair("fname", FATHERNAME));
            params.add(new BasicNameValuePair("fno", FATHERNO));
            params.add(new BasicNameValuePair("mname", MOTHERNAME));
            params.add(new BasicNameValuePair("mno", MOTHERNO));
            params.add(new BasicNameValuePair("route", ROUTE));
            params.add(new BasicNameValuePair("timings", TIMINGS));
            params.add(new BasicNameValuePair("latitude", LAT));
            params.add(new BasicNameValuePair("longitude", LONG));


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

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

            // check for success tag
            try {
                int success = json.getInt(TAG_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();
        }

    }
}

JSONParser.java-用于建立连接以及保存和检索记录

package com.example.akshay.productdata;

/**
 * Created by Akshay on 8/9/2015.
 */


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.os.StrictMode;
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) {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        // 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();
            Log.e("=======" , json);
        } 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;

    }
}

logcat的:

08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/ROLLNO==========﹕ 77
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/SNAME==========﹕ lkskl
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/REGID==========﹕ jefk3je3eh
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/CLASS==========﹕ mmm
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/FATHERNAME==========﹕ sdf
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/FATHERNO==========﹕ 54554
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/MOTHERNAME==========﹕ dfd
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/MOTHERNO==========﹕ 544
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/ROUTE==========﹕ 54
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/Timings==========﹕ 5445
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/LAT==========﹕ 78.555454
08-22 00:39:39.640    7279-7452/com.example.akshay.productdata E/LONG==========﹕ 78.545545
08-22 00:39:40.300    7279-7452/com.example.akshay.productdata E/=======﹕ {"success":0,"message":"Oops! An error occurred."}
08-22 00:39:40.300    7279-7452/com.example.akshay.productdata E/Create Response﹕ {"success":0,"message":"Oops! An error occurred."}

更新:

我试图在MYSQL数据库上运行查询,但是发生以下错误

Error
SQL query:

INSERT INTO school( rollno, sname, regid, class, fname, fno, mname, mno, route, timings, latitude, longitude ) 
VALUES ( 12, Akshay, mk34, MCA, Ajay Sood, 686, Manju Sood, 5454, 401, 55, 78.545545, 79.5421081 )

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Sood, 686, Manju Sood, 5454, 401, 55, 78.545545, 79.5421081)' at line 1 

请在SQL查询中的varchar字段中使用单引号''。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM