QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Create a Intel XDK APP with PHP and MySQL Backend

Create a Intel XDK APP with PHP and MySQL Backend

xdk-php-mysql

This post is a part 48 of Intel XDK Complete Tutorial post series.

PHP and MySQL are most popular backend technologies ever. 82% of mobile apps using PHP and MySQL as their backend server. In this tutorial we will see how to create PHP web services and call them using Intel XDK. And also how to execute MySQL queries using Intel XDK.

Introduction to Web Services

A web service is a method of communication between two process over a network. REST web services are those web services which use HTTP to communicate over the network. Some popular REST web service request and response formats are SOAP, JSON, XML, XML-RPC etc.

SOAP, JSON, XML etc formats are used to request or send some data to an remote application. Whereas XML-RPC format is used when you want to call a function of a remote application.

Create a JSON REST Web Service using PHP

Let’s create a REST web service which uses JSON format to send some requested data.

Here is an PHP code which sends an PHP array as JSON object to the Intel XDK app

if(isset($_GET["names"]))
{
    //checks the format client wants
    if($_GET["names"] == "json")
    {
        $name_and_age = array("Name1" => 12, "Name2" => 34, "Name3" => 67);

        //sets the response format type
        header("Content-Type: application/json");

        //converts any PHP type to JSON string
        echo json_encode($name_and_age);   
    }
    else
    {
        //web service not found
        header("HTTP/1.0 404 Not Found");
    }
}
else
{
    header("HTTP/1.0 404 Not Found");
}

Success output would be

{"Name 1":12,"Name 2":34,"Name 3":67}

Above we created a HTTP GET web service but you can also create POST, DELETE, PUT etc web services. POST is used if you want to send data to server.

If web service is not found then we are sending 404 not found header in response. There are various HTTP response status codes available for use in various different cases. Here is the list

100 - "Continue",
101 - "Switching Protocols",
200 - "OK",
201 - "Created",
202 - "Accepted",
203 - "Non-Authoritative Information",
204 - "No Content",
205 - "Reset Content",
206 - "Partial Content",
300 - "Multiple Choices",
301 - "Moved Permanently",
302 - "Found",
303 - "See Other",
304 - "Not Modified",
305 - "Use Proxy",
306 - "(Unused)",
307 - "Temporary Redirect",
400 - "Bad Request",
401 - "Unauthorized",
402 - "Payment Required",
403 - "Forbidden",
404 - "Not Found",
405 - "Method Not Allowed",
406 - "Not Acceptable",
407 - "Proxy Authentication Required",
408 - "Request Timeout",
409 - "Conflict",
410 - "Gone",
411 - "Length Required",
412 - "Precondition Failed",
413 - "Request Entity Too Large",
414 - "Request-URI Too Long",
415 - "Unsupported Media Type",
416 - "Requested Range Not Satisfiable",
417 - "Expectation Failed",
500 - "Internal Server Error",
501 - "Not Implemented",
502 - "Bad Gateway",
503 - "Service Unavailable",
504 - "Gateway Timeout",
505 - "HTTP Version Not Supported"

Here is how you can make a request to the web service using JavaScript running in XDK

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://domain/?names=json", false);
xhr.onload = function(){
    if(xhr.status == 200)
    {
        var json_string = xhr.responseText;
        var json = JSON.parse(json_string);
        intel.xdk.notification.alert(json.Name1, "Name 1");
    }
    else if(xhr.status == 404)
    {
        intel.xdk.notification.alert("Web Service Doesn't Exist", "Error");
    }
    else
    {
        intel.xdk.notification.alert("Unknown error occured while connecting to server", "Error");
    }
}
xhr.send();

Intel XDK doesn’t have any AJAX Same Origin Policy therefore you can make a AJAX request to any domain of your wish.

Output in APP would be

Screen Shot 2015-03-05 at 1.02.11 am

Running MySQL Queries using XDK

There is no way to directly connect and query MySQL using XDK. If you want to directly connect and query MySQL then you have to write your own XDK plugin which can send MySQL protocol requests.

Developers use web services as a mid layer to communicate with MySQL. Here is an example PHP web service which retrieves all the rows of a table and returns to the client i.e., XDK,

<?php

if(isset($_GET["get_rows"]))
{
    //checks the format client wants
    if($_GET["get_rows"] == "json")
    {
        $link = mysqli_connect("host", "username", "password", "db_name");

        /* check connection */
        if (mysqli_connect_errno()) {
            echo mysqli_connect_error();
            header("HTTP/1.0 500 Internal Server Error");
            exit();
        }

        $query = "SELECT * FROM wp_users";

        $jsonData = array();

        if ($result = mysqli_query($link, $query)) {

            /* fetch associative array */
            while ($row = mysqli_fetch_row($result)) {
                $jsonData[] = $row;
            }

            /* free result set */
            mysqli_free_result($result);

            //encode to JSON format
            echo "{"rows":". json_encode($jsonData) . "}";
        }
        else {

            echo "{"rows":". json_encode($jsonData) . "}";
        }

        /* close connection */
        mysqli_close($link);
    }
    else
    {
        header("HTTP/1.0 404 Not Found");
    }
}
else
{
    header("HTTP/1.0 404 Not Found");
}


?>

Sample output would be

{"rows": [["12","narayanrusty"],["23","qnimate"]]}

Here rows are output as JavaScript multidimensional array. Here also we are using JSON format.

Here is how you can make a request to the web service using JavaScript running in XDK

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://domain?get_rows=json", false);
xhr.onload = function(){
    alert(xhr.responseText);
    if(xhr.status == 200)
    {
        var json_string = xhr.responseText;
        var json = JSON.parse(json_string);
        intel.xdk.notification.alert(json.rows[0][0], "Name 1");
    }
    else if(xhr.status == 404)
    {
        intel.xdk.notification.alert("Web Service Doesn't Exist", "Error");
    }
    else
    {
        intel.xdk.notification.alert("Unknown error occured while connecting to server", "Error");
    }
}
xhr.send();

Conclusion

We saw how to create web services using PHP which can be consumed by XDK. We also saw how to use web services to talk to MySQL. You can go ahead and build a REST POST web service to upload some file or send some kind of data to server for storage or any other purpose.

Mar 5, 2015Narayan Prusty
How Does WordPress Cache Data?Get WordPress Post Date as Current Time Difference
Comments: 23
  1. lam
    5 years ago

    how to connect my apps to my database

    ReplyCancel
  2. jalil
    6 years ago

    How to connect mysql xdk intel?

    ReplyCancel
  3. Mario
    6 years ago

    Hi Narayan,
    In test mode and emulate HTTP requests works fine.
    When i compile, generate APK file and install it in Android cell phone, it doesn´t works.
    What should be hapenning?

    Thanks.

    ReplyCancel
  4. Kristoffer Ryan Supan
    6 years ago

    Hi do you also have any example on GET data on a SQL Server?

    ReplyCancel
  5. john
    6 years ago

    this maybe can help a little bit https://www.youtube.com/watch?v=XvkoPP05wtk

    ReplyCancel
  6. Franco Esp
    6 years ago

    Hi, thanks for your tutorial. It would be great if you were to publish a guide on how to integrate the web service in Intel XDK . It is pretty hard to configure the three required files ( apiconfig.json , … ) . Thank you

    ReplyCancel
  7. Roberta
    6 years ago

    I seerchad a bunch of sites and this was the best.

    ReplyCancel
  8. Michael
    7 years ago

    Is there any video all this tutural ?

    ReplyCancel
  9. ajanth
    7 years ago

    can anyone tell me where to do these codes in xdk, as i am new to this platform and also for the ide…
    thank u in advance..

    ReplyCancel
  10. Napester
    7 years ago

    It maybe seems a weird question but what if some user knows the url of the php file for inserting something on the mysql database. It will destroy the backend with useless data.
    How to secure this point

    ReplyCancel
  11. Nick
    7 years ago

    HI, please doa POST example too. I need to see how to send data to a database and files to a server. Please.

    Nick

    ReplyCancel
  12. ygns
    7 years ago

    How to sync my hosted website directly in XDK, so i dnt hv to make .apk for the 1st tym!

    ReplyCancel
  13. kanu
    7 years ago

    Dear Sir,
    i am new in intel xdk. please tell me how can i connect my simple login form with php and xampp database

    ReplyCancel
  14. Emmanuel
    7 years ago

    Ok, it work fine but:
    Are there a way to handle the network error?

    (Not a HTTP error, but connection error etc…).
    The XDK console you can read the network error but JavaScript can’t hadle error with try catch.

    ReplyCancel
  15. Dhazo
    7 years ago

    Hi Sir, im a beginner with Intel XDK. could you please provide the source code for connecting to mysql??

    ReplyCancel
  16. Gollavilli
    7 years ago

    Can we have hbase as a back end for mobile app developed in xdk?

    ReplyCancel
  17. Alfonso
    7 years ago

    Download source code?

    ReplyCancel
  18. Samson Rapando
    7 years ago

    Hi, I am interested in mobile app development, HTML5 to be specific. I also use Intel XDK. I would like to know the best way to make an app save data on the device storage. Like images, and text data. Locally without the need of an online server. Lets say an app that keeps the financial records of a person. Any way, a link to a tutorial or a detailed reply will be appreciated

    ReplyCancel
  19. Stefan Powell
    7 years ago

    I am a young new web developer, with adequate knowledge on PHP and MySql Database, i have just began using Intel XDK but i am still unable to create a php file that connects to my local mysql database, can someone please provide me with some assistance.

    ReplyCancel
    • Robe
      7 years ago

      Please take a look to http://www.w3schools.com/php/php_mysql_connect.asp. There you might find to set up the connection. Also, check http://www.connectionstrings.com/mysql/

      ReplyCancel
  20. kheri
    7 years ago

    please can you show how to create the REST POST web service that send data

    ReplyCancel
  21. Charles Torres
    7 years ago

    Please Mr. Narayan.. help me… the web service don’t work when built and install .apk file in cell phone.

    My blog with problem detail:

    http://rc-code.blogspot.com/2015/03/intel-xdk-android-apk-problem-in.html

    ReplyCancel
  22. Ramiro
    7 years ago

    Olá Narayan,

    Meu nome é Ramiro, sou brasileiro. Estou tentando executar este tutorial (IntelXDK com PHP e MySQL), mas não estou conseguindo. Não sei onde devo salvar o arquivo no IntelXDK: App.js, Innit.js…? Você pode me ajudar?

    ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

8 years ago 23 Comments Cordova
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Introduction to Web Services
  • Create a JSON REST Web Service using PHP
  • Running MySQL Queries using XDK
  • Conclusion
Related Articles
  • Sending SMS using Intel XDK
  • Uploading Files and Showing Progress using Intel XDK
  • Pull To Refresh For Phonegap App
  • Database Design For Storing Chat Messages
  • Local Database Storage using Intel XDK
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license