On Android we have a lot of databases to use, it's SQLite. But if we want to use MySQL or any other database, then we install it on our own server and use it. These web developers, almost all of whom are familiar with MySQL, MySQL has many web applications to access MySQL from the various applications we build. Today we are going to take a look at a short tutorial on how to save data from Android phone to data server database. And as a server programming language, we will use PHP. If you don't have a server, you can install local PHP and MySQL. It is easy to install and install manually using WAMP server. If there is no idea about this, then you can see the following.
Easy Way to send Data To Database From Android + PHP + MySQL |
To send data from an Android application to a MySQL database using PHP, you can follow these general steps:
Here is a sample code that demonstrates the process:
Android code:
Copy code
private void sendDataToServer(String data1, String data2) {
String url = "http://yourdomain.com/insert.php";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// handle response from server
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// handle error
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("data1", data1);
params.put("data2", data2);
return params;
}
};
queue.add(stringRequest);
}
PHP code:
php
Copy code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sanitize the data received from the Android application
$data1 = mysqli_real_escape_string($conn, $_POST['data1']);
$data2 = mysqli_real_escape_string($conn, $_POST['data2']);
// Insert data into the database
$sql = "INSERT INTO myTable (column1, column2) VALUES ('$data1', '$data2')";
if ($conn->query($sql) === TRUE) {
echo "Data inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Note: Remember to replace the database credentials, table name, column names, and URL in the code with your own values.