Apache cordova dengan mysql database

Make mobile app for website. That is, the desired output of articles, users, etc. DB is on the hosting. Own server is not present, so Node.JS does not roll. How do I connect to the database in order to pick up data, please tell me? I would be grateful for an adequate response.

Related questions

  • 5What is GitHub and why you need it?
  • 1How do I get the profiling results without the debug panel?
  • 2Webpack. The Url loader returns a url kosyachny, what's the problem?
  • 1As for Bitrix to see the logs of edits pages?
  • 4What log analyzer for nginx, apache, apache tomcat are using?
  • 2The problem with the software installed in the computer how to solve?
  • 1Why doesn't Paperclip?
  • 1To open a link in chrome when you connect headphones (tasker for Android)?

2 answers

benny43 answered on September 13th 19 at 21:55

Solution

Own server is not present, so Node.JS does not roll.

well, you have a website? So it is possible to create an API to the database.

rubye_Rodriguez answered on September 13th 19 at 21:57

Direct connection to the database from client applications is a very bad idea, anyone can watch anything in your database, and probably even to change something.
Write API.

Find more questions by tags ApacheApache CordovaMySQL

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:

  • MySQL Database Creation
  • Writing PHP code for Serverside
  • 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

Working with MySQL database

Let’s create a new table called course details where, we can store information about courses such as title, duration, and price.we also need to set primary key & auto increment for id

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;

After creating a new table, we need to create simple REST API

Working with PHP code

Let’s create a simple API (no security layer added) for fetching data from MySQL database & display as JSON.here we’re going to create multiple files for insert, delete, update operations. If you want you can merge all files into one single PHP file

Connecting Database Server ( db.php )

This file allows you to connect your MySQL database


    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

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


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";
    }
?>

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


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";
}
?>

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


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"; 
}
?>

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 Parse JSON using Cordova (PhoneGap)


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); 
?>

Connecting JSON with PhoneGap

Insert data using PhoneGap / Apache Cordova ( insert.html )

<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; ">
        <h2 class="title">Insert Databaseh2>
        <a class="button button-clear" href="readjson.html">Read JSONa>
    div><br /><br />
    <div class="list">
        <input type="hidden" id="id" value="" />
        <div class="item">
            <label>Titlelabel>
            <input type="text" id="title" value="" />
        div>
        <div class="item">
            <label>Durationlabel>
            <input type="text" id="duration" value="" />
        div>
        <div class="item">
            <label>Pricelabel>
            <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>

Display / Reading JSON data using PhoneGap ( 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

<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("$" + price + "

" + title + "

" + duration + "

"
); }); }); });
script> head> <body> <div class="bar bar-header bar-positive" style="margin-bottom:80px; "> <a href="index.html" class="button button-clear">Homea> <h2 class="title">Read Database (JSON)h2> div><br /><br /> <ul class="list" id="listview"> ul> body> html>

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

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

<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">Homea>
        <h2 class="title">Update Databaseh2>
        <a class="button button-clear" href="readjson.html">Read JSONa>
    div><br /><br />
    <div class="list">
        <input type="hidden" id="id" value="" />
        <div class="item">
            <label>Titlelabel>
            <input type="text" id="title" value="" />
        div>
        <div class="item">
            <label>Durationlabel>
            <input type="text" id="duration" value="" />
        div>
        <div class="item">
            <label>Pricelabel>
            <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;
}

Known mistakes

  • localhost won’t work in mobile devices, If you’re testing on the 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