簡體   English   中英

為什么無法更新連接到我的Android應用程序的MySQL數據庫?

[英]Why can't a MySQL database, connected to my android app, be updated?

這是連接到MySQL數據庫測試的PHP文件代碼,以及將數據傳遞到PHP的Java代碼。 請幫助我找到錯誤。 當我運行它時,它不會更新數據庫。 但是,我可以使用PHP更新數據庫,它將顯示出來。

PHP文件:

<?php

 $db_name = "testing";
 $mysql_user = "root";
 $mysql_pass = "squidoo";
 $server_name = "localhost";
 $con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name)
 ?>

<?php
 require "dbconfigure.php";

 $firstname = isset($_POST["Firstname"])? $_POST["Firstname"]:null;
 $lastname = isset($_POST["Lastname"])? $_POST["Lastname"]:null;
 $birthdate = isset ($_POST["Birthdate"])? $_POST["Birthdate"]:null;
 $email = isset($_POST["email"])? $_POST["email"]: null;
 $username =  isset($_POST['username'])? $_POST['username'] : null;
 $password = isset ($_POST["password"])? $_POST['username'] : null;
 $sql_query = "INSERT INTO register (firstname, lastname, birthdate,        
 email,username,password)  
  VALUES('$firstname','$lastname','$birthdate','$email','$username','$password');";

?>

JAVA文件:

package com.example.sony.testing;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class RegisterActivity extends Activity {

String firstname, lastname, birthdate, email, username, password;

EditText FirstName, LastName, Email, BirthDate, NewUsername, NewPassword;


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



    FirstName = (EditText) findViewById(R.id.FirstName);
    LastName = (EditText) findViewById(R.id.LastName);
    BirthDate = (EditText) findViewById(R.id.BirthDate);
    Email = (EditText) findViewById(R.id.Email);
    NewUsername = (EditText) findViewById(R.id.NewUsername);
    NewPassword = (EditText) findViewById(R.id.NewPassword);


}

public void userReg(View view) {

    firstname = FirstName.getText().toString();
    lastname = LastName.getText().toString();
    birthdate = BirthDate.getText().toString();
    email = Email.getText().toString();
    username = NewUsername.getText().toString();
    password = NewPassword.getText().toString();

    String method = "register";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute(method, firstname, lastname, birthdate, email, username, password);
    finish();

      }


 }

package com.example.sony.testing;

      import android.app.AlertDialog;
      import android.content.Context;
      import android.os.AsyncTask;
     import android.widget.Toast;
     import java.io.BufferedReader;
     import java.io.BufferedWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.OutputStream;
     import java.io.OutputStreamWriter;
     import java.net.HttpURLConnection;
     import java.net.MalformedURLException;
     import java.net.URL;
     import java.net.URLEncoder;


 public class BackgroundTask extends AsyncTask <String,Void,String> {
AlertDialog alertDialog;
Context ctx;
  public BackgroundTask(Context ctx)
{

    this.ctx =ctx;
}


@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(ctx).create();
    alertDialog.setTitle("Login Information");
}
@Override
protected String doInBackground(String... params) {
    String reg_url = "http://10.0.2.2/webapp/register.php";
    String login_url = "http://10.0.2.2/webapp/login.php";
    String method = params[0];


    if (method.equals("register")) {
        String Firstname = params[1];
        String Lastname = params[2];
        String Birthdate = params[3];
        String email= params[4];
        String username = params[5];
        String password = params[6];

        try {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            //httpURLConnection.setDoInput(true);

            OutputStream OS = httpURLConnection.getOutputStream();

            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));

            String data = URLEncoder.encode("Firstname","UTF-8")+"="+URLEncoder.encode(Firstname,"UTF-8")+"&"+
                    URLEncoder.encode("Lastname","UTF-8")+"="+URLEncoder.encode(Lastname,"UTF-8")+"&"+
                    URLEncoder.encode("Birthdate","UTF-8")+"="+URLEncoder.encode(Birthdate,"UTF-8")+"&"+
                    URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"+
                    URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"+
                    URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");

            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            httpURLConnection.connect();
            httpURLConnection.disconnect();
            return "Registration Success...";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else if(method.equals("login"))
    {
        String login_name = params[1];
        String login_pass = params[2];
        try {
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();

            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

            String data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
                    URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String response = "";
            String line = "";

            while ((line = bufferedReader.readLine())!=null)
            {
                response+= line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            return response;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
    if(result.equals("Registration Success..."))
    {
        Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
    }
    else
    {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
    }
  }

在這里,您缺少執行插入查詢。 您可以使用mysqli_query這樣做。 緊隨其后的是處理大多數條件的代碼,可在您的應用中獲得更好的響應。

注意:查詢的響應在此處以JSON形式給出,因為它將傳遞給android應用程序。

$db_name = "testing";
$mysql_user = "root";
$mysql_pass = "squidoo";
$server_name = "localhost";

// Create connection
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);

// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

// check all parameters are with values
$firstname = isset($_POST["Firstname"]) ? $_POST["Firstname"]:null;
$lastname = isset($_POST["Lastname"]) ? $_POST["Lastname"]:null;
$birthdate = isset ($_POST["Birthdate"]) ? $_POST["Birthdate"]:null;
$email = isset($_POST["email"]) ? $_POST["email"]: null;
$username =  isset($_POST['username']) ? $_POST['username'] : null;
$password = isset ($_POST["password"]) ? $_POST['username'] : null;

$sql_query = "INSERT INTO register (firstname, lastname, birthdate,        
 email,username,password)  
  VALUES('$firstname','$lastname','$birthdate','$email','$username','$password')";

 // execute the query
if (mysqli_query($con, $sql_query)) 
{
    $data = array('result' => 'success', 'message' => 'Successfully user added!');
} 
else 
{
    $data = array('result' => 'error', 'message' => 'Error while registration!');
}

// close the connection
mysqli_close($con);

/* JSON Response */
header("Content-type: application/json");
echo json_encode($data);
    ?>

這是因為您從未執行過SQL查詢,因此無法將數據插入數據庫。 執行SQL,我認為它一定可以工作。

mysqli_query($con, $sql_query)

注意:您需要使用mysqli准備的語句 ,因為您目前容易受到SQL注入攻擊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM