dev_marshell08
dev_marshell08

Reputation: 1101

How to connect PhoneGap App to MySql Database on the server?

I am trying to build a transit mobile application that has data stored in MySql DB on the server. Since my application is just going to connect to the MySql db and fire query/get the data and show it to the user . I was planning to create it using PhoneGap but i don't understand how will i connect to the MySql DB does phonegap only allow local data storage using SqlLite ? Can someone brief me on the architecture i should take into consideration for building this transit app.

Upvotes: 4

Views: 10022

Answers (2)

Roei Aviad
Roei Aviad

Reputation: 11

You can use AJAX to get json data from your own website. For example, this code is used to get the user's username by his id. JS on your phonegap app:

function getUsername(){
    var id = document.getElementById("textbox").value;
    $.ajax({
        url: "https://www.example.com/json_read?id=" + id,
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert(data.username);
        },
        error: function () {
            alert("Error");
        }
    });
}

PHP on your website:

<?php
require 'db.php';
$id = $_GET['id'];
$sql = $mysqli->query("SELECT * FROM users WHERE id='$id'");
$result = $sql->fetch_assoc();
$object->username = $result['username'];
$json = json_encode($object);

echo $json;
?>

Make sure you are only using it on phonegap so no one can see your source code and play with your database :)

Upvotes: 1

James Wong
James Wong

Reputation: 4619

You can use AJAX in your PhoneGap app to get data from your MySQL DB, you will need a script on your server to handle these calls. CGI/ PHP/ Ruby/ NodeJS etc... all of these will fit the job description.

Upvotes: 5

Related Questions