We will see here how to insert android data to MYSQL database using PHP with PHP Data Objects ( PDO ) method. Here , I used example of Firebase Cloud Messaging (FCM) . The FCM SDK generates a registration token for the client app instance. To send push notification to client app first you need to store this registration token in your database during app installation. We will discuss here in detail about data insertion from android to mysql/php, why to use PHP Data objects(PDO).
You can store any data like EditText field data like name , email and other data like android device id, mac address etc to insert from android app client to mysql database. But I will discuss here only about how to insert FCM registration token into mysql database. If you want to know more about FCM and push notifications then see the post FCM Send Push Notification Using PHP .
MyInstanceIDListenerService.java:
This class extends FirebaseInstanceIdService and generate unique registration token for a android device. We have to send this registration token to server. See the following code snippet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
package in.nfluence.nfluencemovies; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.util.ArrayList; import java.util.List; public class MyInstanceIDListenerService extends FirebaseInstanceIdService { /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. Note that this is also called * when the InstanceID token is initially generated, so this is where * you retrieve the token. */ // [START refresh_token] @Override public void onTokenRefresh() { // Get updated InstanceID token. String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d("nfmovies FCM", "Refreshed token: " + refreshedToken); // TODO: Implement this method to send any registration to your app's servers. sendRegistrationToServer(refreshedToken); } private void sendRegistrationToServer(String refreshedToken) { try { Log.d("MainActivity", "in try:"); HttpClient httpclient=new DefaultHttpClient(); HttpPost httppost=new HttpPost("http://192.168.1.8/nFluenceMovies/database/insertfcm.php"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(0); nameValuePairs.add(new BasicNameValuePair("fcmid",refreshedToken)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = httpclient.execute(httppost, responseHandler); Log.d("MainActivity", "INSERT:" + response); //response suceess:1 on success } catch (Exception e) { e.printStackTrace(); } } } |
You need to connect your app client to web server. Here I used XAMPP server for connection between app client to php server to better understand. We have to make HTTP POST request here to send data from app to server. Here HttpPost(url) used to connect and send data. BasicNameValuePair has two parameters . POST name and it’s value. Here in code we are sending ‘fcmid’ as a HTTP POST reqeust and it’s value ‘refreshedToken’.
The method httpclient.execute(httppost, responseHandler) execute the HTTP POST request and send data to server which returns the response String. We can test with response string whether data received on server side or not.
PHP PDO(PHP Data Objects):
The PHP Data Objects (PDO) extension is interface for accessing databases in PHP. There are many advantages of PDO over MYSQL and MYSQLi. The main two advantages of PDO are:
- PDO supports 12 different database systems. Suppose for any reason you changing database(mysql to other like Oracle, ODBC, PGSQL, Microsoft SQL Server ) then you have to also change in code !. But if you are using PDO then there is change in only database connection code. No necessary to change entire code of your project.
- If you are using prepared statements in PDO then you can easily protect your data from SQL injection attacks.
We strongly recommend you that don’t use mysql_query() syntax to execute SQL queries. Hence it is not secure. Migrate your code to PDO and use latest version of PHP i.e. PHP7 .
connectandroid.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $servername = "localhost"; $username = "root"; $password = ""; $database="nf_movies"; try { $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> |
If you are using other than mysql database then there is only little change in connection like:
1 |
$conn = new PDO("sybase:host=$servername;dbname=$database", $username, $password);//sybase database system. |
1 |
$conn = new PDO("sqlite:my/database/path/database.db");// sqlite database system. |
insertfcm.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php $getfcm=$_POST['fcmid']; include "connectandroid.php"; try{ $conn->beginTransaction(); $statement = $conn->prepare("INSERT INTO tblcustomer(fcm_id) VALUES (:fcm_id)"); $statement->bindParam(':fcm_id', $fcm_id); $fcm_id=$getfcm; $statement->execute(); echo 1; //send suceess response on app logcat $conn->commit(); } catch(PDOException $e) { // roll back the transaction if something failed $conn->rollback(); echo "Error: " . $e->getMessage(); } $conn = null; ?> |
Using $_POST[‘fcmid’] you will get registration token of app client. Then insert this token in database. See the above code I have used prepared statement to secure data from SQL injection attacks. Send the response to app client to acknowledge that you have received token from client app.
The beginTransaction() and rollback() methods are used to rollback your actions if any issue were found. for example, if you sending and inserting more than thousand of user input data like emails, names in database and suddenly some issue occurred like no internet connection or load on server then it automatically rollback your last sql query execution. Later, you can send or execute same action without any worry about last failed action !.
In this way you can insert FCM registration token in database. If you want to send push notifications to all this registration token then you can see the post FCM Send Push Notification Using PHP . If you have any question regarding this post then feel free to comment below.