0

I'm new to Android. Don't know which part has gone wrong. The thing is I'm unable to send the data to the server in Android Studio.

This is the error I'm facing

Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\students\connection.php:6 Stack trace: #0 C:\xampp\htdocs\students\add_employee.php(2): include() #1 {main} thrown in C:\xampp\htdocs\students\connection.php on line 6

The code goes like this...

Main Activity

public class MainActivity extends AppCompatActivity  {

Button b1;
EditText e1;
private ProgressDialog pDialog;
private JSONObject json;
private int success=0;
private HTTPURLConnection service;
private String strname ="";
//Initialize webservice URL
private String path = "http://localhost/student/add_employee.php";





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b1 = (Button) findViewById(R.id.button);
    e1 = (EditText) findViewById(R.id.editText9);

    service=new HTTPURLConnection();


    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!e1.getText().toString().equals("") ) {
                strname = e1.getText().toString();

                //Call WebService
                new PostDataTOServer().execute();
            } else {
                Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
            }


            Intent intent = new Intent(MainActivity.this, Student1.class);
            startActivity(intent);

    }
});
}

private class PostDataTOServer extends AsyncTask<Void, Void, Void> {

String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
@Override
protected void onPreExecute() {
    super.onPreExecute();

    pDialog = new ProgressDialog(MainActivity.this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
    postDataParams=new HashMap<String, String>();
    postDataParams.put("name", strname);

    //Call ServerData() method to call webservice and store result in response
    response= service.ServerData(path,postDataParams);
    try {
        json = new JSONObject(response);
        //Get Values from JSONobject
        System.out.println("success=" + json.get("success"));
        success = json.getInt("success");

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}
@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    if (pDialog.isShowing())
        pDialog.dismiss();
    if(success==1) {
        Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
    }
}
}
}

HTTPURLConnection

public class HTTPURLConnection {
String response="";
URL url;
public String ServerData(String path,HashMap<String, String> params) {
    try {
        url = new URL(path);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);


        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(params));

        writer.flush();
        writer.close();
        os.close();
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            //Log.d("Output",br.toString());
            while ((line = br.readLine()) != null) {
                response += line;
                Log.d("output lines", line);
            }
        } else {
            response = "";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}}

My PHP code

add_employee.php

<?php
include('connection.php');
$emp_name=$_POST["name"];
$success=0;
$status="Active";
$sql = "INSERT INTO  `employee` (`emp_name`) 
VALUES ('$emp_name')";
if(mysql_query($sql))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysql_close($con);
?>

connection.php

<?php
 $dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);    
if(!$conn) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('student');
?>
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    1. **Don't** use the **deprecated and insecure** `mysql_*`-functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead. 2. **You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php)** and should really use [Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead of concatenating your queries, which can be used if you use the above mentioned MySQLi or PDO. – M. Eriksson Aug 18 '17 at 06:26
  • 1
    Possible duplicate of [Why shouldn't I use mysql\_\* functions in PHP?](https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – B. Desai Aug 18 '17 at 06:28
  • If you're getting error messages, start by searching on those messages. This have been asked and answered multiple times already. – M. Eriksson Aug 18 '17 at 06:30
  • This is more of a PHP question than an Android question. Consider testing the API in a REST client like Postman first? – Basant Singh Aug 18 '17 at 06:31
  • 1
    Thanks!! When i used MYSQLi I am getting these type of error Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\students\connection.php on line 10 Notice: Undefined index: name in C:\xampp\htdocs\students\add_employee.php on line 4 Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\students\add_employee.php on line 10 {"success":0} – Hirshit S M Aug 18 '17 at 06:34
  • Welcome to Stack Overflow, please take a time to go through [the welcome tour](https://stackoverflow.com/tour) to know your way around here (and also to earn your first badge), read how to [create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and also check [How to Ask Good Questions](https://stackoverflow.com/help/how-to-ask) so you increase your chances to get feedback and useful answers. – Valentun Aug 18 '17 at 06:34
  • 1
    Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\students\connection.php on line 10 Notice: Undefined index: name in C:\xampp\htdocs\students\add_employee.php on line 4 Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\students\add_employee.php on line 10 {"success":0} – Hirshit S M Aug 18 '17 at 06:34
  • Can I know whether android code part is correct?? – Hirshit S M Aug 18 '17 at 06:47
  • You should [read the documentation about mysqli](http://php.net/manual/en/book.mysqli.php) and you should also do as I suggested, search for any error message you get. SO isn't a substitute for research or reading the docs. – M. Eriksson Aug 18 '17 at 06:56
  • ^ It is worth adding those errors to the question itself, Hirshit. Please use the formatting tools provided (e.g. `>` quote device). – halfer Aug 21 '17 at 14:45

0 Answers0