Phonegap PHP MySQL Example | Apache Cordova

phonegap-php-mysql-example
phonegap php mysql example
PhoneGap PHP MySQL example

Phonegap PHP MySQL Example

In this article, I would like to write an article about PhoneGap with PHP & MySQL. we’ll see how to perform CRUD (Create, Read, Update, Delete) operations with MySQL Database.

Step By Step Guide:

  1. MySQL Database Creation
  2. Writing PHP code for Serverside
  3. Writing Jquery code for PhoneGap / Apache Cordova side

Dependencies: PHP, MySQL, JQuery

Learn More about PHP & MySQL http://www.w3schools.com/php/php_mysql_intro.asp or http://www.tutorialspoint.com/php/php_and_mysql.htm

1. MYSQL DATABASE CREATION

In this example, I’m going to create some basic database & table (course_details) with following fields such as id, title, price.

phonegap-mysql-database
PhoneGap-MySQL-database
CREATE TABLE `course_details` (
`id` int(1) NOT NULL,
 `title` varchar(25) NOT NULL,
 `duration` varchar(50) NOT NULL,
 `price` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

ALTER TABLE `course_details` ADD PRIMARY KEY (`id`);
ALTER TABLE `course_details` MODIFY `id` int(1) NOT NULL AUTO_INCREMENT;

WRITING PHP CODE (SIMPLE WEBSERVICE)

1. Connecting Database Server (db.php)

<?php
 header("Access-Control-Allow-Origin: *");
 $con = mysqli_connect("localhost","root","root","phonegap_demo") or die ("could not connect database");
?>

NOTE

header("Access-Control-Allow-Origin: *"); use to allow cross domains

2. Insert data into MySQL database using PHP (insert.php)

This code will receive data from the mobile  / PhoneGap Apache Cordova using POST method & It’ll insert data to MySQL, If it is successful it will return ok as output otherwise error as output

<?php
 include "db.php";
 if(isset($_POST['insert']))
 {
 $title=$_POST['title'];
 $duration=$_POST['duration'];
 $price=$_POST['price'];
 $q=mysqli_query($con,"INSERT INTO `course_details` (`title`,`duration`,`price`) VALUES ('$title','$duration','$price')");
 if($q)
  echo "success";
 else
  echo "error";
 }
 ?>

3.Update Database using PHP (update.php)

This code will receive data from the mobile  / PhoneGap / Apache Cordova using POST method & It’ll Update data to MySQL with respect to course_id, If it is successful it will return ok as output otherwise error as output


<?php
 include "db.php";
 if(isset($_POST['update']))
 {
 $id=$_POST['id'];
 $title=$_POST['title'];
 $duration=$_POST['duration'];
 $price=$_POST['price'];
 $q=mysqli_query($con,"UPDATE `course_details` SET `title`='$title',`duration`='$duration',`price`='$price' where `id`='$id'");
 if($q)
 echo "success";
 else
 echo "error";
 }
 ?>

4. Delete data from Database using PHP (delete.php)

This code will receive data from the mobile  / PhoneGap / Apache Cordova using POST method & It’ll delete data to MySQL with respect to course_id, If it is successful it will return ok as output otherwise error as output


<?php
 include "db.php";
 if(isset($_GET['id']))
 {
 $id=$_GET['id'];
 $q=mysqli_query($con,"delete from `course_details` where `id`='$id'");
 if($q)
 echo "success";
 else
 echo "error";
 }
 ?>

5. Displaying Data using JSON (json.php)

For displaying data from MySQL database to Phonegap / Apache Cordova, we need to create json based output. we can display JSON data to phonegap using Jquery getJSON or AJAX method. Read more https://phonegappro.com/tutorials/how-to-parse-read-json-using-phonegap-apache-cordova/


<?php
include "db.php";
$data=array();
$q=mysqli_query($con,"select * from `course_details`");
while ($row=mysqli_fetch_object($q)){
 $data[]=$row;
}
echo json_encode($data);
?>

Writing Jquery code for PhoneGap / Apache Cordova Side

1. Insert data using Phonegap / Apache Cordova (insert.html)

insert data to mysql phonegap
insert data to MySQL PhoneGap

<html>
<head>
 <link rel="stylesheet" type="text/css" href="css/ionic.css">
 <script type="text/javascript" src="js/jquery.js"></script>
 <script type="text/javascript">
 $(document).ready(function()
 {
 $("#insert").click(function(){
 var title=$("#title").val();
 var duration=$("#duration").val();
 var price=$("#price").val();
 var dataString="title="+title+"&duration="+duration+"&price="+price+"&insert=";
 if($.trim(title).length>0 & $.trim(duration).length>0 & $.trim(price).length>0)
 {
 $.ajax({
 type: "POST",
 url:"http://localhost/phonegap/database/insert.php",
 data: dataString,
 crossDomain: true,
 cache: false,
 beforeSend: function(){ $("#insert").val('Connecting...');},
 success: function(data){
 if(data=="success")
 {
 alert("inserted");
 $("#insert").val('submit');
 }
 else if(data=="error")
 {
 alert("error");
 }
 }
 });
 }return false;
 });
 });
 </script>
</head>
<body>
 <div class="bar bar-header bar-positive" style="margin-bottom:80px;">
 <h1 class="title">Insert Database</h1>
 <a class="button button-clear" href="readjson.html">Read JSON</a>
 </div><br/><br/>
 <div class="list">
 <input type="hidden" id="id" value=""/>
 <div class="item">
 <label>Title</label>
 <input type="text" id="title" value=""/>
 </div>
 <div class="item">
 <label>Duration</label>
 <input type="text" id="duration" value=""/>
 </div>
 <div class="item">
 <label>Price</label>
 <input type="text" id="price" value=""/>
 </div>
 <div class="item">
 <input type="button" id="insert" class="button button-block" value="Insert"/>
 </div>
 </div>
</body>
</html>

2. Display / Reading JSON data using PhoneGap / Apache Cordova (readjson.html)

It’ll display list the data from the server as a link. when you click the link, it’ll redirect you to form.html. you can update data from form.html

read data from mysql phonegap
read data from MySQL PhoneGap

<html>
<head>
 <link rel="stylesheet" type="text/css" href="css/ionic.css">
 <script type="text/javascript" src="js/jquery.js"></script>
 <script type="text/javascript">
 $(document).ready(function()
 {
 var url="http://localhost/phonegap/database/json.php";
 $.getJSON(url,function(result){
 console.log(result);
 $.each(result, function(i, field){
 var id=field.id;
 var title=field.title;
 var duration=field.duration;
 var price=field.price;
 $("#listview").append("<a class='item' href='form.html?id="+id+"&title="+title+"&duration="+duration+"&price="+price+"'><span class='item-note'>$"+price+"</span><h2>"+ title + " </h2><p>"+ duration +"</p></a>");
 });
 });
 });
 </script>
</head>
<body>
 <div class="bar bar-header bar-positive" style="margin-bottom:80px;">
 <a href="index.html" class="button button-clear">Home</a>
 <h1 class="title">Read Database (JSON)</h1>
 </div><br/><br/>
 <ul class="list" id="listview">
 </ul>
</body>
</html>

3. Updating MySQL database from Phonegap / Apache Cordova (form.html)

This example shows how to update data and delete data from database using Phonegap / Apache Cordova

upddate data from mysql phonegap
update data from mysql phonegap
update data from mysql phonegap
update data from MySQL PhoneGap

<html>
<head>
 <link rel="stylesheet" type="text/css" href="css/ionic.css">
 <script type="text/javascript" src="js/jquery.js"></script>
 <script type="text/javascript" src="js/geturi.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
 var id = decodeURI(getUrlVars()["id"]);
 var title = decodeURI(getUrlVars()["title"]);
 var duration = decodeURI(getUrlVars()["duration"]);
 var price = decodeURI(getUrlVars()["price"]);
 $("#id").val(id);
 $("#title").val(title);
 $("#duration").val(duration);
 $("#price").val(price);
 $("#update").click(function(){
 var id=$("#id").val();
 var title=$("#title").val();
 var duration=$("#duration").val();
 var price=$("#price").val();
 var dataString="id="+id+"&title="+title+"&duration="+duration+"&price="+price+"&update=";
 $.ajax({
 type: "POST",
 url:"http://localhost/phonegap/database/update.php",
 data: dataString,
 crossDomain: true,
 cache: false,
 beforeSend: function(){ $("#update").val('Connecting...');},
 success: function(data){
 if(data=="success")
 {
 alert("Updated");
 $("#update").val("Update");
 }
 else if(data=="error")
 {
 alert("error");
 }
 }
 });
 
 });
 $("#delete").click(function(){
 var id=$("#id").val();
 var dataString="id="+id+"&delete=";
 $.ajax({
 type: "GET",
 url:"http://localhost/phonegap/database/delete.php",
 data: dataString,
 crossDomain: true,
 cache: false,
 beforeSend: function(){ $("#delete").val('Connecting...');},
 success: function(data){
 if(data=="success")
 {
 alert("Deleted");
 $("#delete").val("Delete");
 }
 else if(data=="error")
 {
 alert("error");
 }
 }
 });
 
 });
 });
 </script>
</head>
<body>
 <div class="bar bar-header bar-positive" style="margin-bottom:80px;">
 <a href="index.html" class="button button-clear">Home</a>
 <h1 class="title">Update Database</h1>
 <a class="button button-clear" href="readjson.html">Read JSON</a>
 </div><br/><br/>
 <div class="list">
 <input type="hidden" id="id" value=""/>
 <div class="item">
 <label>Title</label>
 <input type="text" id="title" value=""/>
 </div>
 <div class="item">
 <label>Duration</label>
 <input type="text" id="duration" value=""/>
 </div>
 <div class="item">
 <label>Price</label>
 <input type="text" id="price" value=""/>
 </div>
 <div class="item">
 <input type="button" id="update" class="button button-block" value="Update"/>
 <input type="button" id="delete" class="button button-block" value="Delete"/>
 </div>
 </div>
 
</body>
</html>

This is all about PhoneGap PHP MySQL example for performing CRUD Operation. If you’ve any doubts feel free to comment below

geturi.js

this code is used for getting value from URL.like site.com/file?

E.g http://localhost/file.html?name=sundar&country=india

if you want to get name and URL, you can use like this

var name = gerUrlVars()[“name”];

var country = gerUrlVars()[“country”];


function getUrlVars() {
 var vars = [], hash;
 var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
 for (var i = 0; i < hashes.length; i++) {
 hash = hashes[i].split('=');
 vars.push(hash[0]);
 vars[hash[0]] = hash[1];
 }
 return vars;
}

COMMON MISTAKES

  • localhost won’t work in mobile devices, If you’re testing on device you need to host your file or you need to connect with IP address
  • Make sure you’ve included geturi.js
  • Download the files and try
  • Still facing any issues ?, Feel free to comment below
  • Was this Helpful ?
  • Yes   No
  • Dipesh

    is it possible to crud function phonegap to ms-sql?

  • Enny Rodríguez

    Hi Sundaravel, i tried to replicate this,

    i created an index.html that call readjson.html, compiled apk and when i load the aplication in my phone or web browser and it doesn´t show any data in insert.html neither insert data… i´m using wamp server.

    i noted that you call in form.html ionic.css is necessary? y must use ionic to create this project?. and GetUri.js is necessary where can i find it? sorry i’m new in mobile.

    • Hi @ennyrodrguez:disqus, You don’t need to add ionic (ionic only for UI). GetUri.js is for get value from url (using GET method). I updated with my code. please check

      • Enny Rodríguez

        Perfect!, thanks!! it works perfect!, now i’m ready to work in my project thanks to this tutorial.

        Greetings from venezuela!

        • Jason Lihou

          @ennyrodrguez:disqus. Are you able to provide a zip of your working files? Thanks.

      • Sam

        Dear Sundara, I tried all above and created apk. Downloaded apk from phonegap and installed but it doent work on mobile. Its working in XAMPP with server path (http://www.domain.com/json.php). (All files has been uploaded to server, Updated data path aswell then created apk.)

        Kindly help.

  • Sam

    Hi, I tried all above and created apk. Downloaded apk from phonegap and installed but it doent work on mobile. Its working in XAMPP.

    • @disqus_RywqPb2IbN:disqus, Please Check following:
      1) Whitelist Plugin
      2) Cross Domain Origin

      • Sam

        Where do I check this?

        • add and remove cordova-plugin-whitelist . Search my previous article for debugging with GapDebug for debugging purpose

          • Sam

            Ok let me search and get back to you if I stuck again.

          • Sam

            Thanks Sundara, Finally its working on ios and android.

          • Welcome 🙂

          • Issa Jad

            Hello Sam
            I have the same problem can you provide me the solution 🙂

          • Jason Lihou

            @Sam, can you supply the working code as a downloadable zip? I’ve got data being inserted to database, but cannot do anything else, like read the data back, delete or update. I’d be very grateful. Thank you.

      • Sam

        https://github.com/apache/cordova-plugin-whitelist

        Do I need to download all this and put into plugin folder?

  • napester

    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

  • Jimson Jose

    i have tried to build the same but seems to be not working, it just says that Connecting,
    initially came to know that there was a line missing element. (i dont know weather it requires or not. but implemented.
    and checked weather on button click press “data is pushed or not i have even tried that to check with alert” that to seems to be working..

    Can you please suggest me what went wrong.

    • Make sure you’ve changed the url & configured everything correctly

      • Jason Lihou

        I’ve changed relevant url’s but I get the same “Connecting…”. It does insert to database, but I cannot then read them back from ‘readjson.html’, or update or delete. Please reply, thank you.

  • Yash Mishra

    Hi sir,
    I have used the above given technique to con phonegap, but I am connectecting it to to a remote sql server.
    1) So will there be any changes in code?
    2) what is the use of geturi.js file?

    • You need to change the URL of your own server

      • Jason Lihou

        How is the ‘geturi.js’ file used? Do we just add the file as you have provided it, or are other modifications required?

  • Fabien F. Hanna

    Hi Sundara,

    Can you please provide me with the download link ? so that i can follow the code in an easier way ?

    Thank you

    • No changes in code. you can just copy paste, It’ll work

      Anyway I’ll update soon

      • Jason Lihou

        Are you still planning an update? 🙂

  • Issa Jad

    Hi Sundara,
    it dosent work for me to insert or show i think is src=”js/jquery.js” this is missing so its not working
    can you post for me here what this file contain !
    regards

    • Hey, you need to include jquery file (download from jquery website)

    • Jason Lihou

      Try adding this. 🙂

  • Nickson Nyakambi

    Where do we get the jquery.js file?

    • download form jquery website

      • Nickson Nyakambi

        and what about jq.js and auth.js

  • Andy

    Hi Sundaravel, great tutorial – Thanks

    • Welcome @disqus_VkcpK6GBo4:disqus, Thanks for your feedback

  • Issa Jad

    Hello Sundaravel
    I have problem that this code dosent work in my phone but work in xamp server
    i search for solution and some one tel me to use XMLHttpRequest to retrive data
    can you please help me how i can make this with your code
    thanks in advance 🙂

    • @issajad:disqus, localhost, won’t work on your mobile, please host your file on server

      • Issa Jad

        i host them in the server but not work in phone after make the apk file please help

      • Issa Jad

        I tried all above and created apk. Downloaded apk from phonegap and installed but it doent work on mobile.

  • OpenMerchantAccount

    Or, skip all that and just use http://www.mysqljs.com ?

    • Issa Jad

      how can does this work to get data and post from the server can you explain more and give example ?

    • Thanks @openmerchantaccount:disqus, I’ll also try this

  • Uchenna

    Hi Sundaravel,

    Thanks for the excellent post. My problem is I don’t have a web server at this point. Does it mean I can’t test a Cordova App using localhost on a different port? The VC Ripple emulator uses localhost:4400. I have XAMPP setup to use localhost:8080. I tried an AJAX request to http://127.0.0.1:8080/signin.php” and also
    “http://localhost:8080/signin.php”
    while running Apache through XAMPP with same domain and port number and I don’t get any responses back. Also, what are the right settings for config.xml as far as access origin goes? Does it mean I can’t test remote database without a real web server?
    Thanks

    • Without hosting also you can check, you just run your client-side (mobile html pages) in your browser

  • Nyoman Lukas

    Hi Sundaravel,

    first of all thanks for the great tutorial! I am refering to the “insert”-function:
    The code is working in my own project. But even though the values are inserted to my db the button remains on “Connecting…”.

    Do you have any idea what could be the reason for this?

    (First, I tried your code with exactly the same db like in your example. Also here the button remains on “Connecting…”)

    Thanks!

    • Nyoman Lukas

      Ok, I think the problem is that “mysql_query” is deprecated and php does not just send back “OK” but also an error message.

      • @nyomanlukas:disqus, Yes, Maybe…

        But you can fix that using jQuery

  • Ashraf

    you have mistake in file update.php:
    $course_id=$_POST[‘course_id’];
    it must be
    $course_id=$_POST[‘id’];

    • Thanks for your information

      • Kaj Hutchison

        I downloaded files today and this mistake is still within update.php, wich caused this to fail on update, then discovered other mistake in update.php —
        where `course_id`=’$course_id’
        must be
        where `id`=’$course_id’

        and yes this solved my problem

    • Updated !!

  • Ashraf

    usually i test my app on Genymotion and mobile also , i do not have web server , so how i test my app with php&mysql with localhost wamp

  • Ashraf

    usually i test my app on Genymotion and mobile also , i do not have web server , so how i test my app with php&mysql with localhost wamp as apk on phonegap?

  • Olfa Harrouchi

    Hello,

    I have to make a web application with only phonegap/Apache Cordova (not test on a mobile). I did not understand or I have to create these files in the directory WWW of WAMP Server or in the WWW directory of my project cordova. I tried to create a project on c: wamp www but it doesn’t work. Thank you guide me well.

    • you can create where ever you want

      • Olfa Harrouchi

        thank you for your response

        • Olfa Harrouchi

          When i try to insert the button display connecting… and don’t insert the new course.

          • arun pathrose

            i also have the same problem . insertion and reading is fine,please help…………

  • ilham arditya

    im using phonegap mobile app.. database mysql using xampp. but when insert data, in button “Connecting”. my query fix. but still “connecting”
    why?

    • does the value inserted on db??
      check:
      If you’re testing on mobile, you cannot connect using “localhost”, so you need to use IP address

      • Anna Amalfi

        I have the same problem, when click on insert button, it show always “connecting” and I used IP address, what is the problem?

        • May be, you need to add domain with whitelist plugin

          • Anna Amalfi

            only on the mobile, it don’t work. With chrome and with phonegap desktop, it works

  • kamlesh katpara

    your code is not working on my end, when I click on any button nothing happens

    • Please make sure, you’ve included jQuery file

      • kamlesh katpara

        I have included the jquery.mobile-1.4.1.min.js, and testing on visual studio, still it doesn’t work, and why is the js code not in index.js ?

        • It should work.
          Note : For user understanding purpose, I’ve included all codes in respective files. If you want you can write @ index.js

          • kamlesh katpara

            I appreciate your work buddy, I have tried every step, still don’t know why it didn’t work, if possible can you please keep this sample files for download so that i can debug and see what I am doing wrong.

          • foufou H

            Hi, Did you mean we create a file in js directory and then we create a form in index.html or what. can you explain more ?
            Thanks

  • foufou H

    The code doesn’t work for me. I emulate the code on android emulator. Could you explain more where directory i write the code?

  • Kaj Hutchison

    Looks like a good tutorial, unfortunately as with all phonegap tutorials, you have taken it for granted, that beginners like me get what your talking about.. Be nice if you actually covered the few holes in your tutorial, i.e where the html files go, also seems to be one file in your example with no NAME, this is why I couldn’t make use of it… Shame

    • Thanks for your valuable feedback !! I’ll update that

      • Kaj Hutchison

        Thanks Sundara, have revisted your project & downloaded files , it works quite well except for the update database, for update i only get error, checked & re-checked , cannot find why (i’m using wehosting & mysql)… Any ideas ?
        Thanks

        • Kaj Hutchison

          I found two mistakes in update.php —

          $course_id=$_POST[‘course_id’];
          it must be
          $course_id=$_POST[‘id’];

          (which you’ve already been told about & said you updated, no you haven’t.

          other mistake in update.php is —
          where `course_id`=’$course_id’
          must be
          where `id`=’$course_id’

          ……. and yes this solved my problem

  • Sumit Kumawat

    public class MainActivity extends DroidGap
    {
    public void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    super.loadUrl(“file:///android_asset/www/index.php”);
    }
    i just load php file but show code…how to load php file

  • Adrian Bodolan

    Hello, can you tell me please why after I build the code as an apk (with phonegap cloud), the query doesn’t work anymore? Even after I forwarded the port for mysql and connected to the external ip, the data isn’t retrieved… I also replaced all “localhost” with external ip (which again was forwarded to be accessed from outside). Please, help me, I don’t know what to do…

    • Can you please check you console for error!!. so that i can help you!!

      • robkman

        Hi I have the same problem. I got everyting working via the browser on mobile. It inserts to the db and reads it out. after building with apk with phonegap build it doesnt connect to the database.

  • irwan Dwiyanto

    Nice good tutorial, i wil try…

  • Manoj Bhanu

    i installed phonegap … and tried with XAMPP… insert options working fine … but i dont know why UPDATE and DELETE is not working …

  • Anisha

    Thanks……finally i got how to connect cordova app to mysql

    • Welcome 🙂

      • Anisha

        then how cordova app connect to mysql database ondeviceready function for device….bcoz this code not working in emulator

  • Kamz Yewr Valentino

    You are just ignoring this bug in your code that the update and delete functions don’t work @@sundara_vel:disqus

    • Update and delete functions are working. Make sure you included geturi.js

  • Prudhvi raj

    Thanks @sundara_vel:disqus for such a nice tutorial. but i a have so many doubts regarding phonegap becz iam new to learnig this technology.. I have assigned small internal project tooo as a fresher.
    I have created pages run it throw phonegap app to connect with ip address:port no. and i can generate .apk file also. my only problem is with database.???? if i have to run .php files throw wamp, i just reside my pg project at “c:/wamp/www/phonegap_project” and i can connect with DB throw it but not in phonegap app. I have doubt that how DB files will generate into .apk file? when we will run apk file how it will connect with DB internally?? otherwise is it possible to connect with SQLlite?? but i dont know sqllite.. these all stop my project to move forward. Please help me in deeply. waiting for your valuable response. I dont know my questions are correct r not but iam in confusion mode. Thanks

  • Zion

    Hi..This code is works for web but dose not working on android mobile..
    why is that..?

  • arun pathrose

    i tried yhe above example . for hosting i use xampp and ngrork .but can’t access the server.
    plz help

  • 수학전문학원파스칼

    Thank u for very useful sample
    I learn lots by code
    but i have a problem

    Download link was sent to swordkang@hanmail.net.

    I do not receive link email

    Several times i subscribed but link email does not come

    Please send me downloaf link

  • Ankur arora

    Its Working fine on Phonegap Desktop and Phonegap Mobile, but when i build apk and run on android mobile and click on insert button ,nothing happens

  • Michael

    I just requested the downloadable files 2 hours ago but didn’t get it till now.
    How long does it take to sent the Mail with the Files?
    Tutorial is very nice, thanks so much.
    Will buy other tutorials on this site soon.
    Kind regards.
    Michael

    • sorry for inconvenience, please check spam folder, or try again

      • Michael

        thanks for reply 🙂
        checked spam folder and tried again twice with different mail accounts.
        still didn’t get it.
        any ideas?
        kind regards.
        michael

      • Michael

        still doesn’t work 🙁

  • Sudhanwa Alur

    hey,the code is working perfectly fine in browser..but when i convert it to app,it always shows connecting .please help me out

    • If you’re building from PhoneGap Build, Checkout Whitelist plugin

  • Syed Wajahat Imam

    hello, Sir with due respect i ant to say this code is working fine but the issue is it is not converting it self into application as i run it on emulator or my personal device it shows connecting…. please help me out…

    • If you’re building from PhoneGap Build or any cloud services, Checkout Whitelist plugin

  • bilal

    hello, this code not works from my android device. when i make .apk of the html files and install it in my android. it is not performing any task like insert and select. it works perfectly when i use it from desktop. i host my file on azure

    • Hello @disqus_RTvthmQrxW:disqus , If you’re building from PhoneGap Build, Checkout Whitelist plugin

  • Marote Thabang

    If I want to interact with an online server, AFTER phonegap build how can I achieve this?
    I get errors after running the phonegap build because the application is not hosted. Is it possible to run a phonegap app from a domain?

    • Yes, it’s possible.

      Note:
      1) If you’re hosting you app on domain, loading time will be slow

  • Piyush Tripathi

    Hello Sundaravel
    I have problem that this code dosent work in my phone apk file but work in wamp server and also work on webserver were database and php file are stored. i’m trying to create user login panel.
    i search for solution and some one tel me to use XMLHttpRequest to retrive data
    can you please help me how i can make this with your code
    thanks

  • Naj Shazalie

    Hello sir, this code works on my laptop when i click on the server link, but when i connect it to my iphone, it wont work

    Can you help?

    • Localhost won’t work on laptop. use IP address instead.

  • Omar Elbaga

    This is great but don’t the php files have to be hosted on a server and not packaged in the PhoneGap app.

    In this case how can you use Ajax to Read from php files hosted on another server. Wouldn’t this be cross domain and not allowed?

    • 1) PHP -> Host on your server
      2) ajax & Read JSON -> Pack as App

      Note: We already enabled cross domain

      • Paul

        Yours: url:”http://localhost/phonegap/database/insert.php”,

        For example, what should the above line of code be for someone who is hosting the database on a web server?

        Mine: url:”http://111.222.333.444 (server IP?)/home/phonegap/database/insert.php”,

        Server IP instead of localhost and then follow whatever directory the file is stored in?

  • This line: header(“Access-Control-Allow-Origin: *”);

    It means that anyone would be able to pull requests from your database. Is there a way to limit it to your phonegapp App?

    Not sure how you would do that when I don’t think your phonegapp app has an IP address

    • header(“Access-Control-Allow-Origin: *”); -> You’re allowing GET,POST, REQUEST, PUT …etch methods

      If you want to restrict only from app, use API key concepts

  • Paul

    Where should your php files be stored? html, js and css are stored inside the www folder in a PhoneGapProject directory and the .sql file is stored on a web server or locally via MAMP/WAMP.

    Should the php files be stored in the file manager of a cPanel on the web server?

    PLEASE, can anyone answer me this.

    • The php files should be on a live server hosted somewhere. Probably the same server that hosts the database, but not on a local server. Has to be a live server on a web hosting company.

      • Paul

        Thanks mate! Appreciate it.

  • Frank

    Thanks. Great tutorial!

    What further implementation would you need to do for the app
    to be able to work offline as well as online? How would you synchronise the
    data from the local device to the mysql database? Does anyone know how to
    achieve this?

    • Yes, you can use SQLite for Sync operations

      • Frank

        Great! I will take a look. Thanks

  • Tommy Klausen

    Hi!

    Great tutorial.

    I am not receiving any download links on this. Nowhere to be found in my mailsystem.

    • Please Check your spam folder too

      • Tommy Klausen

        Nothing there 🙂

      • Tommy Klausen

        Hi. For some reason I can`t get anything displayed in the listview. Only the text “Read Database (JSON)” text is.
        I try to read data from one of my tables and running the php that handles the select in the browser works fine, but not when I implement it in PhoneGap.

        I`m not really that used to JS but is the ready-function called automatically?
        I don`t need to call it myself?

  • Tommy Klausen

    Hi.
    I think I have partially fixed this.
    I got to read the content from the database by adjusting the references in the script section referencing the js and css files properly.
    But when I try to run this on my Windows Phone, the PG developer app shuts down when extracting the content.

    • @disqus_cxT4qIdyDz:disqus You cannot test localhost inside mobile, use IPaddress instead

      • Tommy Klausen

        Hi.
        I use the ip address.
        It works on my Android device but not on my WP.

      • boulouayz

        I had been test on localhost and this work !
        Thnx for this useful tutorial

  • Haizad

    hi, thanks for the tutorial!. but I have a problem here.
    When I click on the button , it says “connecting…” and the page keep static without any output… do you have the solution ?
    # I use free web hosting as server, but I am not sure whether it is the cause.

  • Rasel

    Update Button not working.when i click update it say connecting.otherwise everything is ok.When mobile folder upload web update work in web server but not work app.Thank

  • Hatim ali asghar

    Great help sir , I have having problem that what should be the url instead of this url: “http://localhost/Rohan/CURD/insert.php”, I have upload my php files and database to 000webhost so what url should i mention ?

  • Hillary Chweya

    Hello
    I trust that you’re well.
    Thank you for the tutorial.
    I have a question that needs your expertise

    Based on “https://phonegappro.com/tutorials/phonegap-php-mysql-example/” how can I have on the ‘homepage’
    this example?
    I have four categories of stuff like below

    1. Vegetables
    2. Fruits
    3. Cereals
    4. Animal Products

    when I click, say,
    Vegetables
    I get a listview of vegetables available eg
    Cabbages : 100
    Kale: 300
    ….

    and when I click, say
    Fruits
    I get a listview of fruits eg.
    Oranges : 50
    PawPaw: 500
    ….

    I welcome better ideas too. Thank you for your time.

  • karthik rajan

    Hi Sundara vel,

    Whether ajax is the only way to get data from the php or any other alternative is there because using ajax will tend to have security issues know? how to overcome that.. whether it is a good practice to get data from the server using ajax from different domain.

    • No, we have some other plugin like http to to that

  • Daniel E. Speckman

    I downloaded your files. This tut was posted on Dec 22, 2015

    There is an “index.html”

    Do I replace the Phonegap “index.html” file with the downloaded one?

    Also, is this tutorial the same one as this posted on June 26, 2015?

    https://phonegappro.com/tutorials/phonegap-login-system-using-php-mysql/

    It has a different file structure with a “signup.html” and a “login.html” files. Which files are the correct ones?

  • Alain

    the download is somehow not working — I put in my email address but no email with the link came in…

  • Raja Siva

    Hi, Its working good localhost and how to android apk file convert?

    • Build your apk

      • Raja Siva

        sorry i am new developer, please explain briefly. thank you.

        • I wrote some article, plz check

        • Shayne

          Use adobe phonegap.

  • Shubhajeet Saha

    Hi I have downloaded codes, changed urls whereever required with a domain url I am using for testing and build apk using intel XDK. But its stucked at Connecting…. Not proceeding further. Nor am able to see any error log at server. Kindly help me to resolve the issue.

    • Check your console for error

    • Samuel Cruz-Lara

      I’m having exactly the same problem with an iOS cordova-based application: stocked at Connecting… I’m using MAMP.

  • adhy

    thanks for sharing… i have downloaded your source code and working perfectly,…

  • Shayne

    Great tutorial, but I have a question. When displaying/reading data, how would I be able to pass a variable to the php function in order to filter my results?

  • SeveBarnett

    Thank you!

  • MAYUR PANCHAL

    i make a ionic app it works in browser but it is not working in my android device…like data insert in online database is inserted but when i installed app and try in my android device then i insert the data it not insertde. now what to do?

    • Kruti patel

      Bhai also me check.,
      you can use ajax or javascript angular

      • MAYUR PANCHAL

        ajax call in javascript

        • Kruti patel

          To ghare Jato re..??

          • MAYUR PANCHAL

            ok tubi

    • Please check console for errors

      • MAYUR PANCHAL

        console me error nahi aa rahi

        • English please

          • Kruti patel

            i also check that console but not here any error shown

          • MAYUR PANCHAL

            failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

            now what to do?

          • Possible errors:
            1) Connection with web service (using network tab)
            2) Re-check your source code
            3) check about whitelist
            4) Use IP address instead of localhost

          • MAYUR PANCHAL

            reply me fast

  • MAYUR PANCHAL

    i cant insert data in android application. what to do now?

  • crazzyking

    with cordova its working fine but im dong this with monaca and onsen UI in that its not working can you help ?

  • Mustafa Kamel

    i have faced problem when i made insert the program hung at connecting and not insert any thing . why ? ? and when i want to try it at mobile the my computer IP put it at url as it 192.168.1. .. or not ?

  • ANBARASAN ANBU

    insert working properly but update is noy

  • jae

    it works fine on desktop phonegap but when i try on my android device it stuck at connecting and can’t insert successfully. Any idea why is this happening? i’ve include device ready function.

    • Ashley Jean Maagad Austria

      same problem

    • Danya Faisal

      localhost won’t work in mobile devices, If you’re testing on device you need to host your file or you need to connect with IP address

      • Justinn Monton

        any sample or instructions on how to connect with IP address? hosting the file seems to be costly. I am just a student and my project needs phonegap and xampp

  • Haribabu Dayalan

    Hi, i am facing some issue, please help me. check this screen short.
    https://screencast.com/t/HngYrVjp

  • Danya Faisal
  • Danya Faisal

    Mr Sundara you said that localhost won’t work on phonegap application (iphone device), and i should host the file, did you mean i should only host php-code folder that contain all php file and can i know what is the best hosting website ?

    • Haribabu Dayalan

      Hey Danya, whats your skype id?

      • Danya Faisal

        Idnt have skype , do you know how can i solve it?
        please Email me mm-mmu@hotmail.com

  • Ashley Jean Maagad Austria

    I have a problem, someone help.
    i made this into an APK, via adobe could compiler. and it cant connect to the database. (database is already cloud storage, and i used the IP to access it)

    also, i tested the code with the web browser and works perfectly.

  • Oliver

    Hello
    How can you make the information on the Database hidden on the json.php file ?
    If somewhere is going to the link (like this : http://www.mywebside.com/test/json.php) they see all inputs on the database. Thats not really cool 😉

    • PHP is server side language. By going to that URL, the end user only sees the output after the script runs on the server side. PHP is not like HTML, CSS, Javascript, etc where the script is visible to anyone and is rendered in the browser. This is completely safe and the correct way of connecting to a database.

  • Dexter Crawford

    Hi. I am new to app development. I downloaded your files, and uploaded them to my server. One folder with the html files, js and css folders, and another folder with the php.
    I changed the url in in the index file to http://MyDomainName/TestFolder/insert.php, and changed the db file to my database and password on my server.
    The index page is loading, But when I click the insert button, I only get connecting.., and nothing happens. I checked my console, and nothing is there.

    Am I missing something?

  • kamlakar adepu

    insert is working but read JSON is not working
    in app