0

I have an activity where the user enters his / her name, username, and password. I want to send this information as an entry in a MySQL database. Here is my code:

 protected String doInBackground(String... params) {

    String reg_url = "http://MyIPAddress:ServerPort#/Register.php"; 



        String name = params[1];
        String user_name = params[2];
        String user_pass = params[3];


        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("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                    URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
                    URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");


            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();


            return "Registration Success!";


        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) { 

            e.printStackTrace();
        }


    return null;

}

The code runs without any errors, but the database remains empty after the program is executed. Here is my PHP file (Register.php):

 <?php

   require "Connection.php"; //Establishes connection to database


   $name = $_POST["user"]; 
   $user_name = $_POST["user_name"];
   $user_pass = $_POST["user_pass"];

   $sql_query = "insert into user_info values('$name','$user_name','$user_pass');"; 

   if (mysqli_real_query($link, $sql_query)) {

      echo "<h1> Data Insertion Success! </h1>";

   }

   else {

     echo "Data Insertion Error..."; 


   }


 ?>

And the code to connect to the database (Connection.php):

<?php


   $link = mysqli_init();

   $success = mysqli_real_connect($link,$host,$user,$password,$db,$port);


   if($success) {

      echo "<h1> Success! </h1>";

   }


   else {

      echo "Error...".mysqli_connect_error();

   }

?>

Am I missing something here? I would gladly appreciate your help. Thanks!

Nisarg
  • 397
  • 1
  • 5
  • 14
  • Where is the Server side code that runs when you post this data – RiggsFolly Aug 24 '16 at 21:49
  • We do not PLOUGH through a youtube tutorial to catch up on what you have done wrong. Please read how to create a [Minimal, Complete and Verifiable example](http://stackoverflow.com/help/mcve) – RiggsFolly Aug 24 '16 at 21:50
  • Have you checked that the serer receives the request? If so have you debugged through on that side to see where its failing? – Gabe Sechan Aug 24 '16 at 21:58
  • @RiggsFolly I just edited the question so you can see my PHP file. I have followed the instructions on the tutorial word for word but the code still doesn't work, that's why I felt a need to post the link.... the only difference is I am using the MAMP service instead of WAMP for my server / database. (since I am coding on a Mac). – Nisarg Aug 24 '16 at 21:59
  • @GabeSechan Yes, I have and it works fine..... I just edited the question to post my PHP code that communicates with the database – Nisarg Aug 24 '16 at 22:01
  • Lets see the `Connection.php` file as well – RiggsFolly Aug 24 '16 at 22:01
  • @RiggsFolly Okay, I just posted the Connection.php code – Nisarg Aug 24 '16 at 22:06
  • 1
    I have never used the `mysqli_real_*` functions, cant see why your tutorial is either, so I will bow out – RiggsFolly Aug 24 '16 at 22:18
  • 1
    I would suggest a change to the insert query `"insert into user_info col_name1, col_name2, col_name3 values('$name','$user_name','$user_pass')";` – RiggsFolly Aug 24 '16 at 22:19
  • @RiggsFolly Alright, thanks for the help! I also found out that I was using the wrong port number for my server, and then I edited the PHP file as you said..... everything works fine now. :) – Nisarg Aug 24 '16 at 22:45
  • @RiggsFolly Any tutorial that recommends those should be thrown into the trash. It's obviously making terrible suggestions. That interface is so obscure I'm surprised that code even runs. – tadman Aug 24 '16 at 23:17
  • 1
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST` or `$_GET` data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Aug 24 '16 at 23:17
  • @tadman Thank you very much for letting me know about this, I will definitely work on fixing these problems. I just posted my own answer, where I included the new code I'm using (not from the tutorial - see the reference link) and things seem to be working fine now. Here is the link to the tutorial I was following before: https://www.youtube.com/watch?v=cOsZHuu8Qog Should I look for another tutorial? Please let me know what you think. I really appreciate your help. – Nisarg Aug 25 '16 at 03:37
  • 1
    @Nisarg I'll be honest here. For some reason a lot of PHP tutorials are terrible, and the ones made by people who have more strength with Java and Android apps than with any kind of server side work are often the worst. A framework like [Laravel is pretty easy to get going with](http://laravelbook.com/laravel-introduction/) and there's a lot of training material out there specifically for it. This is usually a lot higher quality than some random PHP tutorial based on techniques that are obsolete. The Laravel authentication system and Eloquent ORM will help you stay productive. – tadman Aug 25 '16 at 06:58
  • @tadman Alright, thank you very much. I'll be sure to check it out. – Nisarg Aug 25 '16 at 19:29
  • @tadman Currently, I'm using my IP address to communicate with the server (http://MyIPAddress:ServerPort#/Register.php). However, this will obviously only work within my local WIFI network. Do you know how I can make sure that users can send information to the database regardless of the WIFI network they're connected to, or if they are using cellular data such as 3G / LTE? – Nisarg Aug 25 '16 at 23:54
  • 1
    You need a public web server IP where your PHP code is hosted. Do not expose your database to the general internet. – tadman Aug 26 '16 at 01:06
  • @tadman Okay, thanks. – Nisarg Aug 26 '16 at 18:47

1 Answers1

0

Here's the code I ended up using to send the data to my database within the doInBackground method:

try{ 


            String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                    URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
                    URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");

            URL url = new URL(reg_url);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            // Read Server Response
            while((line = reader.readLine()) != null)
            {
                sb.append(line);
                break;
            }

            Log.e("TAG", sb.toString());

            return sb.toString();


        }catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

Reference: Android login to mysql database

Also turned out the port number I had entered for my server was incorrect. I fixed that as well, and now everything seems to work fine. Thank you to all of you guys for the help!

Community
  • 1
  • 1
Nisarg
  • 397
  • 1
  • 5
  • 14