Nicero Nicero - 28 days ago 24
Javascript Question

Phonegap. Cannot accessing remote mysql database

I'm doing my first experiments with Phonegap. I would like to build an app that retrieves data from a MySql server, but it seems that the problem is that I'm not able to connect to my dB.

When I build web sites it's easy. I use PHP and the following code:

$conn = new mysqli($servername, $username, $password);


where
$servername
is
localhost


But with Phonegap
localhost
won't work of course so I have to use the
hostname
or the
IP address
.

And here's the problem. I have a VPS with a IP and the host name is, suppose, vps.my-domain.com. Both won't give me access to the MySql db and I don't understand why.

The following strings report:

'SQLSTATE[HY000] [2005] Unknown MySQL server host 'vps.my-domain.com:3306' (20)'

$conn = new mysqli("xxx.yy.kkk.qqq", $username, $password);
$conn = new mysqli("vps.my-domain.com", $username, $password);


My code (HTML+Jquery+Ajax+PHP) works fine when I run it on my VPS and I use
localhost
but it fails when I use the
IP address
or the
hostname
.

I also tried with mySQLjs:

MySql.Execute(
"http://xxx.yy.kkk.qqq",
"username",
"password",
"phonegap",
"select * from test",
function (data) {
console.log(data)
});


but still without success.

The demo code I found at mySQLjs works fine, so I'm pretty sure I'm missing something about my connection.

How do I access my MySql db using the
IP address
or the
hostname
rather than using
localhost
? Is there a configuration that should be I set on my VPS?

Answer

SOLVED

After many temptatives I worked it out.

By default remote access to the MySQL database server is disabled for security reasons.

1- You need to edit MySQL configuration file and allow access from origins different than localhost.

nano /etc/mysql/my.cnf

2- change the line bind-addressto:

bind-address = your_ip_number          i.e. bind-address = xxx.yy.qqq.tt

3- restart MySQL:

/etc/init.d/mysql restart

4- with PHPMyAdmin create a user which host is your ip address so that it seems as:

phonegap@your_ip_number

Below there's the code (HTML+PHP+CONFIG.XML)

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Fetch MySQL data into Phonegap app</title>

        <script src="jquery.min.js"></script>
        <script src="phonegap.js"></script>     <!-- When you build the app with build.phonegap.com remove the phonegap.js file from the package you are going to upload but keep its reference --> 

    </head>
    <body>
        HELLO WORLD!

        <div id="output"></div>

        <script>
            $(document).ready(function($){          

               var output = $('#output');

               $.ajax({
                   url: 'http://your_domain.com/get.php',     // FULL PATH!
                   dataType: 'jsonp',
                   jsonp: 'jsoncallback',
                   timeout: 3000,
                   success: function(data, status){
                      $.each(data, function(i,item){ 
                         var landmark = '<h1>'+item.title+'</h1>'
                         + '<p>'+item.description+'<br>'
                         + item.url+'</p>';

                         output.append(landmark);
                      });
                   },
               error: function(){
                  output.text('There was an error loading the data.');
               }
           });
       });
    </script>
</body>

PHP

<?php
    header("Access-Control-Allow-Origin: *");

   $db_username = 'the_user_you_created';
   $db_password = 'the_password';
   $db_name     = 'the_db_name';
   $db_host     = 'your_ip_number';

   $mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
   if ($mysqli->connect_error) {
       die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
   }

   // Run the query and fetch the data. $html contains the result

   // Convert it to JSON and remember to add the 'jsoncallback' string
   echo $_GET['jsoncallback'] . '(' . json_encode($html) . ');';

?>

CONFIG.XML This is the config file for Phonegap

<?xml version="1.0" encoding="UTF-8" ?>
<widget xmlns   = "http://www.w3.org/ns/widgets"
    xmlns:gap   = "http://phonegap.com/ns/1.0"
    id          = "com.phonegap.example"
    versionCode = "10" 
    version     = "1.0.0" >

    <!-- versionCode is optional and Android only -->

    <name>Your app</name>

    <description>
        My first MySql connection with Phonegap
    </description>

   <author href="http://www.my_domain.com">
       Its me
   </author>

   <!-- The two following lines make the difference! Important -->
   <gap:plugin name="cordova-plugin-whitelist" source="npm"/>

   <!-- In my esperience only * worked. Using the IP address (http://xxx.yy.qqq.tt or simply xxx.yy.qqq.tt) did not work -->
   <access origin="*" subdomains="true" />

</widget>

ZIP the HTML file, the XML file and JQuery.min.js and upload the package to build.phonegap.com using your account.

Hope I helped someone!

Comments