Android + Volley + PHP Connector Does not insert data into SQL Server database

Asked

Viewed 68 times

1

I’m trying to input data from an Android application into the SQL Server database, and I’m using Volley and PHP Nector. The connection is ok, and searches usually appear on the device screen. I need to enter data, but all tests were unsuccessful. Thanks in advance for the help.

Code php.:

$username = "";   
$email = "";    
$password = ""; 
if(isset($_POST['nome'])){    
    $username = $_POST['nome'];   
}
if(isset($_POST['email'])){    
    $email = $_POST['email'];    
}
if(isset($_POST['senha'])){    
    $password = $_POST['senha'];    
}
if(!empty($username) && !empty($password) && !empty($email)){
    $sql1 = "INSERT INTO Usuario (nome, email, senha) VALUES ('".$_POST['nome']."','".$_POST['email']."','".$_POST['senha']."')";
}
include_once "busca.php";
?>

Code java register., from Android Studio, where I connect to Volley:

public class Cadastro extends AppCompatActivity
{
    EditText txtNome, txtEmail, txtSenha, txtRepeteSenha;
    Button btnCadastrar;
    ProgressBar progressBar;
    ConnectionClass connectionClass;


    AlertDialog.Builder alertDialog;

    @Override
    protected void onCreate (Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cadastro);
        connectionClass = new ConnectionClass();
        txtNome = findViewById(R.id.name);
        txtEmail = findViewById(R.id.mail);
        txtSenha = findViewById(R.id.key);
        txtRepeteSenha = findViewById(R.id.key_again);
        btnCadastrar = findViewById(R.id.cadastrar);
        progressBar = findViewById(R.id.progressBar);

        btnCadastrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String nome, email, senha;
                nome = txtNome.getText().toString();
                email = txtEmail.getText().toString();
                senha = txtSenha.getText().toString();
                RequestQueue queue = Volley.newRequestQueue(Cadastro.this);

                String url = "http://192.168.15.17/cadastro.php";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                alertDialog = new AlertDialog.Builder(Cadastro.this);
                                //alertDialog.setTitle("Resposta do servidor:");
                                alertDialog.setMessage("Resposta: " + response);
                                alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        txtNome.setText("");
                                        txtEmail.setText("");
                                        txtSenha.setText("");
                                    }
                                });
                                AlertDialog alertDialog2 = alertDialog.create();
                                alertDialog2.show();
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(Cadastro.this, "Erro!", Toast.LENGTH_SHORT).show();
                                error.printStackTrace();
                            }
                        }){
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("nome", nome);
                        params.put("email", email);
                        params.put("senha", senha);
                        return params;
                    }
                };
                queue.add(stringRequest);
            }
        });
    }

php connection.

<?php

    $serverName = "DESKTOP-AOQ0PBR\TESTE"; 
    $connectionInfo = array( "Database"=>"appscout");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);

    if( $conn ) {
        echo "Connection established.<br />";
    }else{
         echo "Connection could not be established.<br />";
         die( print_r( sqlsrv_errors(), true));
    }
?>

1 answer

2


You cannot insert as you just created a string concatenated with posted values.

I created a solution with commented code:

if(!empty($username) && !empty($password) && !empty($email)){
     $sql1 = "INSERT INTO Usuario (nome, email, senha) VALUES (?,?,?)"; // String que contém o comando de inserção
        try {
            // preparação
          $st = sqlsrv_prepare( $conn, $sql1, [$nome, $email, $senha]);
          sqlsrv_execute($st); // <-- inserção das variáveis nos seus respectivos campos

        } catch(PDOException $e) {
            // se algo der errado no meio do caminho mostre a mensagem de erro
            echo 'ERROR: ' . $e->getMessage();
        }
}
  • Hi Andrei. Thank you so much for your help, however I can connect with the bank using the php connection. no include. The php search. at the end of the code brings the requested results from the bank. What I can’t even insert is.

  • @Paulolara put the code of the connection with the bank in the question.

  • 1

    Andrei, it worked here with your code. I was sinning in the detail of the post, and with those "?" inside the VALUES. I will move on to the next battle. Thank you very much. Resolved.

  • ok... I’ll just edit the answer because you entered new information in the question.

  • ok. With these answers I already found the path in delete and update.

  • @Paulolara tranquil!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.