Reputation: 642
I'm trying to insert some values from editTexts into my local database but it's not working. Here is my code:
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){
}
}
}
}
this is the http request:
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);
}
}
and this is the php code:
<?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."');";
}
?>
Is it because of the permission? because the connection to the database is already checked and its fully operating. I've tried and changed everything and every part of the code but still it seems it won't work for no reason.
Upvotes: 0
Views: 91
Reputation: 642
We just needed this line of code in the beginning:
if($_SERVER['REQUEST_METHOD']=='POST'){
....
}
Upvotes: 0
Reputation: 11
The proper solution which prevents SQL Injection and does the job is the following:
This is how your init.php should look like(you need to replace the authentication details with yours):
$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();
}
and this is how your php code should look like:
<?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.
}
Bonus tip: use var_dump($_POST) to see if your variables are actually set and it will display not only the information received from your android application but also the type of data.
If you need further help feel free to reply to my answer.
Upvotes: 1