Android值未插入我的MySQL数据库

时间:2019-07-16 07:43:08

标签: php android mysql

我正在尝试将editTexts中的某些值插入本地数据库,但无法正常工作。这是我的代码:

public class MainActivity extends AppCompatActivity {
    private static int REQUEST_INTERNET = 100;
    EditText et_name, et_password;
    Button send;
    String name,password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.INTERNET},REQUEST_INTERNET);
            return;
        }

        et_name = findViewById(R.id.et_name);
        et_password = findViewById(R.id.et_pass);
        send = findViewById(R.id.btn_send);

    }
    public void reguser(View view){


if (name != null){
    name= et_name.getText().toString();
}
if (password != null){
    password= et_password.getText().toString();

}
        String method= "register";

        BackgroundTask backgroundTask= new BackgroundTask(this);

        backgroundTask.execute(method,name,password);


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_INTERNET){
            if (grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){

            }
        }
    }
}

这是http请求:

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

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

    }
    @Override
    protected String doInBackground(String... params) {
        String reg_url = "http://127.0.0.1/stHans/parkinsonism.php";
        String method = params[0];

        if (method.equals("register")){
            String name = params[1];
            String password =params[2];

            try {
                URL url =new URL(reg_url);
                HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                OutputStream os = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));

                String data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"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();
                return "Registered!";
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }



    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(ctx,result,Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

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

这是php代码:

<?php
 require "init.php";

if(isset($_POST["name"]) && isset($_POST["password"])){

 $u_name=$_POST["name"];
 $u_password=$_POST["password"];

 $sql_query="INSERT INTO parkinsonism_value(name,password) VALUES('".$u_name."','".$u_password."');";
}


?>

是因为许可吗? 因为已经检查了与数据库的连接,并且数据库已完全运行。我已经尝试并更改了代码的所有部分,但似乎仍然无缘无故。

2 个答案:

答案 0 :(得分:1)

防止SQL注入并完成工作的正确解决方案如下:

这是您的 init.php 的外观(您需要用自己的身份验证详细信息替换):

$servername = "localhost"; // localhost by default
$username = "db_username"; // root by default
$password = "db_password";// empty by default
$dbname = "db_name"; // your db name
$conn="";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);// this allows to show you errors
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

这是您的php代码的外观:

<?php

require "init.php";

if(isset($_POST["name"]) && isset($_POST["password"])){

 $u_name=$_POST["name"];
 $u_password=$_POST["password"];


// prepare and bind
$stmt = $conn->prepare("INSERT INTO parkinsonism_value(name, password) VALUES (?, ?)");

// here it prepares a your sql query, leave it exactly as it is, the question marks are part of the code, they represent placeholders for information.

$stmt->bind_param("ss", $u_name, $u_password);
// here it binds your variables to the question marks above, therefore $u_name will bind to the first question mark, and $u_password to the second question mark.
// "ss" in bind param stands for the type of data you have if your username and password are strings it will be "ss" (if let's say your username was an int then instead of "ss" you would have "is" which resulted in $stmt->bind_param("is", $u_name, $u_password) );

$stmt->execute();// here it executes the query above with the parameters after this code has been executed you should have your information inserted in your database.

}

奖金提示: :使用var_dump($ _ POST)来查看您的变量是否已实际设置,它不仅会显示从您的android应用程序接收到的信息,还会显示数据类型。

如果您需要进一步的帮助,请随时回复我的答案。

答案 1 :(得分:0)

我们一开始只需要以下代码行:

if($_SERVER['REQUEST_METHOD']=='POST'){
....
}