Android Tutorial Connect Android to MySQL Database Tutorial

Status
Not open for further replies.
A new more powerful framework is now available: jRDC2.

This tutorial explains the basic concepts required for creating a connection between Android device and a remote server. In this case it is a MySQL database.
A tutorial for connecting to SQL Server is available here.

Android cannot connect directly to the database server (search for JdbcSQL). Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

For this example I've created a new database that lists the countries population. The data was derived from a UN database.

The database includes a single table named "countries" with three columns:
mysql_1.png

PHP Script

The web service is made of a single PHP script running on the same server.
You have several options for the web service implementation. You can create several prepared statements which will be filled with parameters passed in the request.
Or you can take the complete query from the request and pass it to the database server.
There are high security risks with issuing queries received from an unknown user. If your service is public then you will probably want to choose the first option.
You should also make sure to correctly escape the parameters. See this php method: PHP: mysql_real_escape_string - Manual

In our example I've chosen the second option which takes the query and passes it to the database directly.
I've restricted the database user to SELECT queries (in MySQL configuration).

The PHP code:
PHP:
<?php

$databasehost = "localhost";
$databasename = "xxxx";
$databaseusername ="xxxx";
$databasepassword = "xxxx";

$con = mysqli_connect($databasehost,$databaseusername,$databasepassword, $databasename) or die(mysqli_error($con));
mysqli_set_charset ($con , "utf8");
$query = file_get_contents("php://input");
$sth = mysqli_query($con, $query);

if (mysqli_errno($con)) {
   header("HTTP/1.1 500 Internal Server Error");
   echo $query.'\n';
   echo mysqli_error($con);
}
else
{
   $rows = array();
   while($r = mysqli_fetch_assoc($sth)) {
     $rows[] = $r;
   }
   $res = json_encode($rows);
    echo $res;
    mysqli_free_result($sth);
}
mysqli_close($con);
?>
The script takes the query from the POST data and submits it to the database.
The result is then written in JSON format.

B4A code

Our application displays a list of countries. When the user presses on a country, its population is retrieved from the database and displayed.

upload_2016-8-3_13-4-25.png



The code sends the query and then when the result arrives the JSON is parsed and displayed.
Note that in this case the JSON object is made of an array of one or more maps.

Edit: Code updated to use OkHttpUtils2.
 

Attachments

  • MySQL.zip
    8 KB · Views: 17,494
Last edited:

Vern

Member
Licensed User
Longtime User
Is there a way around the error "javax.net.ssl.SSLPeerUnverifiedException: No peer certificate" when trying to connect over https? I can't change the SSL certificate on the server.
 

Adilson Jacinto

Active Member
Licensed User
Longtime User
A new more powerful framework is now available: Remote Database Connector.

This tutorial explains the basic concepts required for creating a connection between Android device and a remote server. In this case it is a MySQL database.
A tutorial for connecting to SQL Server is available here.

Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

For this example I've created a new database that lists the countries population. The data was derived from a UN database.

The database includes a single table named "countries" with three columns:
mysql_1.png

PHP Script

The web service is made of a single PHP script running on the same server.
You have several options for the web service implementation. You can create several prepared statements which will be filled with parameters passed in the request.
Or you can take the complete query from the request and pass it to the database server.
There are high security risks with issuing queries received from an unknown user. If your service is public then you will probably want to choose the first option.
You should also make sure to correctly escape the parameters. See this php method: PHP: mysql_real_escape_string - Manual

In our example I've chosen the second option which takes the query and passes it to the database directly.
I've restricted the database user to SELECT queries (in MySQL configuration).

The PHP code:
PHP:
<?

$databasehost = "localhost";
$databasename = "xxxx";
$databaseusername ="xxxx";
$databasepassword = "xxxx";

$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
$query = file_get_contents("php://input");
$sth = mysql_query($query);

if (mysql_errno()) {
    header("HTTP/1.1 500 Internal Server Error");
    echo $query.'\n';
    echo mysql_error();
}
else
{
    $rows = array();
    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }
    print json_encode($rows);
}
?>
The script takes the query from the POST data and submits it to the database.
The result is then written in JSON format.

Basic4android code

Our application displays a list of countries. When the user presses on a country, its population is retrieved from the database and displayed.

SS-2013-01-29_16.42.32.png


The code sends the query and then when the result arrives the JSON is parsed and displayed.
Note that in this case the JSON object is made of an array of one or more maps.

Edit: Code updated to use HttpUtils2 instead of HttpClient.


Hi Erel, can you give us an example of option 1? and the way that we post string through php too?

Thanks
 

Adilson Jacinto

Active Member
Licensed User
Longtime User
I recommend you to switch to RDC instead.

There are many online tutorials about connecting PHP to MySQL. Sending the data to php is simple with HttpUtils2.

I know you recommend me to switch to RDC, and I really want to use it but I don't know how, but there is much help there :(
 

Adilson Jacinto

Active Member
Licensed User
Longtime User
I recommend you to switch to RDC instead.

There are many online tutorials about connecting PHP to MySQL. Sending the data to php is simple with HttpUtils2.
Can you help Erel? I really need to talk to mysql database using RDC, but I haven't got a clue in how to set it up, I tried to follow a few tutorials but with no success :(
 

Wolli013

Well-Known Member
Licensed User
Longtime User
on error, wat ist wrong

B4A version: 5.20
Parsing code. (0.01s)
Compiling code. (0.04s)
Compiling layouts code. (0.00s)
Generating R file. (0.04s)
Compiling generated Java code. Error
B4A line: 55
Log(Response.GetString(\
javac 1.8.0_25
src\anywheresoftware\b4a\samples\mysql\httputils2service.java:143: error: cannot access ParseException
anywheresoftware.b4a.keywords.Common.Log(_response.GetString("UTF8"));
^
class file for org.apache.http.ParseException not found
 

Helcione Madalena Mendes

New Member
Licensed User
Longtime User
I have a problem, I'm trying to use the sample mysql, the firebird, but I am not having success with the return that is always empty! Can anyone help?

PHP:
<?php
  $host = 'localhost:C:\wamp\www\EAS.FDB';
  if(!( $db = ibase_connect($host,'SYSDBA','masterkey')))
    die ("Erro ao conectar".ibase_errmsg());
    $query = file_get_contents("php://input");
    $sth = ibase_query($query);

   if (ibase_errmsg()) {
      header("HTTP/1.1 500 Internal Server Error");
      echo $query.'\n';
      echo ibase_errmsg();
   }
   else
   {
      $rows = array();
      while($r = ibase_fetch_assoc($sth)) {
             $rows[] = $r;
      }
      print json_encode($rows);
}
?>
 

Alisson

Active Member
Licensed User
Erel, how can create one SELECT?
I create second panel with code:

Sub Panel1_Touch (Action As Int, X As Float, Y As Float)
ExecuteRemoteQuery("SELECT population FROM paises WHERE population='" & lblPopulation & "'", COUNTRY_POPULATION)
' How can extract the data from database?
End Sub
 

opus

Active Member
Licensed User
Longtime User
Hi,
I'm trying to conect to a Database im my local network.
I only get an "Internal Server Error" from Job.Result?

The File is found (when using it without the "php" in the starting line, the code of the php-file is returned)
Do I need to use a User that is allowed the connect from the device where the webserver and the database, or do I have to use as Usere that is allowed to connect from a remote IP? Tested both, same result?

I'm out of ideas?
 

opus

Active Member
Licensed User
Longtime User
I'm sorry for missing my SOLVED statement in here.

My problem got solved by DonManfred and sorex.
I had only recently installed PHP(5.5+), which meant in turn that the used MySQL-code in the PHP-file in post #1 wasn't useable.
Something like would be working:
B4X:
<?php
$sql = new mysqli('localhost', 'database_user', 'database_password', 'database_name');
if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit;
}

$query=file_get_contents("php://input");
$result = $sql->query($query);   
if (!$result) {
  printf("Query failed: %s\n", $mysqli->error);
  exit;
}   
$rows=array()
while($row = $result->fetch_row()) {  
  $rows[]=$row;
}
print json_encode($rows);
$result->close();
$sql->close();
?>
 
Last edited:

Declan

Well-Known Member
Licensed User
Longtime User
I am using an edited version of this tutorial to access a MySQL database on my server.
My PHP script is "istockserver.php" located within "C:\istock\". Full path is : C:\istock\istockserver.php".

What is the correct syntax to replace:
B4X:
job.PostString("http://www.b4x.com/android/countries.php", Query)
to point to my IP address?
something like:
B4X:
job.PostString("197.111.111.111/istock/istockserver.php", Query)
 
Status
Not open for further replies.
Top