简体   繁体   English

如何从 Android 应用程序将数据插入 mysql 数据库?

[英]How to insert data into a mysql database form an Android app?

I need to insert into a mysql database some data retrieving from an android app and insert it into some different tables.我需要将一些从 android 应用程序检索的数据插入到 mysql 数据库中,并将其插入到一些不同的表中。

I create a user's register page/activity and it work but I tried to insert others data from an other activity and I can't insert them into my database.我创建了一个用户的注册页面/活动,它可以工作,但我尝试从其他活动中插入其他数据,但无法将它们插入到我的数据库中。

Here's my code: RegisterUserClass is the class for the translation.这是我的代码: RegisterUserClass是用于翻译的类。

RegisterBody.java -> in this case I need to save into table also the user's id, this is the why I save email and password. RegisterBody.java -> 在这种情况下,我需要将用户 ID 也保存到表中,这就是我保存电子邮件和密码的原因。

private static final String REGISTER_URL = "http://10.0.2.2/sFitness/RegisterBody.php";

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

        etWaist =(EditText) findViewById(R.id.etWaist);
        etHips =(EditText) findViewById(R.id.etHips);
        etBreast =(EditText) findViewById(R.id.etBreast);
        etWrist=(EditText) findViewById(R.id.etWrist);
        etWeight=(EditText)findViewById(R.id.etWeight);
        etHeight=(EditText)findViewById(R.id.etHeight);

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

        bNext.setOnClickListener(this);

        Bundle b= this.getIntent().getExtras();
        array=b.getStringArray(null);
        name=array[0];
        surname=array[1];
        age=array[2];
        email=array[3];
        password=array[4];
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.bNext:
                Toast.makeText(getApplicationContext(), "All ok", Toast.LENGTH_LONG).show();
                registerUser();
                break;
        }
    }

    private void registerUser() {
        String waist = etWaist.getText().toString();
        String hips = etHips.getText().toString();
        String breast = etBreast.getText().toString();
        String wrist = etWrist.getText().toString();
        String weight = etWeight.getText().toString();
        String height = etHeight.getText().toString();

        register(waist, hips, breast, wrist, weight, height);
    }

    private void register(String waist, String hips, String breast, String wrist, String weight,String height) {
        class RegisterUser extends AsyncTask<String, Void, String> {

            ProgressDialog loading;
            RegisterUserClass ruc = new RegisterUserClass();

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

                loading = ProgressDialog.show(RegisterBody.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("waist", params[0]);
                data.put("hips", params[1]);
                data.put("breast", params[2]);
                data.put("wrist", params[3]);
                data.put("weight", params[4]);
                data.put("height", params[5]);

                String result = ruc.sendPostRequest(REGISTER_URL, data);
                return result;
            }
        }
        RegisterUser ru = new RegisterUser();
        ru.execute(waist,hips,breast,wrist,weight,height, email, password);
        Bundle b=new Bundle();
        b.putStringArray(null, new String[]{name, surname, age, email, password,waist,hips,breast,wrist,weight,height});
        Intent in=new Intent(this,ChooseDiet.class);
        in.putExtras(b);
        startActivity(in);
    }

RegisterBody.php注册体.php

if($_SERVER['REQUEST_METHOD']=='POST')
{
    $waist = $_POST["waist"];
    $hips = $_POST["hips"];
    $breast = $_POST["breast"];
    $wrist = $_POST["wrist"];
    $weight = $_POST["weight"];
    $height = $_POST["height"];
    $email = $_POST["email"];
    $password = $_POST["password"];


    $conn = mysqli_connect("localhost","root","","sfitness") or die("Error " . mysqli_error($conn));


    $sql="SELECT ID_Person FROM Person WHERE email=".$email." AND password=".$password."";
    $id_person=mysqli_query($conn,$sql);
    if (!$sql)
    {
            echo 'Could not run query: ' . mysql_error();
            exit;
    }
    $id_person = mysql_fetch_row($sql);



    $query ="INSERT INTO Body
                    (Waistline,Hips,Breast,
                     Wrist,Height,ID_person)                  
              values('$waist','$hips','$breast',
                     '$wrist','$weight','$height','$id_peroson')";

    $rows=mysql_query($query,$conn) or die("query fallita");
    mysql_close($conn);

    if($rows>0)
        echo "Registrazione avvenuta correttamente";
    else
        echo "Registrazione fallita";

}

else
{
    echo "Error!!";
}

I don't have errors but the data won't save into table.. why?我没有错误,但数据不会保存到表中..为什么?

Ok having formatted your INSERT query so it is more readable the error is obvious.好的,已经格式化了您的 INSERT 查询,因此它更具可读性,错误很明显。 They normally are when you use some sensible formatting of your code.它们通常是当您使用一些合理的代码格式时。

The INSERT query has 6 columns mentioned and 7 parametes set INSERT 查询有 6 个提到的列和 7 个参数集

Also you have misspelt $id_person as $ID_Peroson您也将$id_person拼错为$ID_Peroson

$query ="INSERT INTO Body                 
              (Waistline,Hips,Breast,
               Wrist,Height,ID_person) 
         values('$waist','$hips','$breast',
                '$wrist','$weight','$height','$id_person')";

$res = mysqli_query($query,$conn);
if ($res === FALSE ){
    echo mysqli_error($conn);
    exit;
}

Either add Weight to the column list or remove $weight from the parameter list.将权Weight添加到列列表或从参数列表中删除$weight

Additional Note;附加说明; Also take note of @JayBlanchards comments about hashing passwords and using prepared and parameterised queries还要注意@JayBlanchards 关于散列密码和使用准备好的参数化查询的评论

$query ="INSERT INTO Body                 
                   (Waistline,Hips,Breast,Wrist,Weight,Height,ID_person) 
             values(?,?,?,?,?,?,?)";

$stmt = mysqli_prepare($query);
if ( $stmt === FALSE ) {
    mysqli_error($conn);
    exit;
}
mysqli_stmt_bind_param('ssssssi', '$waist','$hips','$breast',
                                  '$wrist','$weight','$height','$id_person');

$result = mysqli_stmt_execute($stmt); 
if ( $result === FALSE ){
    echo $mysqli_stmt_error($stmt);
    exit;
}

I find the solution of my problems.我找到了我的问题的解决方案。

Into the java file I modify this part to add:java文件中我修改这部分添加:

data.put("email", email);
data.put("password", password);

In addition into php file I modify my code with this one:除了php文件,我还用这个修改了我的代码:

$conn = mysql_connect("127.0.0.1","root","") or die("DBMS non disponibile");
mysql_select_db("sfitness") or die("Database non disponibile");

$sql="SELECT * FROM person WHERE Email='$email' AND Password='$password'";

$result=mysql_query($sql,$conn);
if (mysql_num_rows($result)==1){
    $row = mysql_fetch_array($result);
    $id_person=$row['ID_Person'];
}


$query ="INSERT INTO Body (Waistline, Hips, Breast, Wrists, Weight, Height, ID_person) values('$waist','$hips','$breast','$wrist','$weight','$height','$id_person')";

$rows=mysql_query($query,$conn) or die("query fallita");
mysql_close($conn);
if($rows>0)
     echo "Correct registration";
else
     echo "Registration failed";

With this code now it works, thanks to all有了这个代码现在它可以工作了,感谢所有人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM