php - 如何向远程数据库添加数据?

标签 php android mysql database server

https://github.com/mitchtabian/LoginAndRegister

我刚刚将 BackgroundTask 类中的 urlRegistration 和 urlLogin 变量从“http://tabian.ca/LoginAndRegister-register.php”更改为我的“http://lmonstergirl.0fees.us/LoginAndRegister-register.php”。

数据库与项目相同。

每当我想注册任何人时,我都会收到“成功注册用户”的消息,但它只添加了 id,其他行是空白的。

enter image description here

代码相同,我的 php 文件在下面。这个

<?php
require "LoginAndRegister-connection.php";

$user_name = $_POST["identifier_name"];
$user_pass = $_POST["identifier_password"];
$user_email = $_POST["identifier_email"];

//test variables
//$user_name = "Ron";
//$user_pass = "ronspassword";
//$user_email = "ron@tabian.ca";



$query = "INSERT INTO login (name,email,password) VALUES ('$user_name','$user_email','$user_pass')";

if(mysqli_query($conn,$query)){
echo "<h2>Data Successfully Inserted!</h2>";
}
else{
    echo "<h2>Data was unable to be inserted into database :(.</h2>";
}



?>

但是当我把我的 php 改成这个的时候

<?php
require "LoginAndRegister-connection.php";

//$user_name = $_POST["identifier_name"];
//$user_pass = $_POST["identifier_password"];
//$user_email = $_POST["identifier_email"];

//test variables
$user_name = "Ron";
$user_pass = "ronspassword";
$user_email = "ron@tabian.ca";



$query = "INSERT INTO login (name,email,password) VALUES ('$user_name','$user_email','$user_pass')";

if(mysqli_query($conn,$query)){
    echo "<h2>Data Successfully Inserted!</h2>";
}
else{
    echo "<h2>Data was unable to be inserted into database :(.</h2>";
}



?>

它添加到数据库

enter image description here

我还尝试将 $_POST 更改为 $_GET,但仍然添加了空白。

这是我的日志

FATAL EXCEPTION: main
                 Process: applications.loginandregister, PID: 3893
                 android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@12b6e281 is not valid; is your activity running?
                     at android.view.ViewRootImpl.setView(ViewRootImpl.java:576)
                     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:272)
                     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
                     at android.app.Dialog.show(Dialog.java:306)
                     at android.app.AlertDialog$Builder.show(AlertDialog.java:987)
                     at applications.loginandregister.BackgroundTask.display(BackgroundTask.java:183)
                     at applications.loginandregister.BackgroundTask.onPostExecute(BackgroundTask.java:169)
                     at applications.loginandregister.BackgroundTask.onPostExecute(BackgroundTask.java:29)
                     at android.os.AsyncTask.finish(AsyncTask.java:632)
                     at android.os.AsyncTask.access$600(AsyncTask.java:177)
                     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                     at android.os.Handler.dispatchMessage(Handler.java:102)
                     at android.os.Looper.loop(Looper.java:135)
                     at android.app.ActivityThread.main(ActivityThread.java:5349)
                     at java.lang.reflect.Method.invoke(Native Method)
                     at java.lang.reflect.Method.invoke(Method.java:372)
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

我只更改了代码中的 url,但你去吧:

public class BackgroundTask extends AsyncTask<String,Void,String> {

SharedPreferences preferences;
SharedPreferences.Editor editor;

Context context;

BackgroundTask(Context ctx){
    this.context = ctx;
}

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

    preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
    editor = preferences.edit();
    editor.putString("flag","0");
    editor.commit();

    String urlRegistration = "http://lmonstergirl.0fees.us/LoginAndRegister-register.php";
    String urlLogin  = "http://lmonstergirl.0fees.us/LoginAndRegister-login.php";
    String task = params[0];

    if(task.equals("register")){
        String regName = params[1];
        String regEmail = params[2];
        String regPassword = params[3];

        try {
            URL url = new URL(urlRegistration);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            String myData = URLEncoder.encode("identifier_name","UTF-8")+"="+URLEncoder.encode(regName,"UTF-8")+"&"
                    +URLEncoder.encode("identifier_email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&"
                    +URLEncoder.encode("identifier_password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8");
            bufferedWriter.write(myData);
            bufferedWriter.flush();
            bufferedWriter.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            inputStream.close();

            editor.putString("flag","register");
            editor.commit();
            return "Successfully Registered " + regName;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    if(task.equals("login")){
        String loginEmail = params[1];
        String loginPassword = params[2];
        try {
            URL url = new URL(urlLogin);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);

            //send the email and password to the database
            OutputStream outputStream = httpURLConnection.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            String myData = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginEmail,"UTF-8")+"&"
                    +URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginPassword,"UTF-8");
            bufferedWriter.write(myData);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            //get response from the database
            InputStream inputStream = httpURLConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String dataResponse = "";
            String inputLine = "";
            while((inputLine = bufferedReader.readLine()) != null){
                dataResponse += inputLine;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.out.println(dataResponse);

            editor.putString("flag","login");
            editor.commit();
            return  dataResponse;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return null;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

//This method willbe called when doInBackground completes... and it will return the completion string which
//will display this toast.
@Override
protected void onPostExecute(String s) {
    String flag = preferences.getString("flag","0");

    if(flag.equals("register")) {
        Toast.makeText(context,s,Toast.LENGTH_LONG).show();
    }
    if(flag.equals("login")){
        String test = "false";
        String name = "";
        String email = "";
        String[] serverResponse = s.split("[,]");
        test = serverResponse[0];
        name = serverResponse[1];
        email = serverResponse[2];

        if(test.equals("true")){
            editor.putString("name",name);
            editor.commit();
            editor.putString("email",email);
            editor.commit();
            Intent intent = new Intent(context,LogginIn.class);
            context.startActivity(intent);
        }else{
            display("Login Failed...", "That email and password do not match our records :(.");
        }
    }else{
        display("Login Failed...","Something weird happened :(.");
    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

public void display(String title, String message){
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}
}  

public class LogginIn extends AppCompatActivity {
TextView name,email;
SharedPreferences preferences;

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

    email = (TextView) findViewById(R.id.textEmail);
    name = (TextView) findViewById(R.id.textName);
    preferences = this.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);

    String mName = preferences.getString("name","ERROR getting name");
    String mEmail = preferences.getString("email","ERROR getting email");
    name.setText(mName);
    email.setText(mEmail);
}
}

public class Register extends AppCompatActivity {
EditText etName, etEmail, etPassword;
String name, email, password;
Button btnRegister;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register_layout);
    etName = (EditText) findViewById(R.id.etNewName);
    etEmail = (EditText) findViewById(R.id.etNewEmail);
    etPassword = (EditText) findViewById(R.id.etNewPassword);
    btnRegister = (Button) findViewById(R.id.btnNewRegister);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name = etName.getText().toString();
            email = etEmail.getText().toString();
            password = etPassword.getText().toString();
            String task = "register";
            BackgroundTask backgroundTask = new BackgroundTask(Register.this);
            backgroundTask.execute(task,name, email, password);
            finish();
        }
    });


}
}

public class MainActivity extends AppCompatActivity {

Button btnRegister, btnLogin;
EditText etEmail,etPassword;
String stringEmail,stringPassword;

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

    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    etEmail = (EditText) findViewById(R.id.etEmail);
    etPassword = (EditText) findViewById(R.id.etPassword);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stringEmail = etEmail.getText().toString();
            stringPassword = etPassword.getText().toString();
            String task = "login";
            BackgroundTask backgroundTask = new BackgroundTask(MainActivity.this);

            etEmail.setText("");
            etPassword.setText("");

            //execute the task
            //passes the paras to the backgroundTask (param[0],param[1],param[2])
            backgroundTask.execute(task,stringEmail,stringPassword);
        }
    });

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,Register.class);
            startActivity(intent);
        }
    });
}
}

最佳答案

感谢您发布到 stackoverflow!

因为您的测试变量有效,所以您知道它不是 php.ini 文件。问题几乎 100% 在于 android 代码。请发布您的 android 代码。

关于php - 如何向远程数据库添加数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39266630/

相关文章:

php - 四年前的MySQL查询

android - Google Tango Leibniz API 中的彩色图像

android - CardView 内的 ImageView CardView 内

mysql - 如何优化规范化数据库结构的查询?

php - 我喜欢 7 0's, but that' s 只是不对(PHP 时间问题)

php - 类似 mysql 的查询无法在浏览器上运行

php - MySQL 错误的时区

php - Guzzle PUT 请求身份验证错误

Android 应用程序在方向更改时重置,最佳处理方式?

php - JSON 解析器无法转换我的字符串