android php mysql
To connect an Android app to a MySQL database using PHP, you need to follow these steps:
Create a MySQL database: You can create a MySQL database on a web hosting service or on a local server using software like XAMPP. Once the database is created, you need to create a table and add some data to it.
Create a PHP file: Create a PHP file on your server that will handle the database connection and the queries. Here's an example PHP code:
<?php $host = "localhost"; $user = "username"; $password = "password"; $database = "database_name"; $conn = mysqli_connect($host, $user, $password, $database); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT * FROM table_name"; $result = mysqli_query($conn, $sql); $rows = array(); while ($row = mysqli_fetch_assoc($result)) { $rows[] = $row; } mysqli_close($conn); echo json_encode($rows); ?>Source:www.theitroad.com
This code connects to the MySQL database, selects all the records from a table, and returns the results in JSON format.
- Call the PHP file from your Android app: In your Android app, you can use the
HttpURLConnection
class to call the PHP file and get the results. Here's an example code:
String url = "http://yourdomain.com/yourphpfile.php"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // Set request method con.setRequestMethod("GET"); // Read response BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Parse JSON response JSONArray jsonArray = new JSONArray(response.toString()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String name = jsonObject.getString("name"); // Do something with the data }
This code sends a GET request to the PHP file, reads the response, and parses the JSON data.
That's it! With these steps, you can connect your Android app to a MySQL database using PHP.