0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
bsiilvia
  • 97
  • 1
  • 10
  • 1
    **mysql_query != mysqli_query** You cannot mix `mysqli_` and `mysql_` function calls – RiggsFolly Feb 09 '16 at 15:24
  • So, what do I need to use? @RiggsFolly – bsiilvia Feb 09 '16 at 15:25
  • If that is not giving you errors in the php error log, then you are **just not looking** – RiggsFolly Feb 09 '16 at 15:25
  • You connect with `mysqli_connect` Your SELECT uses `mysqli_query()` stick with all `mysqli_` functions all the way through your code. – RiggsFolly Feb 09 '16 at 15:26
  • Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). – Jay Blanchard Feb 09 '16 at 15:30
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). – Jay Blanchard Feb 09 '16 at 15:30
  • @RiggsFolly I modify with all `mysqli_` but nothing will be saved into my db.. why? – bsiilvia Feb 09 '16 at 15:31

2 Answers2

0

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 Weightto 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;
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

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

bsiilvia
  • 97
  • 1
  • 10