使用 PHP 在 MySQL 数据库中插入一条记录


insert a record in mysql db using php

正在Android上做一个调查项目,它是关于登录的(这部分有效)和插入数据这部分不起作用是问卷,当调查的人登录应用程序时,有一个调查要做,在这个项目中,我从5个问题开始,答案是或否答案作为原型, 他必须回答问题,并且在单击保存按钮时必须将它们添加到MySQL数据库中。但这不起作用(日志猫在下面)以下是班级问卷.java:

public class Questionnaire extends Activity implements LocationListener {
// Progress Dialog
    private ProgressDialog pDialog;
//latitude et longitude
    private LocationManager lm;
    Location location;
    double longitude = 0;
    double latitude = 0;
    private double altitude;
    private float accuracy;
    int i;
    JSONParser jsonParser = new JSONParser();
    Button enregistrer;
    EditText zone;
    RadioGroup mRadioGroup1, mRadioGroup2, mRadioGroup3, mRadioGroup4, mRadioGroup5;
    RadioButton b1, b2, b3, b4, b5;
// url to create new product
    private static String url_insertion = "http://10.0.2.2/android/insertion.php";
// JSON Node names
    private static final String TAG_SUCCESS = "success";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.questions);
        Bundle params = getIntent().getExtras();
        i = params.getInt("compteur");
        i++;
        // Edit zone text
        EditText zone1 = (EditText) findViewById(R.appreciation.zone);
        // edit latitude longitude
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        // edit radiogroup
        mRadioGroup1 = (RadioGroup) findViewById(R.appreciation.rep1);
        mRadioGroup2 = (RadioGroup) findViewById(R.appreciation.rep2);
        mRadioGroup3 = (RadioGroup) findViewById(R.appreciation.rep3);
        mRadioGroup4 = (RadioGroup) findViewById(R.appreciation.rep4);
        mRadioGroup5 = (RadioGroup) findViewById(R.appreciation.rep5);
        //edit radio button
        b1 = (RadioButton) findViewById(mRadioGroup1.getCheckedRadioButtonId());
        b2 = (RadioButton) findViewById(mRadioGroup2.getCheckedRadioButtonId());
        b3 = (RadioButton) findViewById(mRadioGroup3.getCheckedRadioButtonId());
        b4 = (RadioButton) findViewById(mRadioGroup4.getCheckedRadioButtonId());
        b5 = (RadioButton) findViewById(mRadioGroup5.getCheckedRadioButtonId());
        // Create button
        Button enregistrer = (Button) findViewById(R.appreciation.enregistrer);
        // button click event
        enregistrer.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                new InsertAppreciation().execute();
            }
        });
    }
    class InsertAppreciation extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Questionnaire.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        /**
         * Creating appreciation
         * */
        protected String doInBackground(String... args) {
            String zone1 = zone.getText().toString();
            //  String latitude = String.valueOf(latitude).toString();
            //  String longitude = String.valueOf(longitude).toString();
            String rep1 = b1.getText().toString();
            String rep2 = b2.getText().toString();
            String rep3 = b3.getText().toString();
            String rep4 = b4.getText().toString();
            String rep5 = b5.getText().toString();
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("zone", zone1));
            //  params.add(new BasicNameValuePair("latitude", latitude));
            //   params.add(new BasicNameValuePair("longitude", longitude));
            params.add(new BasicNameValuePair("rep1", rep1));
            params.add(new BasicNameValuePair("rep2", rep2));
            params.add(new BasicNameValuePair("rep3", rep3));
            params.add(new BasicNameValuePair("rep4", rep4));
            params.add(new BasicNameValuePair("rep5", rep5));
            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_insertion,
                    "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 appreciation
                    Toast.makeText(getBaseContext(), "Successful insertion", Toast.LENGTH_SHORT).show();
                    if (i < 5) {
                        Intent intent1 = new Intent(Questionnaire.this, Questionnaire.class);
                        intent1.putExtra("compteur", i);
                        startActivity(intent1);
                    } else {
                        Intent intent2 = new Intent(Questionnaire.this, Endsurvey.class);
                        startActivity(intent2);
                    }
                } else {
                    // failed to create appreciation
                    Toast.makeText(getBaseContext(), "failed insertion", Toast.LENGTH_SHORT).show();
                }
            } 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();
        }
    }
}

对不起,我知道它太长了,但我别无选择。这是日志猫:

08-15 22:15:31.620: D/AndroidRuntime(241): Shutting down VM
08-15 22:15:31.630: W/dalvikvm(241): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
08-15 22:15:31.640: E/AndroidRuntime(241): Uncaught handler: thread main exiting due to uncaught exception
08-15 22:15:31.671: E/AndroidRuntime(241): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.stage.sondage/com.stage.sondage.Questionnaire}: java.lang.NullPointerException
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.access$2200(ActivityThread.java:119)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.os.Looper.loop(Looper.java:123)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.main(ActivityThread.java:4363)
08-15 22:15:31.671: E/AndroidRuntime(241):  at java.lang.reflect.Method.invokeNative(Native Method)
08-15 22:15:31.671: E/AndroidRuntime(241):  at java.lang.reflect.Method.invoke(Method.java:521)
08-15 22:15:31.671: E/AndroidRuntime(241):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
08-15 22:15:31.671: E/AndroidRuntime(241):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
08-15 22:15:31.671: E/AndroidRuntime(241):  at dalvik.system.NativeStart.main(Native Method)
08-15 22:15:31.671: E/AndroidRuntime(241): Caused by: java.lang.NullPointerException
08-15 22:15:31.671: E/AndroidRuntime(241):  at com.stage.sondage.Questionnaire.onCreate(Questionnaire.java:73)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-15 22:15:31.671: E/AndroidRuntime(241):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
08-15 22:15:31.671: E/AndroidRuntime(241):  ... 11 more
08-15 22:15:31.730: I/dalvikvm(241): threadid=7: reacting to signal 3
08-15 22:15:31.730: E/dalvikvm(241): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
08-15 22:15:35.341: I/Process(241): Sending signal. PID: 241 SIG: 9
08-15 22:15:36.380: E/ActivityThread(282): Failed to find provider info for com.google.settings
08-15 22:15:36.390: E/ActivityThread(282): Failed to find provider info for com.google.settings
08-15 22:15:36.430: E/ActivityThread(282): Failed to find provider info for com.google.settings
08-15 22:15:36.982: D/dalvikvm(282): GC freed 1983 objects / 133688 bytes in 137ms
08-15 22:15:37.110: D/LocationManager(282): Constructor: service = android.location.ILocationManager$Stub$Proxy@44ea4f80
08-15 22:15:37.212: D/LocationManager(282): removeUpdates: listener = com.google.android.maps.MyLocationOverlay@44e9db00
08-15 22:15:37.222: I/Maps.MyLocationOverlay(282): Request updates from gps
08-15 22:15:37.360: D/SensorManager(282): found sensor: Goldfish 3-axis Accelerometer, handle=0
08-15 22:15:37.520: D/SensorManager(282): found sensor: Goldfish 3-axis Magnetic field sensor, handle=1
08-15 22:15:37.672: D/SensorManager(282): found sensor: Goldfish Orientation sensor, handle=2
08-15 22:15:37.830: D/SensorManager(282): found sensor: Goldfish Temperature sensor, handle=3
08-15 22:15:37.970: I/MapActivity(282): Handling network change notification:CONNECTED
08-15 22:15:37.980: E/MapActivity(282): Couldn't get connection factory client
08-15 22:15:38.460: D/dalvikvm(282): GC freed 5048 objects / 299360 bytes in 90ms
08-15 22:16:00.971: D/dalvikvm(282): GC freed 13338 objects / 892160 bytes in 200ms

这是 PHP 文件:

    <?php
    //turn off error reporting
     error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
    //Create fields for the database
    //server, username, password, database
    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "";
    $dbdb = "survey";
    //connect to mySQL
    $connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");
    //Select the database
    mysql_select_db($dbdb)or die("database selection error");
    //Retrieve the login details via POST
    $zone = $_POST['zone'];
    $latitude = $_POST['latitude'];
    $longitude = $_POST['longitude'];
    $rep1 = $_POST['rep1'];
    $rep2 = $_POST['rep2'];
    $rep3 = $_POST['rep3'];
    $rep4 = $_POST['rep4'];
    $rep5 = $_POST['rep5'];
    // mysql inserting a new row
    $result = mysql_query("INSERT INTO appreciation(id, zone, latitude, longitude,                    rep1, rep2, rep3, rep4, rep5) VALUES('', '$zone1', '', '', '$rep1', '$rep2', '$rep3',  '$rep4', '$rep5' )");

    // 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);
    //close the connection
    mysql_close();

         }

          ?>

请帮忙,这真的很紧急。 谢谢

首先,正如其他人在评论中所说,请查看PDO,因为您的数据库交互非常不安全。

您提供的异常跟踪显示Questionnaire活动的onCreate方法中发生了未捕获(开始使用 try/catch)异常。 我希望(请通过调试检查)当您第二次查看 intents 捆绑包中的compteur时会抛出错误(您正在从Questionnaire活动转到Questionnaire活动)。

我可以看到您在触发意图时将一个对象放入捆绑包中,但是在处理它之前您还没有检查它是否为空。

Unable to open stack trace file '/data/anr/traces.txt': Permission denied

您是否在清单 xml 文件中添加了从 SD 卡读取的权限?

<uses-permission  android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>