简体   繁体   中英

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.

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.

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.

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

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. They normally are when you use some sensible formatting of your code.

The INSERT query has 6 columns mentioned and 7 parametes set

Also you have misspelt $id_person as $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.

Additional Note; Also take note of @JayBlanchards comments about hashing passwords and using prepared and parameterised queries

$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:

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

In addition into php file I modify my code with this one:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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