php - Android 值未插入我的 mysql 数据库中

标签 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."');";
}


?>

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

最佳答案

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

这就是您的 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 应用程序收到的信息,还会显示数据类型。

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

关于php - Android 值未插入我的 mysql 数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57052357/

相关文章:

安卓 4 : can't dismiss notification by swiping

mysql - 从数据表中获取前四个值。然后根据条件交换

php - undefined index PHP和MYSQL

php - PHP-检测另一个对象上的更改

android - 如何使两个不同的布局具有相同的高度?

java - Android:巨型模式与 Multidex

mysql - 检查 IF IS NULL 或 IF NOT EXIST,导致 SQL 语法错误

android - 我的数据未存储在数据库中

php - 我该如何改进这段 PHP 代码?

php - 如何在javascript中使用 anchor 的OnClick关闭弹出窗口?