Adding data to MySQL from android using php service
In this tutorial you will learn how to add data to your remote MySQL database, inside of your android application. This is really useful, if you’re trying to use one database for your website and your application, or when you need to keep a statistics track. The solution given below is the simplest and it can be implemented in around 10 minutes. A basic android and php knowledge is required in order to understand the steps.
First of all let’s set the server(php) side. You need a simple script that will be listening for calls and, if the link contains the needed variables everything will be inserted into our database.
Here is how your listener should be looking like:
[code language=”php”]
<?php
// Adding data to MySQL from android using php service
$host = "localhost";
$dbName = "name_goes_here";
$dbUsername = "username_goes_here";
$dbPassword = "password_here";
$isCompleted = 0;
$dateTime = $_GET[‘date’];
$param = $_GET[‘param’];
$clientIP = ‘mobile’;
$email = $_GET[’email’];
$ownerEmail = $_GET[‘identifier’];
$mysqli = new mysqli($host, $dbUsername, $dbPassword, $dbName);
$mysqli->set_charset(‘utf8’);
$insertReminder = "INSERT INTO YOUR_TABLE(date_time, param, is_complete, client_ip, email, ownerEmail)"
. " VALUES(?, ?, ?, ?, ?, ?)";
try {
if ($stmt = $mysqli->prepare($insertReminder)) {
$stmt->bind_param(‘ssisss’, $dateTime, $param, $isCompleted, $clientIP, $email, $ownerEmail);
$stmt->execute();
$stmt->close();
}
} catch (Exception $ex) {
http_response_code(401);
}
$mysqli->close();
// Adding data to MySQL from android using php service
[/code]
If we send a request to the URL containing the above code it will check for the variables and if everything is ok the script will insert a row into the database.
But wait a minute! How is it possible to make this request from an android device?
The solution is really simple! The only requirement is that the device should be connected to the internet – so don’t forget to check for connectivity in your activity!
Here is how to pass the parameters from the android device to your remote MySQL database:
[code language=”java”]
// Adding data to MySQL from android using php service
@Override
protected void onPreExecute() {
Dialog.setMessage("Sending request!");
Dialog.show();
}
protected Long doInBackground(URI… urls) {
try {
String s = unformatedDate + " " + selectedTime.getText().toString();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM-dd-yyyy HH:mm");
Date date = new Date();
try {
date = simpleDateFormat.parse(s);
} catch (ParseException ex) {
ex.printStackTrace();
}
DateFormat gmtFormat = new SimpleDateFormat("MMMM-dd-yyyy HH:mm");
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("your_website_here")
.appendPath("android") // sub directory – if existing
.appendPath("agent.php") // the name of the php file containing the listener
.appendQueryParameter("date", gmtFormat.format(date))
.appendQueryParameter("param", reminderTxt.getText().toString())
.appendQueryParameter("email", emailTxt.getText().toString())
.appendQueryParameter("identifier", deviceRecognition);
String myUrl = builder.build().toString();
URL url = new URL(myUrl);
URLConnection urlConnection = url.openConnection();
InputStream in = urlConnection.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer… progress) {
// do nothing
}
protected void onPostExecute(Long result) {
Dialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(NotificanaScreen.this);
builder.setMessage("Your reminder was saved and you will receive an email at the chosen time")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
// Adding data to MySQL from android using php service
[/code]
In the code above you are building the url along with the needed parameters and sending a request to your server. You also should check, if the server is available just before you post the request
Congratulations! Now you know how to communicate with your server from your android device! Adding data to MySQL from android using php service was never easier!