试图通过php在android中插入数据但不能做到这一点

时间:2016-07-15 06:46:13

标签: java php android mysqli

我试图通过php文件在mysql中插入数据,该文件包含3个查询,其中执行第一个选择查询然后插入并在更新之后。选择和更新是在同一个表上完成的,而试图通过php在android应用程序中插入另一个表。

这是我的java代码mainactivity.java

package com.lab.myospaz.insert;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText editTextName;
    private EditText editTextnumber;
    private EditText editTextstandard;
    private EditText editTextgender;
    private EditText editTextinstitute;
    private EditText editTextloction;
    private EditText editTextactivation;
    private EditText editTextEmail;

    private Button buttonRegister;

    private static final String REGISTER_URL = "http://register.mobilekipathshala.com/StudentActivation.php";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextnumber = (EditText) findViewById(R.id.editTextnumber);
        editTextstandard = (EditText) findViewById(R.id.editTextstandard);
        editTextinstitute = (EditText) findViewById(R.id.editTextinstitute);
        editTextloction = (EditText) findViewById(R.id.editTextloction);
        editTextgender = (EditText) findViewById(R.id.editTextgender);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        editTextactivation = (EditText) findViewById(R.id.editTextactivation);

        buttonRegister = (Button) findViewById(R.id.buttonRegister);

        buttonRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v == buttonRegister){
            registerUser();
        }
    }

    private void registerUser() {
        String full_name = editTextName.getText().toString().trim().toLowerCase();
        String contact_number = editTextnumber.getText().toString().trim().toLowerCase();
        String email_address = editTextEmail.getText().toString().trim().toLowerCase();
        String location = editTextloction.getText().toString().trim().toLowerCase();
        String institute = editTextinstitute.getText().toString().trim().toLowerCase();
        String standard= editTextstandard.getText().toString().trim().toLowerCase();
        String gender = editTextgender.getText().toString().trim().toLowerCase();
        String code = editTextactivation.getText().toString().trim().toLowerCase();
        register(full_name,contact_number,email_address,location,institute,standard,gender,code);
    }

    private void register(String full_name, String contact_number, String email_address, String location,String institute,String standard,String gender,String code) {
        class RegisterUser extends AsyncTask<String, Void, String>{
            ProgressDialog loading;
            RegisterUserClass ruc = new RegisterUserClass();


            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this, "Please Wait",null, true, true);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(String... params) {

                HashMap<String, String> data = new HashMap<String,String>();
                data.put("full_name",params[0]);
                data.put("contact_number",params[1]);
                data.put("email_address",params[2]);
                data.put("location",params[3]);
                data.put("institute",params[4]);
                data.put("standard",params[5]);
                data.put("gender",params[6]);
                data.put("code",params[7]);

                String result = ruc.sendPostRequest(REGISTER_URL,data);

                return  result;
            }
        }

这是另一个类RegisterUser.java

package com.lab.myospaz.insert;

/**
 * Created by asus1 on 14-Jul-2016.
 */
import org.apache.http.HttpException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by Belal on 8/6/2015.
 */
public class RegisterUserClass {

    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                response = br.readLine();
            }
            else {
                response="Error Registering";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

            RegisterUser ru = new RegisterUser();
            ru.execute(full_name,contact_number,email_address,location,institute,standard,gender,code);
    }
}

这是我的php文件

<?php
//Database Connection

$conn = new mysqli('127.0.0.1', 'mobileki_factum', '%bq41214xA5&}wp)o','mobileki_amit');

if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

$sql1="select ";
$code=$_POST['code'];


if(isset($_POST["submit"])){
    $query = "SELECT * FROM `mobileki_amit`.`activations` WHERE code='$code' AND status='not used'";

$result=$conn->query($query);


if($result->num_rows > 0)
{
    $fname=$_POST['fname']; 
    $email=$_POST['email_address'];
    $contact=$_POST['contact_number'];
    $gender=$_POST['gender'];
    $location=$_POST['location'];
    $stander=$_POST['standard'];
    $institute=$_POST['institute'];
    $code=$_POST['code'];








$sql1="INSERT INTO `students`(`full_name`, `email_address`, `contact_number`, `gender`, `location`, `standard`, `institute`) VALUES('$fname','$email','$contact','$gender','$location','$stander','$institute');";
if($conn->query($sql1)===TRUE){
    echo "new recored is successful AND";


$mysql_query="UPDATE `activations` SET 
                               `status` = 'in use'
                                WHERE `CODE` = '$code'";
    // or die(mysql_error());

if($conn->query($mysql_query)===TRUE){
    echo "recored is updated successful";
}
else
{
 echo "no recored  updated ";
}


}
else{
echo "not able to insert";

}

0 个答案:

没有答案